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"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/PrettyPrinter.h"
25 #include "clang/AST/Stmt.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/IdentifierTable.h"
29 #include "clang/Basic/Module.h"
30 #include "clang/Basic/Specifiers.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Frontend/FrontendDiagnostic.h"
33 #include "llvm/Support/ErrorHandling.h"
36 using namespace clang;
38 Decl *clang::getPrimaryMergedDecl(Decl *D) {
39 return D->getASTContext().getPrimaryMergedDecl(D);
42 // Defined here so that it can be inlined into its direct callers.
43 bool Decl::isOutOfLine() const {
44 return !getLexicalDeclContext()->Equals(getDeclContext());
47 TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
48 : Decl(TranslationUnit, nullptr, SourceLocation()),
49 DeclContext(TranslationUnit), Ctx(ctx), AnonymousNamespace(nullptr) {
50 Hidden = Ctx.getLangOpts().ModulesLocalVisibility;
53 //===----------------------------------------------------------------------===//
54 // NamedDecl Implementation
55 //===----------------------------------------------------------------------===//
57 // Visibility rules aren't rigorously externally specified, but here
58 // are the basic principles behind what we implement:
60 // 1. An explicit visibility attribute is generally a direct expression
61 // of the user's intent and should be honored. Only the innermost
62 // visibility attribute applies. If no visibility attribute applies,
63 // global visibility settings are considered.
65 // 2. There is one caveat to the above: on or in a template pattern,
66 // an explicit visibility attribute is just a default rule, and
67 // visibility can be decreased by the visibility of template
68 // arguments. But this, too, has an exception: an attribute on an
69 // explicit specialization or instantiation causes all the visibility
70 // restrictions of the template arguments to be ignored.
72 // 3. A variable that does not otherwise have explicit visibility can
73 // be restricted by the visibility of its type.
75 // 4. A visibility restriction is explicit if it comes from an
76 // attribute (or something like it), not a global visibility setting.
77 // When emitting a reference to an external symbol, visibility
78 // restrictions are ignored unless they are explicit.
80 // 5. When computing the visibility of a non-type, including a
81 // non-type member of a class, only non-type visibility restrictions
82 // are considered: the 'visibility' attribute, global value-visibility
83 // settings, and a few special cases like __private_extern.
85 // 6. When computing the visibility of a type, including a type member
86 // of a class, only type visibility restrictions are considered:
87 // the 'type_visibility' attribute and global type-visibility settings.
88 // However, a 'visibility' attribute counts as a 'type_visibility'
89 // attribute on any declaration that only has the former.
91 // The visibility of a "secondary" entity, like a template argument,
92 // is computed using the kind of that entity, not the kind of the
93 // primary entity for which we are computing visibility. For example,
94 // the visibility of a specialization of either of these templates:
95 // template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
96 // template <class T, bool (&compare)(T, X)> class matcher;
97 // is restricted according to the type visibility of the argument 'T',
98 // the type visibility of 'bool(&)(T,X)', and the value visibility of
99 // the argument function 'compare'. That 'has_match' is a value
100 // and 'matcher' is a type only matters when looking for attributes
101 // and settings from the immediate context.
103 const unsigned IgnoreExplicitVisibilityBit = 2;
104 const unsigned IgnoreAllVisibilityBit = 4;
106 /// Kinds of LV computation. The linkage side of the computation is
107 /// always the same, but different things can change how visibility is
109 enum LVComputationKind {
110 /// Do an LV computation for, ultimately, a type.
111 /// Visibility may be restricted by type visibility settings and
112 /// the visibility of template arguments.
113 LVForType = NamedDecl::VisibilityForType,
115 /// Do an LV computation for, ultimately, a non-type declaration.
116 /// Visibility may be restricted by value visibility settings and
117 /// the visibility of template arguments.
118 LVForValue = NamedDecl::VisibilityForValue,
120 /// Do an LV computation for, ultimately, a type that already has
121 /// some sort of explicit visibility. Visibility may only be
122 /// restricted by the visibility of template arguments.
123 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
125 /// Do an LV computation for, ultimately, a non-type declaration
126 /// that already has some sort of explicit visibility. Visibility
127 /// may only be restricted by the visibility of template arguments.
128 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
130 /// Do an LV computation when we only care about the linkage.
132 LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
135 /// Does this computation kind permit us to consider additional
136 /// visibility settings from attributes and the like?
137 static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
138 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
141 /// Given an LVComputationKind, return one of the same type/value sort
142 /// that records that it already has explicit visibility.
143 static LVComputationKind
144 withExplicitVisibilityAlready(LVComputationKind oldKind) {
145 LVComputationKind newKind =
146 static_cast<LVComputationKind>(unsigned(oldKind) |
147 IgnoreExplicitVisibilityBit);
148 assert(oldKind != LVForType || newKind == LVForExplicitType);
149 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
150 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
151 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
155 static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
156 LVComputationKind kind) {
157 assert(!hasExplicitVisibilityAlready(kind) &&
158 "asking for explicit visibility when we shouldn't be");
159 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
162 /// Is the given declaration a "type" or a "value" for the purposes of
163 /// visibility computation?
164 static bool usesTypeVisibility(const NamedDecl *D) {
165 return isa<TypeDecl>(D) ||
166 isa<ClassTemplateDecl>(D) ||
167 isa<ObjCInterfaceDecl>(D);
170 /// Does the given declaration have member specialization information,
171 /// and if so, is it an explicit specialization?
172 template <class T> static typename
173 std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
174 isExplicitMemberSpecialization(const T *D) {
175 if (const MemberSpecializationInfo *member =
176 D->getMemberSpecializationInfo()) {
177 return member->isExplicitSpecialization();
182 /// For templates, this question is easier: a member template can't be
183 /// explicitly instantiated, so there's a single bit indicating whether
184 /// or not this is an explicit member specialization.
185 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
186 return D->isMemberSpecialization();
189 /// Given a visibility attribute, return the explicit visibility
190 /// associated with it.
192 static Visibility getVisibilityFromAttr(const T *attr) {
193 switch (attr->getVisibility()) {
195 return DefaultVisibility;
197 return HiddenVisibility;
199 return ProtectedVisibility;
201 llvm_unreachable("bad visibility kind");
204 /// Return the explicit visibility of the given declaration.
205 static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
206 NamedDecl::ExplicitVisibilityKind kind) {
207 // If we're ultimately computing the visibility of a type, look for
208 // a 'type_visibility' attribute before looking for 'visibility'.
209 if (kind == NamedDecl::VisibilityForType) {
210 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
211 return getVisibilityFromAttr(A);
215 // If this declaration has an explicit visibility attribute, use it.
216 if (const auto *A = D->getAttr<VisibilityAttr>()) {
217 return getVisibilityFromAttr(A);
220 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
221 // implies visibility(default).
222 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
223 for (const auto *A : D->specific_attrs<AvailabilityAttr>())
224 if (A->getPlatform()->getName().equals("macosx"))
225 return DefaultVisibility;
232 getLVForType(const Type &T, LVComputationKind computation) {
233 if (computation == LVForLinkageOnly)
234 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
235 return T.getLinkageAndVisibility();
238 /// \brief Get the most restrictive linkage for the types in the given
239 /// template parameter list. For visibility purposes, template
240 /// parameters are part of the signature of a template.
242 getLVForTemplateParameterList(const TemplateParameterList *Params,
243 LVComputationKind computation) {
245 for (const NamedDecl *P : *Params) {
246 // Template type parameters are the most common and never
247 // contribute to visibility, pack or not.
248 if (isa<TemplateTypeParmDecl>(P))
251 // Non-type template parameters can be restricted by the value type, e.g.
252 // template <enum X> class A { ... };
253 // We have to be careful here, though, because we can be dealing with
255 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
256 // Handle the non-pack case first.
257 if (!NTTP->isExpandedParameterPack()) {
258 if (!NTTP->getType()->isDependentType()) {
259 LV.merge(getLVForType(*NTTP->getType(), computation));
264 // Look at all the types in an expanded pack.
265 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
266 QualType type = NTTP->getExpansionType(i);
267 if (!type->isDependentType())
268 LV.merge(type->getLinkageAndVisibility());
273 // Template template parameters can be restricted by their
274 // template parameters, recursively.
275 const auto *TTP = cast<TemplateTemplateParmDecl>(P);
277 // Handle the non-pack case first.
278 if (!TTP->isExpandedParameterPack()) {
279 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
284 // Look at all expansions in an expanded pack.
285 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
287 LV.merge(getLVForTemplateParameterList(
288 TTP->getExpansionTemplateParameters(i), computation));
295 /// getLVForDecl - Get the linkage and visibility for the given declaration.
296 static LinkageInfo getLVForDecl(const NamedDecl *D,
297 LVComputationKind computation);
299 static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
300 const Decl *Ret = nullptr;
301 const DeclContext *DC = D->getDeclContext();
302 while (DC->getDeclKind() != Decl::TranslationUnit) {
303 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
304 Ret = cast<Decl>(DC);
305 DC = DC->getParent();
310 /// \brief Get the most restrictive linkage for the types and
311 /// declarations in the given template argument list.
313 /// Note that we don't take an LVComputationKind because we always
314 /// want to honor the visibility of template arguments in the same way.
315 static LinkageInfo getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
316 LVComputationKind computation) {
319 for (const TemplateArgument &Arg : Args) {
320 switch (Arg.getKind()) {
321 case TemplateArgument::Null:
322 case TemplateArgument::Integral:
323 case TemplateArgument::Expression:
326 case TemplateArgument::Type:
327 LV.merge(getLVForType(*Arg.getAsType(), computation));
330 case TemplateArgument::Declaration:
331 if (const auto *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
332 assert(!usesTypeVisibility(ND));
333 LV.merge(getLVForDecl(ND, computation));
337 case TemplateArgument::NullPtr:
338 LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility());
341 case TemplateArgument::Template:
342 case TemplateArgument::TemplateExpansion:
343 if (TemplateDecl *Template =
344 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
345 LV.merge(getLVForDecl(Template, computation));
348 case TemplateArgument::Pack:
349 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
352 llvm_unreachable("bad template argument kind");
359 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
360 LVComputationKind computation) {
361 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
364 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
365 const FunctionTemplateSpecializationInfo *specInfo) {
366 // Include visibility from the template parameters and arguments
367 // only if this is not an explicit instantiation or specialization
368 // with direct explicit visibility. (Implicit instantiations won't
369 // have a direct attribute.)
370 if (!specInfo->isExplicitInstantiationOrSpecialization())
373 return !fn->hasAttr<VisibilityAttr>();
376 /// Merge in template-related linkage and visibility for the given
377 /// function template specialization.
379 /// We don't need a computation kind here because we can assume
382 /// \param[out] LV the computation to use for the parent
384 mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
385 const FunctionTemplateSpecializationInfo *specInfo,
386 LVComputationKind computation) {
387 bool considerVisibility =
388 shouldConsiderTemplateVisibility(fn, specInfo);
390 // Merge information from the template parameters.
391 FunctionTemplateDecl *temp = specInfo->getTemplate();
393 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
394 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
396 // Merge information from the template arguments.
397 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
398 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
399 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
402 /// Does the given declaration have a direct visibility attribute
403 /// that would match the given rules?
404 static bool hasDirectVisibilityAttribute(const NamedDecl *D,
405 LVComputationKind computation) {
406 switch (computation) {
408 case LVForExplicitType:
409 if (D->hasAttr<TypeVisibilityAttr>())
413 case LVForExplicitValue:
414 if (D->hasAttr<VisibilityAttr>())
417 case LVForLinkageOnly:
420 llvm_unreachable("bad visibility computation kind");
423 /// Should we consider visibility associated with the template
424 /// arguments and parameters of the given class template specialization?
425 static bool shouldConsiderTemplateVisibility(
426 const ClassTemplateSpecializationDecl *spec,
427 LVComputationKind computation) {
428 // Include visibility from the template parameters and arguments
429 // only if this is not an explicit instantiation or specialization
430 // with direct explicit visibility (and note that implicit
431 // instantiations won't have a direct attribute).
433 // Furthermore, we want to ignore template parameters and arguments
434 // for an explicit specialization when computing the visibility of a
435 // member thereof with explicit visibility.
437 // This is a bit complex; let's unpack it.
439 // An explicit class specialization is an independent, top-level
440 // declaration. As such, if it or any of its members has an
441 // explicit visibility attribute, that must directly express the
442 // user's intent, and we should honor it. The same logic applies to
443 // an explicit instantiation of a member of such a thing.
445 // Fast path: if this is not an explicit instantiation or
446 // specialization, we always want to consider template-related
447 // visibility restrictions.
448 if (!spec->isExplicitInstantiationOrSpecialization())
451 // This is the 'member thereof' check.
452 if (spec->isExplicitSpecialization() &&
453 hasExplicitVisibilityAlready(computation))
456 return !hasDirectVisibilityAttribute(spec, computation);
459 /// Merge in template-related linkage and visibility for the given
460 /// class template specialization.
461 static void mergeTemplateLV(LinkageInfo &LV,
462 const ClassTemplateSpecializationDecl *spec,
463 LVComputationKind computation) {
464 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
466 // Merge information from the template parameters, but ignore
467 // visibility if we're only considering template arguments.
469 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
471 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
472 LV.mergeMaybeWithVisibility(tempLV,
473 considerVisibility && !hasExplicitVisibilityAlready(computation));
475 // Merge information from the template arguments. We ignore
476 // template-argument visibility if we've got an explicit
477 // instantiation with a visibility attribute.
478 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
479 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
480 if (considerVisibility)
481 LV.mergeVisibility(argsLV);
482 LV.mergeExternalVisibility(argsLV);
485 /// Should we consider visibility associated with the template
486 /// arguments and parameters of the given variable template
487 /// specialization? As usual, follow class template specialization
488 /// logic up to initialization.
489 static bool shouldConsiderTemplateVisibility(
490 const VarTemplateSpecializationDecl *spec,
491 LVComputationKind computation) {
492 // Include visibility from the template parameters and arguments
493 // only if this is not an explicit instantiation or specialization
494 // with direct explicit visibility (and note that implicit
495 // instantiations won't have a direct attribute).
496 if (!spec->isExplicitInstantiationOrSpecialization())
499 // An explicit variable specialization is an independent, top-level
500 // declaration. As such, if it has an explicit visibility attribute,
501 // that must directly express the user's intent, and we should honor
503 if (spec->isExplicitSpecialization() &&
504 hasExplicitVisibilityAlready(computation))
507 return !hasDirectVisibilityAttribute(spec, computation);
510 /// Merge in template-related linkage and visibility for the given
511 /// variable template specialization. As usual, follow class template
512 /// specialization logic up to initialization.
513 static void mergeTemplateLV(LinkageInfo &LV,
514 const VarTemplateSpecializationDecl *spec,
515 LVComputationKind computation) {
516 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
518 // Merge information from the template parameters, but ignore
519 // visibility if we're only considering template arguments.
521 VarTemplateDecl *temp = spec->getSpecializedTemplate();
523 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
524 LV.mergeMaybeWithVisibility(tempLV,
525 considerVisibility && !hasExplicitVisibilityAlready(computation));
527 // Merge information from the template arguments. We ignore
528 // template-argument visibility if we've got an explicit
529 // instantiation with a visibility attribute.
530 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
531 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
532 if (considerVisibility)
533 LV.mergeVisibility(argsLV);
534 LV.mergeExternalVisibility(argsLV);
537 static bool useInlineVisibilityHidden(const NamedDecl *D) {
538 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
539 const LangOptions &Opts = D->getASTContext().getLangOpts();
540 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
543 const auto *FD = dyn_cast<FunctionDecl>(D);
547 TemplateSpecializationKind TSK = TSK_Undeclared;
548 if (FunctionTemplateSpecializationInfo *spec
549 = FD->getTemplateSpecializationInfo()) {
550 TSK = spec->getTemplateSpecializationKind();
551 } else if (MemberSpecializationInfo *MSI =
552 FD->getMemberSpecializationInfo()) {
553 TSK = MSI->getTemplateSpecializationKind();
556 const FunctionDecl *Def = nullptr;
557 // InlineVisibilityHidden only applies to definitions, and
558 // isInlined() only gives meaningful answers on definitions
560 return TSK != TSK_ExplicitInstantiationDeclaration &&
561 TSK != TSK_ExplicitInstantiationDefinition &&
562 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
565 template <typename T> static bool isFirstInExternCContext(T *D) {
566 const T *First = D->getFirstDecl();
567 return First->isInExternCContext();
570 static bool isSingleLineLanguageLinkage(const Decl &D) {
571 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
572 if (!SD->hasBraces())
577 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
578 LVComputationKind computation) {
579 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
580 "Not a name having namespace scope");
581 ASTContext &Context = D->getASTContext();
583 // C++ [basic.link]p3:
584 // A name having namespace scope (3.3.6) has internal linkage if it
586 // - an object, reference, function or function template that is
587 // explicitly declared static; or,
588 // (This bullet corresponds to C99 6.2.2p3.)
589 if (const auto *Var = dyn_cast<VarDecl>(D)) {
590 // Explicitly declared static.
591 if (Var->getStorageClass() == SC_Static)
592 return LinkageInfo::internal();
594 // - a non-volatile object or reference that is explicitly declared const
595 // or constexpr and neither explicitly declared extern nor previously
596 // declared to have external linkage; or (there is no equivalent in C99)
597 if (Context.getLangOpts().CPlusPlus &&
598 Var->getType().isConstQualified() &&
599 !Var->getType().isVolatileQualified()) {
600 const VarDecl *PrevVar = Var->getPreviousDecl();
602 return getLVForDecl(PrevVar, computation);
604 if (Var->getStorageClass() != SC_Extern &&
605 Var->getStorageClass() != SC_PrivateExtern &&
606 !isSingleLineLanguageLinkage(*Var))
607 return LinkageInfo::internal();
610 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
611 PrevVar = PrevVar->getPreviousDecl()) {
612 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
613 Var->getStorageClass() == SC_None)
614 return PrevVar->getLinkageAndVisibility();
615 // Explicitly declared static.
616 if (PrevVar->getStorageClass() == SC_Static)
617 return LinkageInfo::internal();
619 } else if (const FunctionDecl *Function = D->getAsFunction()) {
621 // A non-member function template can have internal linkage; any
622 // other template name shall have external linkage.
624 // Explicitly declared static.
625 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
626 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
627 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
628 // - a data member of an anonymous union.
629 const VarDecl *VD = IFD->getVarDecl();
630 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
631 return getLVForNamespaceScopeDecl(VD, computation);
633 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
635 if (D->isInAnonymousNamespace()) {
636 const auto *Var = dyn_cast<VarDecl>(D);
637 const auto *Func = dyn_cast<FunctionDecl>(D);
638 // FIXME: In C++11 onwards, anonymous namespaces should give decls
639 // within them internal linkage, not unique external linkage.
640 if ((!Var || !isFirstInExternCContext(Var)) &&
641 (!Func || !isFirstInExternCContext(Func)))
642 return LinkageInfo::uniqueExternal();
645 // Set up the defaults.
648 // If the declaration of an identifier for an object has file
649 // scope and no storage-class specifier, its linkage is
653 if (!hasExplicitVisibilityAlready(computation)) {
654 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
655 LV.mergeVisibility(*Vis, true);
657 // If we're declared in a namespace with a visibility attribute,
658 // use that namespace's visibility, and it still counts as explicit.
659 for (const DeclContext *DC = D->getDeclContext();
660 !isa<TranslationUnitDecl>(DC);
661 DC = DC->getParent()) {
662 const auto *ND = dyn_cast<NamespaceDecl>(DC);
664 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
665 LV.mergeVisibility(*Vis, true);
671 // Add in global settings if the above didn't give us direct visibility.
672 if (!LV.isVisibilityExplicit()) {
673 // Use global type/value visibility as appropriate.
674 Visibility globalVisibility;
675 if (computation == LVForValue) {
676 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
678 assert(computation == LVForType);
679 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
681 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
683 // If we're paying attention to global visibility, apply
684 // -finline-visibility-hidden if this is an inline method.
685 if (useInlineVisibilityHidden(D))
686 LV.mergeVisibility(HiddenVisibility, true);
690 // C++ [basic.link]p4:
692 // A name having namespace scope has external linkage if it is the
695 // - an object or reference, unless it has internal linkage; or
696 if (const auto *Var = dyn_cast<VarDecl>(D)) {
697 // GCC applies the following optimization to variables and static
698 // data members, but not to functions:
700 // Modify the variable's LV by the LV of its type unless this is
701 // C or extern "C". This follows from [basic.link]p9:
702 // A type without linkage shall not be used as the type of a
703 // variable or function with external linkage unless
704 // - the entity has C language linkage, or
705 // - the entity is declared within an unnamed namespace, or
706 // - the entity is not used or is defined in the same
708 // and [basic.link]p10:
709 // ...the types specified by all declarations referring to a
710 // given variable or function shall be identical...
711 // C does not have an equivalent rule.
713 // Ignore this if we've got an explicit attribute; the user
714 // probably knows what they're doing.
716 // Note that we don't want to make the variable non-external
717 // because of this, but unique-external linkage suits us.
718 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
719 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
720 if (TypeLV.getLinkage() != ExternalLinkage)
721 return LinkageInfo::uniqueExternal();
722 if (!LV.isVisibilityExplicit())
723 LV.mergeVisibility(TypeLV);
726 if (Var->getStorageClass() == SC_PrivateExtern)
727 LV.mergeVisibility(HiddenVisibility, true);
729 // Note that Sema::MergeVarDecl already takes care of implementing
730 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
733 // As per function and class template specializations (below),
734 // consider LV for the template and template arguments. We're at file
735 // scope, so we do not need to worry about nested specializations.
736 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
737 mergeTemplateLV(LV, spec, computation);
740 // - a function, unless it has internal linkage; or
741 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
742 // In theory, we can modify the function's LV by the LV of its
743 // type unless it has C linkage (see comment above about variables
744 // for justification). In practice, GCC doesn't do this, so it's
745 // just too painful to make work.
747 if (Function->getStorageClass() == SC_PrivateExtern)
748 LV.mergeVisibility(HiddenVisibility, true);
750 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
751 // merging storage classes and visibility attributes, so we don't have to
752 // look at previous decls in here.
754 // In C++, then if the type of the function uses a type with
755 // unique-external linkage, it's not legally usable from outside
756 // this translation unit. However, we should use the C linkage
757 // rules instead for extern "C" declarations.
758 if (Context.getLangOpts().CPlusPlus &&
759 !Function->isInExternCContext()) {
760 // Only look at the type-as-written. If this function has an auto-deduced
761 // return type, we can't compute the linkage of that type because it could
762 // require looking at the linkage of this function, and we don't need this
763 // for correctness because the type is not part of the function's
765 // FIXME: This is a hack. We should be able to solve this circularity and
766 // the one in getLVForClassMember for Functions some other way.
767 QualType TypeAsWritten = Function->getType();
768 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
769 TypeAsWritten = TSI->getType();
770 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
771 return LinkageInfo::uniqueExternal();
774 // Consider LV from the template and the template arguments.
775 // We're at file scope, so we do not need to worry about nested
777 if (FunctionTemplateSpecializationInfo *specInfo
778 = Function->getTemplateSpecializationInfo()) {
779 mergeTemplateLV(LV, Function, specInfo, computation);
782 // - a named class (Clause 9), or an unnamed class defined in a
783 // typedef declaration in which the class has the typedef name
784 // for linkage purposes (7.1.3); or
785 // - a named enumeration (7.2), or an unnamed enumeration
786 // defined in a typedef declaration in which the enumeration
787 // has the typedef name for linkage purposes (7.1.3); or
788 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
789 // Unnamed tags have no linkage.
790 if (!Tag->hasNameForLinkage())
791 return LinkageInfo::none();
793 // If this is a class template specialization, consider the
794 // linkage of the template and template arguments. We're at file
795 // scope, so we do not need to worry about nested specializations.
796 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
797 mergeTemplateLV(LV, spec, computation);
800 // - an enumerator belonging to an enumeration with external linkage;
801 } else if (isa<EnumConstantDecl>(D)) {
802 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
804 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
805 return LinkageInfo::none();
808 // - a template, unless it is a function template that has
809 // internal linkage (Clause 14);
810 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
811 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
813 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
814 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
816 // - a namespace (7.3), unless it is declared within an unnamed
818 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
821 // By extension, we assign external linkage to Objective-C
823 } else if (isa<ObjCInterfaceDecl>(D)) {
826 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
827 // A typedef declaration has linkage if it gives a type a name for
829 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
830 return LinkageInfo::none();
832 // Everything not covered here has no linkage.
834 return LinkageInfo::none();
837 // If we ended up with non-external linkage, visibility should
838 // always be default.
839 if (LV.getLinkage() != ExternalLinkage)
840 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
845 static LinkageInfo getLVForClassMember(const NamedDecl *D,
846 LVComputationKind computation) {
847 // Only certain class members have linkage. Note that fields don't
848 // really have linkage, but it's convenient to say they do for the
849 // purposes of calculating linkage of pointer-to-data-member
850 // template arguments.
852 // Templates also don't officially have linkage, but since we ignore
853 // the C++ standard and look at template arguments when determining
854 // linkage and visibility of a template specialization, we might hit
855 // a template template argument that way. If we do, we need to
856 // consider its linkage.
857 if (!(isa<CXXMethodDecl>(D) ||
860 isa<IndirectFieldDecl>(D) ||
862 isa<TemplateDecl>(D)))
863 return LinkageInfo::none();
867 // If we have an explicit visibility attribute, merge that in.
868 if (!hasExplicitVisibilityAlready(computation)) {
869 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
870 LV.mergeVisibility(*Vis, true);
871 // If we're paying attention to global visibility, apply
872 // -finline-visibility-hidden if this is an inline method.
874 // Note that we do this before merging information about
875 // the class visibility.
876 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
877 LV.mergeVisibility(HiddenVisibility, true);
880 // If this class member has an explicit visibility attribute, the only
881 // thing that can change its visibility is the template arguments, so
882 // only look for them when processing the class.
883 LVComputationKind classComputation = computation;
884 if (LV.isVisibilityExplicit())
885 classComputation = withExplicitVisibilityAlready(computation);
887 LinkageInfo classLV =
888 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
889 // If the class already has unique-external linkage, we can't improve.
890 if (classLV.getLinkage() == UniqueExternalLinkage)
891 return LinkageInfo::uniqueExternal();
893 if (!isExternallyVisible(classLV.getLinkage()))
894 return LinkageInfo::none();
897 // Otherwise, don't merge in classLV yet, because in certain cases
898 // we need to completely ignore the visibility from it.
900 // Specifically, if this decl exists and has an explicit attribute.
901 const NamedDecl *explicitSpecSuppressor = nullptr;
903 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
904 // If the type of the function uses a type with unique-external
905 // linkage, it's not legally usable from outside this translation unit.
906 // But only look at the type-as-written. If this function has an
907 // auto-deduced return type, we can't compute the linkage of that type
908 // because it could require looking at the linkage of this function, and we
909 // don't need this for correctness because the type is not part of the
910 // function's signature.
911 // FIXME: This is a hack. We should be able to solve this circularity and
912 // the one in getLVForNamespaceScopeDecl for Functions some other way.
914 QualType TypeAsWritten = MD->getType();
915 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
916 TypeAsWritten = TSI->getType();
917 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
918 return LinkageInfo::uniqueExternal();
920 // If this is a method template specialization, use the linkage for
921 // the template parameters and arguments.
922 if (FunctionTemplateSpecializationInfo *spec
923 = MD->getTemplateSpecializationInfo()) {
924 mergeTemplateLV(LV, MD, spec, computation);
925 if (spec->isExplicitSpecialization()) {
926 explicitSpecSuppressor = MD;
927 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
928 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
930 } else if (isExplicitMemberSpecialization(MD)) {
931 explicitSpecSuppressor = MD;
934 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
935 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
936 mergeTemplateLV(LV, spec, computation);
937 if (spec->isExplicitSpecialization()) {
938 explicitSpecSuppressor = spec;
940 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
941 if (isExplicitMemberSpecialization(temp)) {
942 explicitSpecSuppressor = temp->getTemplatedDecl();
945 } else if (isExplicitMemberSpecialization(RD)) {
946 explicitSpecSuppressor = RD;
949 // Static data members.
950 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
951 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
952 mergeTemplateLV(LV, spec, computation);
954 // Modify the variable's linkage by its type, but ignore the
955 // type's visibility unless it's a definition.
956 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
957 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
958 LV.mergeVisibility(typeLV);
959 LV.mergeExternalVisibility(typeLV);
961 if (isExplicitMemberSpecialization(VD)) {
962 explicitSpecSuppressor = VD;
966 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
967 bool considerVisibility =
968 (!LV.isVisibilityExplicit() &&
969 !classLV.isVisibilityExplicit() &&
970 !hasExplicitVisibilityAlready(computation));
972 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
973 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
975 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
976 if (isExplicitMemberSpecialization(redeclTemp)) {
977 explicitSpecSuppressor = temp->getTemplatedDecl();
982 // We should never be looking for an attribute directly on a template.
983 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
985 // If this member is an explicit member specialization, and it has
986 // an explicit attribute, ignore visibility from the parent.
987 bool considerClassVisibility = true;
988 if (explicitSpecSuppressor &&
989 // optimization: hasDVA() is true only with explicit visibility.
990 LV.isVisibilityExplicit() &&
991 classLV.getVisibility() != DefaultVisibility &&
992 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
993 considerClassVisibility = false;
996 // Finally, merge in information from the class.
997 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
1001 void NamedDecl::anchor() { }
1003 static LinkageInfo computeLVForDecl(const NamedDecl *D,
1004 LVComputationKind computation);
1006 bool NamedDecl::isLinkageValid() const {
1007 if (!hasCachedLinkage())
1010 return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
1014 ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1015 StringRef name = getName();
1016 if (name.empty()) return SFF_None;
1018 if (name.front() == 'C')
1019 if (name == "CFStringCreateWithFormat" ||
1020 name == "CFStringCreateWithFormatAndArguments" ||
1021 name == "CFStringAppendFormat" ||
1022 name == "CFStringAppendFormatAndArguments")
1023 return SFF_CFString;
1027 Linkage NamedDecl::getLinkageInternal() const {
1028 // We don't care about visibility here, so ask for the cheapest
1029 // possible visibility analysis.
1030 return getLVForDecl(this, LVForLinkageOnly).getLinkage();
1033 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
1034 LVComputationKind computation =
1035 (usesTypeVisibility(this) ? LVForType : LVForValue);
1036 return getLVForDecl(this, computation);
1039 static Optional<Visibility>
1040 getExplicitVisibilityAux(const NamedDecl *ND,
1041 NamedDecl::ExplicitVisibilityKind kind,
1042 bool IsMostRecent) {
1043 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1045 // Check the declaration itself first.
1046 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
1049 // If this is a member class of a specialization of a class template
1050 // and the corresponding decl has explicit visibility, use that.
1051 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
1052 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1053 if (InstantiatedFrom)
1054 return getVisibilityOf(InstantiatedFrom, kind);
1057 // If there wasn't explicit visibility there, and this is a
1058 // specialization of a class template, check for visibility
1060 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND))
1061 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1064 // Use the most recent declaration.
1065 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
1066 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1067 if (MostRecent != ND)
1068 return getExplicitVisibilityAux(MostRecent, kind, true);
1071 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
1072 if (Var->isStaticDataMember()) {
1073 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1074 if (InstantiatedFrom)
1075 return getVisibilityOf(InstantiatedFrom, kind);
1078 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1079 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1084 // Also handle function template specializations.
1085 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
1086 // If the function is a specialization of a template with an
1087 // explicit visibility attribute, use that.
1088 if (FunctionTemplateSpecializationInfo *templateInfo
1089 = fn->getTemplateSpecializationInfo())
1090 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1093 // If the function is a member of a specialization of a class template
1094 // and the corresponding decl has explicit visibility, use that.
1095 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1096 if (InstantiatedFrom)
1097 return getVisibilityOf(InstantiatedFrom, kind);
1102 // The visibility of a template is stored in the templated decl.
1103 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
1104 return getVisibilityOf(TD->getTemplatedDecl(), kind);
1109 Optional<Visibility>
1110 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1111 return getExplicitVisibilityAux(this, kind, false);
1114 static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
1115 LVComputationKind computation) {
1116 // This lambda has its linkage/visibility determined by its owner.
1118 if (isa<ParmVarDecl>(ContextDecl))
1119 DC = ContextDecl->getDeclContext()->getRedeclContext();
1121 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1124 if (const auto *ND = dyn_cast<NamedDecl>(DC))
1125 return getLVForDecl(ND, computation);
1127 return LinkageInfo::external();
1130 static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1131 LVComputationKind computation) {
1132 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
1133 if (Function->isInAnonymousNamespace() &&
1134 !Function->isInExternCContext())
1135 return LinkageInfo::uniqueExternal();
1137 // This is a "void f();" which got merged with a file static.
1138 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1139 return LinkageInfo::internal();
1142 if (!hasExplicitVisibilityAlready(computation)) {
1143 if (Optional<Visibility> Vis =
1144 getExplicitVisibility(Function, computation))
1145 LV.mergeVisibility(*Vis, true);
1148 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1149 // merging storage classes and visibility attributes, so we don't have to
1150 // look at previous decls in here.
1155 if (const auto *Var = dyn_cast<VarDecl>(D)) {
1156 if (Var->hasExternalStorage()) {
1157 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
1158 return LinkageInfo::uniqueExternal();
1161 if (Var->getStorageClass() == SC_PrivateExtern)
1162 LV.mergeVisibility(HiddenVisibility, true);
1163 else if (!hasExplicitVisibilityAlready(computation)) {
1164 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
1165 LV.mergeVisibility(*Vis, true);
1168 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1169 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1170 if (PrevLV.getLinkage())
1171 LV.setLinkage(PrevLV.getLinkage());
1172 LV.mergeVisibility(PrevLV);
1178 if (!Var->isStaticLocal())
1179 return LinkageInfo::none();
1182 ASTContext &Context = D->getASTContext();
1183 if (!Context.getLangOpts().CPlusPlus)
1184 return LinkageInfo::none();
1186 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1187 if (!OuterD || OuterD->isInvalidDecl())
1188 return LinkageInfo::none();
1191 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
1192 if (!BD->getBlockManglingNumber())
1193 return LinkageInfo::none();
1195 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1196 BD->getBlockManglingContextDecl(), computation);
1198 const auto *FD = cast<FunctionDecl>(OuterD);
1199 if (!FD->isInlined() &&
1200 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
1201 return LinkageInfo::none();
1203 LV = getLVForDecl(FD, computation);
1205 if (!isExternallyVisible(LV.getLinkage()))
1206 return LinkageInfo::none();
1207 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1208 LV.isVisibilityExplicit());
1211 static inline const CXXRecordDecl*
1212 getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1213 const CXXRecordDecl *Ret = Record;
1214 while (Record && Record->isLambda()) {
1216 if (!Record->getParent()) break;
1217 // Get the Containing Class of this Lambda Class
1218 Record = dyn_cast_or_null<CXXRecordDecl>(
1219 Record->getParent()->getParent());
1224 static LinkageInfo computeLVForDecl(const NamedDecl *D,
1225 LVComputationKind computation) {
1226 // Internal_linkage attribute overrides other considerations.
1227 if (D->hasAttr<InternalLinkageAttr>())
1228 return LinkageInfo::internal();
1230 // Objective-C: treat all Objective-C declarations as having external
1232 switch (D->getKind()) {
1236 // Per C++ [basic.link]p2, only the names of objects, references,
1237 // functions, types, templates, namespaces, and values ever have linkage.
1239 // Note that the name of a typedef, namespace alias, using declaration,
1240 // and so on are not the name of the corresponding type, namespace, or
1241 // declaration, so they do *not* have linkage.
1242 case Decl::ImplicitParam:
1244 case Decl::NamespaceAlias:
1247 case Decl::UsingShadow:
1248 case Decl::UsingDirective:
1249 return LinkageInfo::none();
1251 case Decl::EnumConstant:
1252 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
1253 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1256 case Decl::TypeAlias:
1257 // A typedef declaration has linkage if it gives a type a name for
1258 // linkage purposes.
1259 if (!D->getASTContext().getLangOpts().CPlusPlus ||
1260 !cast<TypedefNameDecl>(D)
1261 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1262 return LinkageInfo::none();
1265 case Decl::TemplateTemplateParm: // count these as external
1266 case Decl::NonTypeTemplateParm:
1267 case Decl::ObjCAtDefsField:
1268 case Decl::ObjCCategory:
1269 case Decl::ObjCCategoryImpl:
1270 case Decl::ObjCCompatibleAlias:
1271 case Decl::ObjCImplementation:
1272 case Decl::ObjCMethod:
1273 case Decl::ObjCProperty:
1274 case Decl::ObjCPropertyImpl:
1275 case Decl::ObjCProtocol:
1276 return LinkageInfo::external();
1278 case Decl::CXXRecord: {
1279 const auto *Record = cast<CXXRecordDecl>(D);
1280 if (Record->isLambda()) {
1281 if (!Record->getLambdaManglingNumber()) {
1282 // This lambda has no mangling number, so it's internal.
1283 return LinkageInfo::internal();
1286 // This lambda has its linkage/visibility determined:
1287 // - either by the outermost lambda if that lambda has no mangling
1289 // - or by the parent of the outer most lambda
1290 // This prevents infinite recursion in settings such as nested lambdas
1291 // used in NSDMI's, for e.g.
1294 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1296 const CXXRecordDecl *OuterMostLambda =
1297 getOutermostEnclosingLambda(Record);
1298 if (!OuterMostLambda->getLambdaManglingNumber())
1299 return LinkageInfo::internal();
1301 return getLVForClosure(
1302 OuterMostLambda->getDeclContext()->getRedeclContext(),
1303 OuterMostLambda->getLambdaContextDecl(), computation);
1310 // Handle linkage for namespace-scope names.
1311 if (D->getDeclContext()->getRedeclContext()->isFileContext())
1312 return getLVForNamespaceScopeDecl(D, computation);
1314 // C++ [basic.link]p5:
1315 // In addition, a member function, static data member, a named
1316 // class or enumeration of class scope, or an unnamed class or
1317 // enumeration defined in a class-scope typedef declaration such
1318 // that the class or enumeration has the typedef name for linkage
1319 // purposes (7.1.3), has external linkage if the name of the class
1320 // has external linkage.
1321 if (D->getDeclContext()->isRecord())
1322 return getLVForClassMember(D, computation);
1324 // C++ [basic.link]p6:
1325 // The name of a function declared in block scope and the name of
1326 // an object declared by a block scope extern declaration have
1327 // linkage. If there is a visible declaration of an entity with
1328 // linkage having the same name and type, ignoring entities
1329 // declared outside the innermost enclosing namespace scope, the
1330 // block scope declaration declares that same entity and receives
1331 // the linkage of the previous declaration. If there is more than
1332 // one such matching entity, the program is ill-formed. Otherwise,
1333 // if no matching entity is found, the block scope entity receives
1334 // external linkage.
1335 if (D->getDeclContext()->isFunctionOrMethod())
1336 return getLVForLocalDecl(D, computation);
1338 // C++ [basic.link]p6:
1339 // Names not covered by these rules have no linkage.
1340 return LinkageInfo::none();
1344 class LinkageComputer {
1346 static LinkageInfo getLVForDecl(const NamedDecl *D,
1347 LVComputationKind computation) {
1348 // Internal_linkage attribute overrides other considerations.
1349 if (D->hasAttr<InternalLinkageAttr>())
1350 return LinkageInfo::internal();
1352 if (computation == LVForLinkageOnly && D->hasCachedLinkage())
1353 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1355 LinkageInfo LV = computeLVForDecl(D, computation);
1356 if (D->hasCachedLinkage())
1357 assert(D->getCachedLinkage() == LV.getLinkage());
1359 D->setCachedLinkage(LV.getLinkage());
1362 // In C (because of gnu inline) and in c++ with microsoft extensions an
1363 // static can follow an extern, so we can have two decls with different
1365 const LangOptions &Opts = D->getASTContext().getLangOpts();
1366 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1369 // We have just computed the linkage for this decl. By induction we know
1370 // that all other computed linkages match, check that the one we just
1371 // computed also does.
1372 NamedDecl *Old = nullptr;
1373 for (auto I : D->redecls()) {
1374 auto *T = cast<NamedDecl>(I);
1377 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1382 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1390 static LinkageInfo getLVForDecl(const NamedDecl *D,
1391 LVComputationKind computation) {
1392 return clang::LinkageComputer::getLVForDecl(D, computation);
1395 std::string NamedDecl::getQualifiedNameAsString() const {
1396 std::string QualName;
1397 llvm::raw_string_ostream OS(QualName);
1398 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1402 void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1403 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1406 void NamedDecl::printQualifiedName(raw_ostream &OS,
1407 const PrintingPolicy &P) const {
1408 const DeclContext *Ctx = getDeclContext();
1410 if (Ctx->isFunctionOrMethod()) {
1415 typedef SmallVector<const DeclContext *, 8> ContextsTy;
1416 ContextsTy Contexts;
1418 // Collect contexts.
1419 while (Ctx && isa<NamedDecl>(Ctx)) {
1420 Contexts.push_back(Ctx);
1421 Ctx = Ctx->getParent();
1424 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1426 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
1427 OS << Spec->getName();
1428 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1429 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1430 TemplateArgs.data(),
1431 TemplateArgs.size(),
1433 } else if (const auto *ND = dyn_cast<NamespaceDecl>(*I)) {
1434 if (P.SuppressUnwrittenScope &&
1435 (ND->isAnonymousNamespace() || ND->isInline()))
1437 if (ND->isAnonymousNamespace()) {
1438 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1439 : "(anonymous namespace)");
1443 } else if (const auto *RD = dyn_cast<RecordDecl>(*I)) {
1444 if (!RD->getIdentifier())
1445 OS << "(anonymous " << RD->getKindName() << ')';
1448 } else if (const auto *FD = dyn_cast<FunctionDecl>(*I)) {
1449 const FunctionProtoType *FT = nullptr;
1450 if (FD->hasWrittenPrototype())
1451 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1455 unsigned NumParams = FD->getNumParams();
1456 for (unsigned i = 0; i < NumParams; ++i) {
1459 OS << FD->getParamDecl(i)->getType().stream(P);
1462 if (FT->isVariadic()) {
1469 } else if (const auto *ED = dyn_cast<EnumDecl>(*I)) {
1470 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1471 // enumerator is declared in the scope that immediately contains
1472 // the enum-specifier. Each scoped enumerator is declared in the
1473 // scope of the enumeration.
1474 if (ED->isScoped() || ED->getIdentifier())
1479 OS << *cast<NamedDecl>(*I);
1487 OS << "(anonymous)";
1490 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1491 const PrintingPolicy &Policy,
1492 bool Qualified) const {
1494 printQualifiedName(OS, Policy);
1499 template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1502 static bool isRedeclarableImpl(...) { return false; }
1503 static bool isRedeclarable(Decl::Kind K) {
1505 #define DECL(Type, Base) \
1507 return isRedeclarableImpl((Type##Decl *)nullptr);
1508 #define ABSTRACT_DECL(DECL)
1509 #include "clang/AST/DeclNodes.inc"
1511 llvm_unreachable("unknown decl kind");
1514 bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
1515 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1517 // Never replace one imported declaration with another; we need both results
1518 // when re-exporting.
1519 if (OldD->isFromASTFile() && isFromASTFile())
1522 // A kind mismatch implies that the declaration is not replaced.
1523 if (OldD->getKind() != getKind())
1526 // For method declarations, we never replace. (Why?)
1527 if (isa<ObjCMethodDecl>(this))
1530 // For parameters, pick the newer one. This is either an error or (in
1531 // Objective-C) permitted as an extension.
1532 if (isa<ParmVarDecl>(this))
1535 // Inline namespaces can give us two declarations with the same
1536 // name and kind in the same scope but different contexts; we should
1537 // keep both declarations in this case.
1538 if (!this->getDeclContext()->getRedeclContext()->Equals(
1539 OldD->getDeclContext()->getRedeclContext()))
1542 // Using declarations can be replaced if they import the same name from the
1544 if (auto *UD = dyn_cast<UsingDecl>(this)) {
1545 ASTContext &Context = getASTContext();
1546 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
1547 Context.getCanonicalNestedNameSpecifier(
1548 cast<UsingDecl>(OldD)->getQualifier());
1550 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
1551 ASTContext &Context = getASTContext();
1552 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
1553 Context.getCanonicalNestedNameSpecifier(
1554 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1557 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1558 // They can be replaced if they nominate the same namespace.
1559 // FIXME: Is this true even if they have different module visibility?
1560 if (auto *UD = dyn_cast<UsingDirectiveDecl>(this))
1561 return UD->getNominatedNamespace()->getOriginalNamespace() ==
1562 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1563 ->getOriginalNamespace();
1565 if (isRedeclarable(getKind())) {
1566 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1572 // Check whether this is actually newer than OldD. We want to keep the
1573 // newer declaration. This loop will usually only iterate once, because
1574 // OldD is usually the previous declaration.
1575 for (auto D : redecls()) {
1579 // If we reach the canonical declaration, then OldD is not actually older
1582 // FIXME: In this case, we should not add this decl to the lookup table.
1583 if (D->isCanonicalDecl())
1587 // It's a newer declaration of the same kind of declaration in the same
1588 // scope: we want this decl instead of the existing one.
1592 // In all other cases, we need to keep both declarations in case they have
1593 // different visibility. Any attempt to use the name will result in an
1594 // ambiguity if more than one is visible.
1598 bool NamedDecl::hasLinkage() const {
1599 return getFormalLinkage() != NoLinkage;
1602 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1603 NamedDecl *ND = this;
1604 while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
1605 ND = UD->getTargetDecl();
1607 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1608 return AD->getClassInterface();
1610 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1611 return AD->getNamespace();
1616 bool NamedDecl::isCXXInstanceMember() const {
1617 if (!isCXXClassMember())
1620 const NamedDecl *D = this;
1621 if (isa<UsingShadowDecl>(D))
1622 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1624 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1626 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1627 return MD->isInstance();
1631 //===----------------------------------------------------------------------===//
1632 // DeclaratorDecl Implementation
1633 //===----------------------------------------------------------------------===//
1635 template <typename DeclT>
1636 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1637 if (decl->getNumTemplateParameterLists() > 0)
1638 return decl->getTemplateParameterList(0)->getTemplateLoc();
1640 return decl->getInnerLocStart();
1643 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1644 TypeSourceInfo *TSI = getTypeSourceInfo();
1645 if (TSI) return TSI->getTypeLoc().getBeginLoc();
1646 return SourceLocation();
1649 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1651 // Make sure the extended decl info is allocated.
1652 if (!hasExtInfo()) {
1653 // Save (non-extended) type source info pointer.
1654 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1655 // Allocate external info struct.
1656 DeclInfo = new (getASTContext()) ExtInfo;
1657 // Restore savedTInfo into (extended) decl info.
1658 getExtInfo()->TInfo = savedTInfo;
1660 // Set qualifier info.
1661 getExtInfo()->QualifierLoc = QualifierLoc;
1663 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1665 if (getExtInfo()->NumTemplParamLists == 0) {
1666 // Save type source info pointer.
1667 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1668 // Deallocate the extended decl info.
1669 getASTContext().Deallocate(getExtInfo());
1670 // Restore savedTInfo into (non-extended) decl info.
1671 DeclInfo = savedTInfo;
1674 getExtInfo()->QualifierLoc = QualifierLoc;
1679 void DeclaratorDecl::setTemplateParameterListsInfo(
1680 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1681 assert(!TPLists.empty());
1682 // Make sure the extended decl info is allocated.
1683 if (!hasExtInfo()) {
1684 // Save (non-extended) type source info pointer.
1685 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1686 // Allocate external info struct.
1687 DeclInfo = new (getASTContext()) ExtInfo;
1688 // Restore savedTInfo into (extended) decl info.
1689 getExtInfo()->TInfo = savedTInfo;
1691 // Set the template parameter lists info.
1692 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
1695 SourceLocation DeclaratorDecl::getOuterLocStart() const {
1696 return getTemplateOrInnerLocStart(this);
1701 // Helper function: returns true if QT is or contains a type
1702 // having a postfix component.
1703 bool typeIsPostfix(clang::QualType QT) {
1705 const Type* T = QT.getTypePtr();
1706 switch (T->getTypeClass()) {
1710 QT = cast<PointerType>(T)->getPointeeType();
1712 case Type::BlockPointer:
1713 QT = cast<BlockPointerType>(T)->getPointeeType();
1715 case Type::MemberPointer:
1716 QT = cast<MemberPointerType>(T)->getPointeeType();
1718 case Type::LValueReference:
1719 case Type::RValueReference:
1720 QT = cast<ReferenceType>(T)->getPointeeType();
1722 case Type::PackExpansion:
1723 QT = cast<PackExpansionType>(T)->getPattern();
1726 case Type::ConstantArray:
1727 case Type::DependentSizedArray:
1728 case Type::IncompleteArray:
1729 case Type::VariableArray:
1730 case Type::FunctionProto:
1731 case Type::FunctionNoProto:
1739 SourceRange DeclaratorDecl::getSourceRange() const {
1740 SourceLocation RangeEnd = getLocation();
1741 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1742 // If the declaration has no name or the type extends past the name take the
1743 // end location of the type.
1744 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
1745 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1747 return SourceRange(getOuterLocStart(), RangeEnd);
1750 void QualifierInfo::setTemplateParameterListsInfo(
1751 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1752 // Free previous template parameters (if any).
1753 if (NumTemplParamLists > 0) {
1754 Context.Deallocate(TemplParamLists);
1755 TemplParamLists = nullptr;
1756 NumTemplParamLists = 0;
1758 // Set info on matched template parameter lists (if any).
1759 if (!TPLists.empty()) {
1760 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1761 NumTemplParamLists = TPLists.size();
1762 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
1766 //===----------------------------------------------------------------------===//
1767 // VarDecl Implementation
1768 //===----------------------------------------------------------------------===//
1770 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1772 case SC_None: break;
1773 case SC_Auto: return "auto";
1774 case SC_Extern: return "extern";
1775 case SC_PrivateExtern: return "__private_extern__";
1776 case SC_Register: return "register";
1777 case SC_Static: return "static";
1780 llvm_unreachable("Invalid storage class");
1783 VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1784 SourceLocation StartLoc, SourceLocation IdLoc,
1785 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1787 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1788 redeclarable_base(C), Init() {
1789 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1790 "VarDeclBitfields too large!");
1791 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1792 "ParmVarDeclBitfields too large!");
1793 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1794 "NonParmVarDeclBitfields too large!");
1796 VarDeclBits.SClass = SC;
1797 // Everything else is implicitly initialized to false.
1800 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1801 SourceLocation StartL, SourceLocation IdL,
1802 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1804 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
1807 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1809 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1810 QualType(), nullptr, SC_None);
1813 void VarDecl::setStorageClass(StorageClass SC) {
1814 assert(isLegalForVariable(SC));
1815 VarDeclBits.SClass = SC;
1818 VarDecl::TLSKind VarDecl::getTLSKind() const {
1819 switch (VarDeclBits.TSCSpec) {
1820 case TSCS_unspecified:
1821 if (!hasAttr<ThreadAttr>() &&
1822 !(getASTContext().getLangOpts().OpenMPUseTLS &&
1823 getASTContext().getTargetInfo().isTLSSupported() &&
1824 hasAttr<OMPThreadPrivateDeclAttr>()))
1826 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1827 LangOptions::MSVC2015)) ||
1828 hasAttr<OMPThreadPrivateDeclAttr>())
1831 case TSCS___thread: // Fall through.
1832 case TSCS__Thread_local:
1834 case TSCS_thread_local:
1837 llvm_unreachable("Unknown thread storage class specifier!");
1840 SourceRange VarDecl::getSourceRange() const {
1841 if (const Expr *Init = getInit()) {
1842 SourceLocation InitEnd = Init->getLocEnd();
1843 // If Init is implicit, ignore its source range and fallback on
1844 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1845 if (InitEnd.isValid() && InitEnd != getLocation())
1846 return SourceRange(getOuterLocStart(), InitEnd);
1848 return DeclaratorDecl::getSourceRange();
1851 template<typename T>
1852 static LanguageLinkage getDeclLanguageLinkage(const T &D) {
1853 // C++ [dcl.link]p1: All function types, function names with external linkage,
1854 // and variable names with external linkage have a language linkage.
1855 if (!D.hasExternalFormalLinkage())
1856 return NoLanguageLinkage;
1858 // Language linkage is a C++ concept, but saying that everything else in C has
1859 // C language linkage fits the implementation nicely.
1860 ASTContext &Context = D.getASTContext();
1861 if (!Context.getLangOpts().CPlusPlus)
1862 return CLanguageLinkage;
1864 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1865 // language linkage of the names of class members and the function type of
1866 // class member functions.
1867 const DeclContext *DC = D.getDeclContext();
1869 return CXXLanguageLinkage;
1871 // If the first decl is in an extern "C" context, any other redeclaration
1872 // will have C language linkage. If the first one is not in an extern "C"
1873 // context, we would have reported an error for any other decl being in one.
1874 if (isFirstInExternCContext(&D))
1875 return CLanguageLinkage;
1876 return CXXLanguageLinkage;
1879 template<typename T>
1880 static bool isDeclExternC(const T &D) {
1881 // Since the context is ignored for class members, they can only have C++
1882 // language linkage or no language linkage.
1883 const DeclContext *DC = D.getDeclContext();
1884 if (DC->isRecord()) {
1885 assert(D.getASTContext().getLangOpts().CPlusPlus);
1889 return D.getLanguageLinkage() == CLanguageLinkage;
1892 LanguageLinkage VarDecl::getLanguageLinkage() const {
1893 return getDeclLanguageLinkage(*this);
1896 bool VarDecl::isExternC() const {
1897 return isDeclExternC(*this);
1900 bool VarDecl::isInExternCContext() const {
1901 return getLexicalDeclContext()->isExternCContext();
1904 bool VarDecl::isInExternCXXContext() const {
1905 return getLexicalDeclContext()->isExternCXXContext();
1908 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
1910 VarDecl::DefinitionKind
1911 VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
1912 // C++ [basic.def]p2:
1913 // A declaration is a definition unless [...] it contains the 'extern'
1914 // specifier or a linkage-specification and neither an initializer [...],
1915 // it declares a static data member in a class declaration [...].
1916 // C++1y [temp.expl.spec]p15:
1917 // An explicit specialization of a static data member or an explicit
1918 // specialization of a static data member template is a definition if the
1919 // declaration includes an initializer; otherwise, it is a declaration.
1921 // FIXME: How do you declare (but not define) a partial specialization of
1922 // a static data member template outside the containing class?
1923 if (isStaticDataMember()) {
1924 if (isOutOfLine() &&
1926 // If the first declaration is out-of-line, this may be an
1927 // instantiation of an out-of-line partial specialization of a variable
1928 // template for which we have not yet instantiated the initializer.
1929 (getFirstDecl()->isOutOfLine()
1930 ? getTemplateSpecializationKind() == TSK_Undeclared
1931 : getTemplateSpecializationKind() !=
1932 TSK_ExplicitSpecialization) ||
1933 isa<VarTemplatePartialSpecializationDecl>(this)))
1936 return DeclarationOnly;
1939 // A definition of an identifier is a declaration for that identifier that
1940 // [...] causes storage to be reserved for that object.
1941 // Note: that applies for all non-file-scope objects.
1943 // If the declaration of an identifier for an object has file scope and an
1944 // initializer, the declaration is an external definition for the identifier
1948 if (hasAttr<AliasAttr>())
1951 if (const auto *SAA = getAttr<SelectAnyAttr>())
1952 if (!SAA->isInherited())
1955 // A variable template specialization (other than a static data member
1956 // template or an explicit specialization) is a declaration until we
1957 // instantiate its initializer.
1958 if (isa<VarTemplateSpecializationDecl>(this) &&
1959 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1960 return DeclarationOnly;
1962 if (hasExternalStorage())
1963 return DeclarationOnly;
1966 // A declaration directly contained in a linkage-specification is treated
1967 // as if it contains the extern specifier for the purpose of determining
1968 // the linkage of the declared name and whether it is a definition.
1969 if (isSingleLineLanguageLinkage(*this))
1970 return DeclarationOnly;
1973 // A declaration of an object that has file scope without an initializer,
1974 // and without a storage class specifier or the scs 'static', constitutes
1975 // a tentative definition.
1976 // No such thing in C++.
1977 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
1978 return TentativeDefinition;
1980 // What's left is (in C, block-scope) declarations without initializers or
1981 // external storage. These are definitions.
1985 VarDecl *VarDecl::getActingDefinition() {
1986 DefinitionKind Kind = isThisDeclarationADefinition();
1987 if (Kind != TentativeDefinition)
1990 VarDecl *LastTentative = nullptr;
1991 VarDecl *First = getFirstDecl();
1992 for (auto I : First->redecls()) {
1993 Kind = I->isThisDeclarationADefinition();
1994 if (Kind == Definition)
1996 else if (Kind == TentativeDefinition)
1999 return LastTentative;
2002 VarDecl *VarDecl::getDefinition(ASTContext &C) {
2003 VarDecl *First = getFirstDecl();
2004 for (auto I : First->redecls()) {
2005 if (I->isThisDeclarationADefinition(C) == Definition)
2011 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
2012 DefinitionKind Kind = DeclarationOnly;
2014 const VarDecl *First = getFirstDecl();
2015 for (auto I : First->redecls()) {
2016 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
2017 if (Kind == Definition)
2024 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
2025 for (auto I : redecls()) {
2026 if (auto Expr = I->getInit()) {
2034 bool VarDecl::hasInit() const {
2035 if (auto *P = dyn_cast<ParmVarDecl>(this))
2036 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2039 return !Init.isNull();
2042 Expr *VarDecl::getInit() {
2046 if (auto *S = Init.dyn_cast<Stmt *>())
2047 return cast<Expr>(S);
2049 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2052 Stmt **VarDecl::getInitAddress() {
2053 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2056 return Init.getAddrOfPtr1();
2059 bool VarDecl::isOutOfLine() const {
2060 if (Decl::isOutOfLine())
2063 if (!isStaticDataMember())
2066 // If this static data member was instantiated from a static data member of
2067 // a class template, check whether that static data member was defined
2069 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2070 return VD->isOutOfLine();
2075 VarDecl *VarDecl::getOutOfLineDefinition() {
2076 if (!isStaticDataMember())
2079 for (auto RD : redecls()) {
2080 if (RD->getLexicalDeclContext()->isFileContext())
2087 void VarDecl::setInit(Expr *I) {
2088 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
2089 Eval->~EvaluatedStmt();
2090 getASTContext().Deallocate(Eval);
2096 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
2097 const LangOptions &Lang = C.getLangOpts();
2099 if (!Lang.CPlusPlus)
2102 // In C++11, any variable of reference type can be used in a constant
2103 // expression if it is initialized by a constant expression.
2104 if (Lang.CPlusPlus11 && getType()->isReferenceType())
2107 // Only const objects can be used in constant expressions in C++. C++98 does
2108 // not require the variable to be non-volatile, but we consider this to be a
2110 if (!getType().isConstQualified() || getType().isVolatileQualified())
2113 // In C++, const, non-volatile variables of integral or enumeration types
2114 // can be used in constant expressions.
2115 if (getType()->isIntegralOrEnumerationType())
2118 // Additionally, in C++11, non-volatile constexpr variables can be used in
2119 // constant expressions.
2120 return Lang.CPlusPlus11 && isConstexpr();
2123 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2124 /// form, which contains extra information on the evaluated value of the
2126 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2127 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
2129 // Note: EvaluatedStmt contains an APValue, which usually holds
2130 // resources not allocated from the ASTContext. We need to do some
2131 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2132 // where we can detect whether there's anything to clean up or not.
2133 Eval = new (getASTContext()) EvaluatedStmt;
2134 Eval->Value = Init.get<Stmt *>();
2140 APValue *VarDecl::evaluateValue() const {
2141 SmallVector<PartialDiagnosticAt, 8> Notes;
2142 return evaluateValue(Notes);
2146 // Destroy an APValue that was allocated in an ASTContext.
2147 void DestroyAPValue(void* UntypedValue) {
2148 static_cast<APValue*>(UntypedValue)->~APValue();
2152 APValue *VarDecl::evaluateValue(
2153 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
2154 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2156 // We only produce notes indicating why an initializer is non-constant the
2157 // first time it is evaluated. FIXME: The notes won't always be emitted the
2158 // first time we try evaluation, so might not be produced at all.
2159 if (Eval->WasEvaluated)
2160 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
2162 const auto *Init = cast<Expr>(Eval->Value);
2163 assert(!Init->isValueDependent());
2165 if (Eval->IsEvaluating) {
2166 // FIXME: Produce a diagnostic for self-initialization.
2167 Eval->CheckedICE = true;
2168 Eval->IsICE = false;
2172 Eval->IsEvaluating = true;
2174 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2177 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2178 // or that it's empty (so that there's nothing to clean up) if evaluation
2181 Eval->Evaluated = APValue();
2182 else if (Eval->Evaluated.needsCleanup())
2183 getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
2185 Eval->IsEvaluating = false;
2186 Eval->WasEvaluated = true;
2188 // In C++11, we have determined whether the initializer was a constant
2189 // expression as a side-effect.
2190 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
2191 Eval->CheckedICE = true;
2192 Eval->IsICE = Result && Notes.empty();
2195 return Result ? &Eval->Evaluated : nullptr;
2198 APValue *VarDecl::getEvaluatedValue() const {
2199 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2200 if (Eval->WasEvaluated)
2201 return &Eval->Evaluated;
2206 bool VarDecl::isInitKnownICE() const {
2207 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2208 return Eval->CheckedICE;
2213 bool VarDecl::isInitICE() const {
2214 assert(isInitKnownICE() &&
2215 "Check whether we already know that the initializer is an ICE");
2216 return Init.get<EvaluatedStmt *>()->IsICE;
2219 bool VarDecl::checkInitIsICE() const {
2220 // Initializers of weak variables are never ICEs.
2224 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2225 if (Eval->CheckedICE)
2226 // We have already checked whether this subexpression is an
2227 // integral constant expression.
2230 const auto *Init = cast<Expr>(Eval->Value);
2231 assert(!Init->isValueDependent());
2233 // In C++11, evaluate the initializer to check whether it's a constant
2235 if (getASTContext().getLangOpts().CPlusPlus11) {
2236 SmallVector<PartialDiagnosticAt, 8> Notes;
2237 evaluateValue(Notes);
2241 // It's an ICE whether or not the definition we found is
2242 // out-of-line. See DR 721 and the discussion in Clang PR
2243 // 6206 for details.
2245 if (Eval->CheckingICE)
2247 Eval->CheckingICE = true;
2249 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2250 Eval->CheckingICE = false;
2251 Eval->CheckedICE = true;
2255 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2256 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2257 return cast<VarDecl>(MSI->getInstantiatedFrom());
2262 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2263 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2264 return Spec->getSpecializationKind();
2266 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2267 return MSI->getTemplateSpecializationKind();
2269 return TSK_Undeclared;
2272 SourceLocation VarDecl::getPointOfInstantiation() const {
2273 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2274 return Spec->getPointOfInstantiation();
2276 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2277 return MSI->getPointOfInstantiation();
2279 return SourceLocation();
2282 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2283 return getASTContext().getTemplateOrSpecializationInfo(this)
2284 .dyn_cast<VarTemplateDecl *>();
2287 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2288 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2291 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2292 if (isStaticDataMember())
2294 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2295 return getASTContext().getTemplateOrSpecializationInfo(this)
2296 .dyn_cast<MemberSpecializationInfo *>();
2300 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2301 SourceLocation PointOfInstantiation) {
2302 assert((isa<VarTemplateSpecializationDecl>(this) ||
2303 getMemberSpecializationInfo()) &&
2304 "not a variable or static data member template specialization");
2306 if (VarTemplateSpecializationDecl *Spec =
2307 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2308 Spec->setSpecializationKind(TSK);
2309 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2310 Spec->getPointOfInstantiation().isInvalid())
2311 Spec->setPointOfInstantiation(PointOfInstantiation);
2314 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2315 MSI->setTemplateSpecializationKind(TSK);
2316 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2317 MSI->getPointOfInstantiation().isInvalid())
2318 MSI->setPointOfInstantiation(PointOfInstantiation);
2323 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2324 TemplateSpecializationKind TSK) {
2325 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2326 "Previous template or instantiation?");
2327 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
2330 //===----------------------------------------------------------------------===//
2331 // ParmVarDecl Implementation
2332 //===----------------------------------------------------------------------===//
2334 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2335 SourceLocation StartLoc,
2336 SourceLocation IdLoc, IdentifierInfo *Id,
2337 QualType T, TypeSourceInfo *TInfo,
2338 StorageClass S, Expr *DefArg) {
2339 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2343 QualType ParmVarDecl::getOriginalType() const {
2344 TypeSourceInfo *TSI = getTypeSourceInfo();
2345 QualType T = TSI ? TSI->getType() : getType();
2346 if (const auto *DT = dyn_cast<DecayedType>(T))
2347 return DT->getOriginalType();
2351 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2353 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2354 nullptr, QualType(), nullptr, SC_None, nullptr);
2357 SourceRange ParmVarDecl::getSourceRange() const {
2358 if (!hasInheritedDefaultArg()) {
2359 SourceRange ArgRange = getDefaultArgRange();
2360 if (ArgRange.isValid())
2361 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2364 // DeclaratorDecl considers the range of postfix types as overlapping with the
2365 // declaration name, but this is not the case with parameters in ObjC methods.
2366 if (isa<ObjCMethodDecl>(getDeclContext()))
2367 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2369 return DeclaratorDecl::getSourceRange();
2372 Expr *ParmVarDecl::getDefaultArg() {
2373 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2374 assert(!hasUninstantiatedDefaultArg() &&
2375 "Default argument is not yet instantiated!");
2377 Expr *Arg = getInit();
2378 if (auto *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
2379 return E->getSubExpr();
2384 void ParmVarDecl::setDefaultArg(Expr *defarg) {
2385 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2389 SourceRange ParmVarDecl::getDefaultArgRange() const {
2390 switch (ParmVarDeclBits.DefaultArgKind) {
2393 // Nothing we can do here.
2394 return SourceRange();
2396 case DAK_Uninstantiated:
2397 return getUninstantiatedDefaultArg()->getSourceRange();
2400 if (const Expr *E = getInit())
2401 return E->getSourceRange();
2403 // Missing an actual expression, may be invalid.
2404 return SourceRange();
2406 llvm_unreachable("Invalid default argument kind.");
2409 void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2410 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2414 Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2415 assert(hasUninstantiatedDefaultArg() &&
2416 "Wrong kind of initialization expression!");
2417 return cast_or_null<Expr>(Init.get<Stmt *>());
2420 bool ParmVarDecl::hasDefaultArg() const {
2421 // FIXME: We should just return false for DAK_None here once callers are
2422 // prepared for the case that we encountered an invalid default argument and
2423 // were unable to even build an invalid expression.
2424 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2428 bool ParmVarDecl::isParameterPack() const {
2429 return isa<PackExpansionType>(getType());
2432 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2433 getASTContext().setParameterIndex(this, parameterIndex);
2434 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2437 unsigned ParmVarDecl::getParameterIndexLarge() const {
2438 return getASTContext().getParameterIndex(this);
2441 //===----------------------------------------------------------------------===//
2442 // FunctionDecl Implementation
2443 //===----------------------------------------------------------------------===//
2445 void FunctionDecl::getNameForDiagnostic(
2446 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2447 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
2448 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2450 TemplateSpecializationType::PrintTemplateArgumentList(
2451 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
2454 bool FunctionDecl::isVariadic() const {
2455 if (const auto *FT = getType()->getAs<FunctionProtoType>())
2456 return FT->isVariadic();
2460 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
2461 for (auto I : redecls()) {
2462 if (I->Body || I->IsLateTemplateParsed) {
2471 bool FunctionDecl::hasTrivialBody() const
2473 Stmt *S = getBody();
2475 // Since we don't have a body for this function, we don't know if it's
2480 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2485 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
2486 for (auto I : redecls()) {
2487 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
2488 I->hasAttr<AliasAttr>()) {
2489 Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
2497 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
2498 if (!hasBody(Definition))
2501 if (Definition->Body)
2502 return Definition->Body.get(getASTContext().getExternalSource());
2507 void FunctionDecl::setBody(Stmt *B) {
2510 EndRangeLoc = B->getLocEnd();
2513 void FunctionDecl::setPure(bool P) {
2516 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2517 Parent->markedVirtualFunctionPure();
2520 template<std::size_t Len>
2521 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2522 IdentifierInfo *II = ND->getIdentifier();
2523 return II && II->isStr(Str);
2526 bool FunctionDecl::isMain() const {
2527 const TranslationUnitDecl *tunit =
2528 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2530 !tunit->getASTContext().getLangOpts().Freestanding &&
2531 isNamed(this, "main");
2534 bool FunctionDecl::isMSVCRTEntryPoint() const {
2535 const TranslationUnitDecl *TUnit =
2536 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2540 // Even though we aren't really targeting MSVCRT if we are freestanding,
2541 // semantic analysis for these functions remains the same.
2543 // MSVCRT entry points only exist on MSVCRT targets.
2544 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2547 // Nameless functions like constructors cannot be entry points.
2548 if (!getIdentifier())
2551 return llvm::StringSwitch<bool>(getName())
2552 .Cases("main", // an ANSI console app
2553 "wmain", // a Unicode console App
2554 "WinMain", // an ANSI GUI app
2555 "wWinMain", // a Unicode GUI app
2561 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2562 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2563 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2564 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2565 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2566 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2568 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2571 const auto *proto = getType()->castAs<FunctionProtoType>();
2572 if (proto->getNumParams() != 2 || proto->isVariadic())
2575 ASTContext &Context =
2576 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2579 // The result type and first argument type are constant across all
2580 // these operators. The second argument must be exactly void*.
2581 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
2584 bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2585 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2587 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2588 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2589 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2590 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2593 if (isa<CXXRecordDecl>(getDeclContext()))
2596 // This can only fail for an invalid 'operator new' declaration.
2597 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2600 const auto *FPT = getType()->castAs<FunctionProtoType>();
2601 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 2 || FPT->isVariadic())
2604 // If this is a single-parameter function, it must be a replaceable global
2605 // allocation or deallocation function.
2606 if (FPT->getNumParams() == 1)
2609 // Otherwise, we're looking for a second parameter whose type is
2610 // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
2611 QualType Ty = FPT->getParamType(1);
2612 ASTContext &Ctx = getASTContext();
2613 if (Ctx.getLangOpts().SizedDeallocation &&
2614 Ctx.hasSameType(Ty, Ctx.getSizeType()))
2616 if (!Ty->isReferenceType())
2618 Ty = Ty->getPointeeType();
2619 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2621 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2622 return RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace();
2625 LanguageLinkage FunctionDecl::getLanguageLinkage() const {
2626 return getDeclLanguageLinkage(*this);
2629 bool FunctionDecl::isExternC() const {
2630 return isDeclExternC(*this);
2633 bool FunctionDecl::isInExternCContext() const {
2634 return getLexicalDeclContext()->isExternCContext();
2637 bool FunctionDecl::isInExternCXXContext() const {
2638 return getLexicalDeclContext()->isExternCXXContext();
2641 bool FunctionDecl::isGlobal() const {
2642 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
2643 return Method->isStatic();
2645 if (getCanonicalDecl()->getStorageClass() == SC_Static)
2648 for (const DeclContext *DC = getDeclContext();
2650 DC = DC->getParent()) {
2651 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
2652 if (!Namespace->getDeclName())
2661 bool FunctionDecl::isNoReturn() const {
2662 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2663 hasAttr<C11NoReturnAttr>() ||
2664 getType()->getAs<FunctionType>()->getNoReturnAttr();
2668 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2669 redeclarable_base::setPreviousDecl(PrevDecl);
2671 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2672 FunctionTemplateDecl *PrevFunTmpl
2673 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
2674 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2675 FunTmpl->setPreviousDecl(PrevFunTmpl);
2678 if (PrevDecl && PrevDecl->IsInline)
2682 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
2684 /// \brief Returns a value indicating whether this function
2685 /// corresponds to a builtin function.
2687 /// The function corresponds to a built-in function if it is
2688 /// declared at translation scope or within an extern "C" block and
2689 /// its name matches with the name of a builtin. The returned value
2690 /// will be 0 for functions that do not correspond to a builtin, a
2691 /// value of type \c Builtin::ID if in the target-independent range
2692 /// \c [1,Builtin::First), or a target-specific builtin value.
2693 unsigned FunctionDecl::getBuiltinID() const {
2694 if (!getIdentifier())
2697 unsigned BuiltinID = getIdentifier()->getBuiltinID();
2701 ASTContext &Context = getASTContext();
2702 if (Context.getLangOpts().CPlusPlus) {
2703 const auto *LinkageDecl =
2704 dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
2705 // In C++, the first declaration of a builtin is always inside an implicit
2707 // FIXME: A recognised library function may not be directly in an extern "C"
2708 // declaration, for instance "extern "C" { namespace std { decl } }".
2710 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
2711 Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2713 return Builtin::BI__GetExceptionInfo;
2716 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
2720 // If the function is marked "overloadable", it has a different mangled name
2721 // and is not the C library function.
2722 if (hasAttr<OverloadableAttr>())
2725 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2728 // This function has the name of a known C library
2729 // function. Determine whether it actually refers to the C library
2730 // function or whether it just has the same name.
2732 // If this is a static function, it's not a builtin.
2733 if (getStorageClass() == SC_Static)
2740 /// getNumParams - Return the number of parameters this function must have
2741 /// based on its FunctionType. This is the length of the ParamInfo array
2742 /// after it has been created.
2743 unsigned FunctionDecl::getNumParams() const {
2744 const auto *FPT = getType()->getAs<FunctionProtoType>();
2745 return FPT ? FPT->getNumParams() : 0;
2748 void FunctionDecl::setParams(ASTContext &C,
2749 ArrayRef<ParmVarDecl *> NewParamInfo) {
2750 assert(!ParamInfo && "Already has param info!");
2751 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
2753 // Zero params -> null pointer.
2754 if (!NewParamInfo.empty()) {
2755 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2756 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
2760 void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
2761 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2763 if (!NewDecls.empty()) {
2764 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2765 std::copy(NewDecls.begin(), NewDecls.end(), A);
2766 DeclsInPrototypeScope = llvm::makeArrayRef(A, NewDecls.size());
2767 // Move declarations introduced in prototype to the function context.
2768 for (auto I : NewDecls) {
2769 DeclContext *DC = I->getDeclContext();
2770 // Forward-declared reference to an enumeration is not added to
2771 // declaration scope, so skip declaration that is absent from its
2772 // declaration contexts.
2773 if (DC->containsDecl(I)) {
2775 I->setDeclContext(this);
2782 /// getMinRequiredArguments - Returns the minimum number of arguments
2783 /// needed to call this function. This may be fewer than the number of
2784 /// function parameters, if some of the parameters have default
2785 /// arguments (in C++) or are parameter packs (C++11).
2786 unsigned FunctionDecl::getMinRequiredArguments() const {
2787 if (!getASTContext().getLangOpts().CPlusPlus)
2788 return getNumParams();
2790 unsigned NumRequiredArgs = 0;
2791 for (auto *Param : params())
2792 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2794 return NumRequiredArgs;
2797 /// \brief The combination of the extern and inline keywords under MSVC forces
2798 /// the function to be required.
2800 /// Note: This function assumes that we will only get called when isInlined()
2801 /// would return true for this FunctionDecl.
2802 bool FunctionDecl::isMSExternInline() const {
2803 assert(isInlined() && "expected to get called on an inlined function!");
2805 const ASTContext &Context = getASTContext();
2806 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2807 !hasAttr<DLLExportAttr>())
2810 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
2811 FD = FD->getPreviousDecl())
2812 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
2818 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
2819 if (Redecl->getStorageClass() != SC_Extern)
2822 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
2823 FD = FD->getPreviousDecl())
2824 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
2830 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2831 // Only consider file-scope declarations in this test.
2832 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2835 // Only consider explicit declarations; the presence of a builtin for a
2836 // libcall shouldn't affect whether a definition is externally visible.
2837 if (Redecl->isImplicit())
2840 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2841 return true; // Not an inline definition
2846 /// \brief For a function declaration in C or C++, determine whether this
2847 /// declaration causes the definition to be externally visible.
2849 /// For instance, this determines if adding the current declaration to the set
2850 /// of redeclarations of the given functions causes
2851 /// isInlineDefinitionExternallyVisible to change from false to true.
2852 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2853 assert(!doesThisDeclarationHaveABody() &&
2854 "Must have a declaration without a body.");
2856 ASTContext &Context = getASTContext();
2858 if (Context.getLangOpts().MSVCCompat) {
2859 const FunctionDecl *Definition;
2860 if (hasBody(Definition) && Definition->isInlined() &&
2861 redeclForcesDefMSVC(this))
2865 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2866 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2867 // an externally visible definition.
2869 // FIXME: What happens if gnu_inline gets added on after the first
2871 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
2874 const FunctionDecl *Prev = this;
2875 bool FoundBody = false;
2876 while ((Prev = Prev->getPreviousDecl())) {
2877 FoundBody |= Prev->Body.isValid();
2880 // If it's not the case that both 'inline' and 'extern' are
2881 // specified on the definition, then it is always externally visible.
2882 if (!Prev->isInlineSpecified() ||
2883 Prev->getStorageClass() != SC_Extern)
2885 } else if (Prev->isInlineSpecified() &&
2886 Prev->getStorageClass() != SC_Extern) {
2893 if (Context.getLangOpts().CPlusPlus)
2897 // [...] If all of the file scope declarations for a function in a
2898 // translation unit include the inline function specifier without extern,
2899 // then the definition in that translation unit is an inline definition.
2900 if (isInlineSpecified() && getStorageClass() != SC_Extern)
2902 const FunctionDecl *Prev = this;
2903 bool FoundBody = false;
2904 while ((Prev = Prev->getPreviousDecl())) {
2905 FoundBody |= Prev->Body.isValid();
2906 if (RedeclForcesDefC99(Prev))
2912 SourceRange FunctionDecl::getReturnTypeSourceRange() const {
2913 const TypeSourceInfo *TSI = getTypeSourceInfo();
2915 return SourceRange();
2916 FunctionTypeLoc FTL =
2917 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
2919 return SourceRange();
2921 // Skip self-referential return types.
2922 const SourceManager &SM = getASTContext().getSourceManager();
2923 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
2924 SourceLocation Boundary = getNameInfo().getLocStart();
2925 if (RTRange.isInvalid() || Boundary.isInvalid() ||
2926 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
2927 return SourceRange();
2932 bool FunctionDecl::hasUnusedResultAttr() const {
2933 QualType RetType = getReturnType();
2934 if (RetType->isRecordType()) {
2935 const CXXRecordDecl *Ret = RetType->getAsCXXRecordDecl();
2936 const auto *MD = dyn_cast<CXXMethodDecl>(this);
2937 if (Ret && Ret->hasAttr<WarnUnusedResultAttr>() &&
2938 !(MD && MD->getCorrespondingMethodInClass(Ret, true)))
2941 return hasAttr<WarnUnusedResultAttr>();
2944 /// \brief For an inline function definition in C, or for a gnu_inline function
2945 /// in C++, determine whether the definition will be externally visible.
2947 /// Inline function definitions are always available for inlining optimizations.
2948 /// However, depending on the language dialect, declaration specifiers, and
2949 /// attributes, the definition of an inline function may or may not be
2950 /// "externally" visible to other translation units in the program.
2952 /// In C99, inline definitions are not externally visible by default. However,
2953 /// if even one of the global-scope declarations is marked "extern inline", the
2954 /// inline definition becomes externally visible (C99 6.7.4p6).
2956 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2957 /// definition, we use the GNU semantics for inline, which are nearly the
2958 /// opposite of C99 semantics. In particular, "inline" by itself will create
2959 /// an externally visible symbol, but "extern inline" will not create an
2960 /// externally visible symbol.
2961 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
2962 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
2963 assert(isInlined() && "Function must be inline");
2964 ASTContext &Context = getASTContext();
2966 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2967 // Note: If you change the logic here, please change
2968 // doesDeclarationForceExternallyVisibleDefinition as well.
2970 // If it's not the case that both 'inline' and 'extern' are
2971 // specified on the definition, then this inline definition is
2972 // externally visible.
2973 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
2976 // If any declaration is 'inline' but not 'extern', then this definition
2977 // is externally visible.
2978 for (auto Redecl : redecls()) {
2979 if (Redecl->isInlineSpecified() &&
2980 Redecl->getStorageClass() != SC_Extern)
2987 // The rest of this function is C-only.
2988 assert(!Context.getLangOpts().CPlusPlus &&
2989 "should not use C inline rules in C++");
2992 // [...] If all of the file scope declarations for a function in a
2993 // translation unit include the inline function specifier without extern,
2994 // then the definition in that translation unit is an inline definition.
2995 for (auto Redecl : redecls()) {
2996 if (RedeclForcesDefC99(Redecl))
3001 // An inline definition does not provide an external definition for the
3002 // function, and does not forbid an external definition in another
3003 // translation unit.
3007 /// getOverloadedOperator - Which C++ overloaded operator this
3008 /// function represents, if any.
3009 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
3010 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3011 return getDeclName().getCXXOverloadedOperator();
3016 /// getLiteralIdentifier - The literal suffix identifier this function
3017 /// represents, if any.
3018 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3019 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3020 return getDeclName().getCXXLiteralIdentifier();
3025 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3026 if (TemplateOrSpecialization.isNull())
3027 return TK_NonTemplate;
3028 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3029 return TK_FunctionTemplate;
3030 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3031 return TK_MemberSpecialization;
3032 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3033 return TK_FunctionTemplateSpecialization;
3034 if (TemplateOrSpecialization.is
3035 <DependentFunctionTemplateSpecializationInfo*>())
3036 return TK_DependentFunctionTemplateSpecialization;
3038 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
3041 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
3042 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
3043 return cast<FunctionDecl>(Info->getInstantiatedFrom());
3048 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3049 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>();
3053 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3055 TemplateSpecializationKind TSK) {
3056 assert(TemplateOrSpecialization.isNull() &&
3057 "Member function is already a specialization");
3058 MemberSpecializationInfo *Info
3059 = new (C) MemberSpecializationInfo(FD, TSK);
3060 TemplateOrSpecialization = Info;
3063 FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3064 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3067 void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3068 TemplateOrSpecialization = Template;
3071 bool FunctionDecl::isImplicitlyInstantiable() const {
3072 // If the function is invalid, it can't be implicitly instantiated.
3073 if (isInvalidDecl())
3076 switch (getTemplateSpecializationKind()) {
3077 case TSK_Undeclared:
3078 case TSK_ExplicitInstantiationDefinition:
3081 case TSK_ImplicitInstantiation:
3084 // It is possible to instantiate TSK_ExplicitSpecialization kind
3085 // if the FunctionDecl has a class scope specialization pattern.
3086 case TSK_ExplicitSpecialization:
3087 return getClassScopeSpecializationPattern() != nullptr;
3089 case TSK_ExplicitInstantiationDeclaration:
3094 // Find the actual template from which we will instantiate.
3095 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
3096 bool HasPattern = false;
3098 HasPattern = PatternDecl->hasBody(PatternDecl);
3100 // C++0x [temp.explicit]p9:
3101 // Except for inline functions, other explicit instantiation declarations
3102 // have the effect of suppressing the implicit instantiation of the entity
3103 // to which they refer.
3104 if (!HasPattern || !PatternDecl)
3107 return PatternDecl->isInlined();
3110 bool FunctionDecl::isTemplateInstantiation() const {
3111 switch (getTemplateSpecializationKind()) {
3112 case TSK_Undeclared:
3113 case TSK_ExplicitSpecialization:
3115 case TSK_ImplicitInstantiation:
3116 case TSK_ExplicitInstantiationDeclaration:
3117 case TSK_ExplicitInstantiationDefinition:
3120 llvm_unreachable("All TSK values handled.");
3123 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
3124 // Handle class scope explicit specialization special case.
3125 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3126 return getClassScopeSpecializationPattern();
3128 // If this is a generic lambda call operator specialization, its
3129 // instantiation pattern is always its primary template's pattern
3130 // even if its primary template was instantiated from another
3131 // member template (which happens with nested generic lambdas).
3132 // Since a lambda's call operator's body is transformed eagerly,
3133 // we don't have to go hunting for a prototype definition template
3134 // (i.e. instantiated-from-member-template) to use as an instantiation
3137 if (isGenericLambdaCallOperatorSpecialization(
3138 dyn_cast<CXXMethodDecl>(this))) {
3139 assert(getPrimaryTemplate() && "A generic lambda specialization must be "
3140 "generated from a primary call operator "
3142 assert(getPrimaryTemplate()->getTemplatedDecl()->getBody() &&
3143 "A generic lambda call operator template must always have a body - "
3144 "even if instantiated from a prototype (i.e. as written) member "
3146 return getPrimaryTemplate()->getTemplatedDecl();
3149 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3150 while (Primary->getInstantiatedFromMemberTemplate()) {
3151 // If we have hit a point where the user provided a specialization of
3152 // this template, we're done looking.
3153 if (Primary->isMemberSpecialization())
3155 Primary = Primary->getInstantiatedFromMemberTemplate();
3158 return Primary->getTemplatedDecl();
3161 return getInstantiatedFromMemberFunction();
3164 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
3165 if (FunctionTemplateSpecializationInfo *Info
3166 = TemplateOrSpecialization
3167 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3168 return Info->Template.getPointer();
3173 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3174 return getASTContext().getClassScopeSpecializationPattern(this);
3177 FunctionTemplateSpecializationInfo *
3178 FunctionDecl::getTemplateSpecializationInfo() const {
3179 return TemplateOrSpecialization
3180 .dyn_cast<FunctionTemplateSpecializationInfo *>();
3183 const TemplateArgumentList *
3184 FunctionDecl::getTemplateSpecializationArgs() const {
3185 if (FunctionTemplateSpecializationInfo *Info
3186 = TemplateOrSpecialization
3187 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3188 return Info->TemplateArguments;
3193 const ASTTemplateArgumentListInfo *
3194 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3195 if (FunctionTemplateSpecializationInfo *Info
3196 = TemplateOrSpecialization
3197 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3198 return Info->TemplateArgumentsAsWritten;
3204 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3205 FunctionTemplateDecl *Template,
3206 const TemplateArgumentList *TemplateArgs,
3208 TemplateSpecializationKind TSK,
3209 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3210 SourceLocation PointOfInstantiation) {
3211 assert(TSK != TSK_Undeclared &&
3212 "Must specify the type of function template specialization");
3213 FunctionTemplateSpecializationInfo *Info
3214 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
3216 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3218 TemplateArgsAsWritten,
3219 PointOfInstantiation);
3220 TemplateOrSpecialization = Info;
3221 Template->addSpecialization(Info, InsertPos);
3225 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3226 const UnresolvedSetImpl &Templates,
3227 const TemplateArgumentListInfo &TemplateArgs) {
3228 assert(TemplateOrSpecialization.isNull());
3229 DependentFunctionTemplateSpecializationInfo *Info =
3230 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3232 TemplateOrSpecialization = Info;
3235 DependentFunctionTemplateSpecializationInfo *
3236 FunctionDecl::getDependentSpecializationInfo() const {
3237 return TemplateOrSpecialization
3238 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3241 DependentFunctionTemplateSpecializationInfo *
3242 DependentFunctionTemplateSpecializationInfo::Create(
3243 ASTContext &Context, const UnresolvedSetImpl &Ts,
3244 const TemplateArgumentListInfo &TArgs) {
3245 void *Buffer = Context.Allocate(
3246 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3247 TArgs.size(), Ts.size()));
3248 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3251 DependentFunctionTemplateSpecializationInfo::
3252 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3253 const TemplateArgumentListInfo &TArgs)
3254 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
3256 NumTemplates = Ts.size();
3257 NumArgs = TArgs.size();
3259 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
3260 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3261 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3263 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
3264 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3265 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3268 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
3269 // For a function template specialization, query the specialization
3270 // information object.
3271 FunctionTemplateSpecializationInfo *FTSInfo
3272 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
3274 return FTSInfo->getTemplateSpecializationKind();
3276 MemberSpecializationInfo *MSInfo
3277 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3279 return MSInfo->getTemplateSpecializationKind();
3281 return TSK_Undeclared;
3285 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3286 SourceLocation PointOfInstantiation) {
3287 if (FunctionTemplateSpecializationInfo *FTSInfo
3288 = TemplateOrSpecialization.dyn_cast<
3289 FunctionTemplateSpecializationInfo*>()) {
3290 FTSInfo->setTemplateSpecializationKind(TSK);
3291 if (TSK != TSK_ExplicitSpecialization &&
3292 PointOfInstantiation.isValid() &&
3293 FTSInfo->getPointOfInstantiation().isInvalid())
3294 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3295 } else if (MemberSpecializationInfo *MSInfo
3296 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3297 MSInfo->setTemplateSpecializationKind(TSK);
3298 if (TSK != TSK_ExplicitSpecialization &&
3299 PointOfInstantiation.isValid() &&
3300 MSInfo->getPointOfInstantiation().isInvalid())
3301 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3303 llvm_unreachable("Function cannot have a template specialization kind");
3306 SourceLocation FunctionDecl::getPointOfInstantiation() const {
3307 if (FunctionTemplateSpecializationInfo *FTSInfo
3308 = TemplateOrSpecialization.dyn_cast<
3309 FunctionTemplateSpecializationInfo*>())
3310 return FTSInfo->getPointOfInstantiation();
3311 else if (MemberSpecializationInfo *MSInfo
3312 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
3313 return MSInfo->getPointOfInstantiation();
3315 return SourceLocation();
3318 bool FunctionDecl::isOutOfLine() const {
3319 if (Decl::isOutOfLine())
3322 // If this function was instantiated from a member function of a
3323 // class template, check whether that member function was defined out-of-line.
3324 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3325 const FunctionDecl *Definition;
3326 if (FD->hasBody(Definition))
3327 return Definition->isOutOfLine();
3330 // If this function was instantiated from a function template,
3331 // check whether that function template was defined out-of-line.
3332 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3333 const FunctionDecl *Definition;
3334 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
3335 return Definition->isOutOfLine();
3341 SourceRange FunctionDecl::getSourceRange() const {
3342 return SourceRange(getOuterLocStart(), EndRangeLoc);
3345 unsigned FunctionDecl::getMemoryFunctionKind() const {
3346 IdentifierInfo *FnInfo = getIdentifier();
3351 // Builtin handling.
3352 switch (getBuiltinID()) {
3353 case Builtin::BI__builtin_memset:
3354 case Builtin::BI__builtin___memset_chk:
3355 case Builtin::BImemset:
3356 return Builtin::BImemset;
3358 case Builtin::BI__builtin_memcpy:
3359 case Builtin::BI__builtin___memcpy_chk:
3360 case Builtin::BImemcpy:
3361 return Builtin::BImemcpy;
3363 case Builtin::BI__builtin_memmove:
3364 case Builtin::BI__builtin___memmove_chk:
3365 case Builtin::BImemmove:
3366 return Builtin::BImemmove;
3368 case Builtin::BIstrlcpy:
3369 case Builtin::BI__builtin___strlcpy_chk:
3370 return Builtin::BIstrlcpy;
3372 case Builtin::BIstrlcat:
3373 case Builtin::BI__builtin___strlcat_chk:
3374 return Builtin::BIstrlcat;
3376 case Builtin::BI__builtin_memcmp:
3377 case Builtin::BImemcmp:
3378 return Builtin::BImemcmp;
3380 case Builtin::BI__builtin_strncpy:
3381 case Builtin::BI__builtin___strncpy_chk:
3382 case Builtin::BIstrncpy:
3383 return Builtin::BIstrncpy;
3385 case Builtin::BI__builtin_strncmp:
3386 case Builtin::BIstrncmp:
3387 return Builtin::BIstrncmp;
3389 case Builtin::BI__builtin_strncasecmp:
3390 case Builtin::BIstrncasecmp:
3391 return Builtin::BIstrncasecmp;
3393 case Builtin::BI__builtin_strncat:
3394 case Builtin::BI__builtin___strncat_chk:
3395 case Builtin::BIstrncat:
3396 return Builtin::BIstrncat;
3398 case Builtin::BI__builtin_strndup:
3399 case Builtin::BIstrndup:
3400 return Builtin::BIstrndup;
3402 case Builtin::BI__builtin_strlen:
3403 case Builtin::BIstrlen:
3404 return Builtin::BIstrlen;
3408 if (FnInfo->isStr("memset"))
3409 return Builtin::BImemset;
3410 else if (FnInfo->isStr("memcpy"))
3411 return Builtin::BImemcpy;
3412 else if (FnInfo->isStr("memmove"))
3413 return Builtin::BImemmove;
3414 else if (FnInfo->isStr("memcmp"))
3415 return Builtin::BImemcmp;
3416 else if (FnInfo->isStr("strncpy"))
3417 return Builtin::BIstrncpy;
3418 else if (FnInfo->isStr("strncmp"))
3419 return Builtin::BIstrncmp;
3420 else if (FnInfo->isStr("strncasecmp"))
3421 return Builtin::BIstrncasecmp;
3422 else if (FnInfo->isStr("strncat"))
3423 return Builtin::BIstrncat;
3424 else if (FnInfo->isStr("strndup"))
3425 return Builtin::BIstrndup;
3426 else if (FnInfo->isStr("strlen"))
3427 return Builtin::BIstrlen;
3434 //===----------------------------------------------------------------------===//
3435 // FieldDecl Implementation
3436 //===----------------------------------------------------------------------===//
3438 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
3439 SourceLocation StartLoc, SourceLocation IdLoc,
3440 IdentifierInfo *Id, QualType T,
3441 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
3442 InClassInitStyle InitStyle) {
3443 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3444 BW, Mutable, InitStyle);
3447 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3448 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3449 SourceLocation(), nullptr, QualType(), nullptr,
3450 nullptr, false, ICIS_NoInit);
3453 bool FieldDecl::isAnonymousStructOrUnion() const {
3454 if (!isImplicit() || getDeclName())
3457 if (const auto *Record = getType()->getAs<RecordType>())
3458 return Record->getDecl()->isAnonymousStructOrUnion();
3463 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3464 assert(isBitField() && "not a bitfield");
3465 auto *BitWidth = static_cast<Expr *>(InitStorage.getPointer());
3466 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3469 unsigned FieldDecl::getFieldIndex() const {
3470 const FieldDecl *Canonical = getCanonicalDecl();
3471 if (Canonical != this)
3472 return Canonical->getFieldIndex();
3474 if (CachedFieldIndex) return CachedFieldIndex - 1;
3477 const RecordDecl *RD = getParent();
3479 for (auto *Field : RD->fields()) {
3480 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3484 assert(CachedFieldIndex && "failed to find field in parent");
3485 return CachedFieldIndex - 1;
3488 SourceRange FieldDecl::getSourceRange() const {
3489 switch (InitStorage.getInt()) {
3490 // All three of these cases store an optional Expr*.
3491 case ISK_BitWidthOrNothing:
3492 case ISK_InClassCopyInit:
3493 case ISK_InClassListInit:
3494 if (const auto *E = static_cast<const Expr *>(InitStorage.getPointer()))
3495 return SourceRange(getInnerLocStart(), E->getLocEnd());
3498 case ISK_CapturedVLAType:
3499 return DeclaratorDecl::getSourceRange();
3501 llvm_unreachable("bad init storage kind");
3504 void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
3505 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
3506 "capturing type in non-lambda or captured record.");
3507 assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
3508 InitStorage.getPointer() == nullptr &&
3509 "bit width, initializer or captured type already set");
3510 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3511 ISK_CapturedVLAType);
3514 //===----------------------------------------------------------------------===//
3515 // TagDecl Implementation
3516 //===----------------------------------------------------------------------===//
3518 SourceLocation TagDecl::getOuterLocStart() const {
3519 return getTemplateOrInnerLocStart(this);
3522 SourceRange TagDecl::getSourceRange() const {
3523 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
3524 return SourceRange(getOuterLocStart(), E);
3527 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
3529 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
3530 TypedefNameDeclOrQualifier = TDD;
3531 if (const Type *T = getTypeForDecl()) {
3533 assert(T->isLinkageValid());
3535 assert(isLinkageValid());
3538 void TagDecl::startDefinition() {
3539 IsBeingDefined = true;
3541 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
3542 struct CXXRecordDecl::DefinitionData *Data =
3543 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
3544 for (auto I : redecls())
3545 cast<CXXRecordDecl>(I)->DefinitionData = Data;
3549 void TagDecl::completeDefinition() {
3550 assert((!isa<CXXRecordDecl>(this) ||
3551 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3552 "definition completed but not started");
3554 IsCompleteDefinition = true;
3555 IsBeingDefined = false;
3557 if (ASTMutationListener *L = getASTMutationListener())
3558 L->CompletedTagDefinition(this);
3561 TagDecl *TagDecl::getDefinition() const {
3562 if (isCompleteDefinition())
3563 return const_cast<TagDecl *>(this);
3565 // If it's possible for us to have an out-of-date definition, check now.
3566 if (MayHaveOutOfDateDef) {
3567 if (IdentifierInfo *II = getIdentifier()) {
3568 if (II->isOutOfDate()) {
3569 updateOutOfDate(*II);
3574 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
3575 return CXXRD->getDefinition();
3577 for (auto R : redecls())
3578 if (R->isCompleteDefinition())
3584 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3586 // Make sure the extended qualifier info is allocated.
3588 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
3589 // Set qualifier info.
3590 getExtInfo()->QualifierLoc = QualifierLoc;
3592 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
3594 if (getExtInfo()->NumTemplParamLists == 0) {
3595 getASTContext().Deallocate(getExtInfo());
3596 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
3599 getExtInfo()->QualifierLoc = QualifierLoc;
3604 void TagDecl::setTemplateParameterListsInfo(
3605 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
3606 assert(!TPLists.empty());
3607 // Make sure the extended decl info is allocated.
3609 // Allocate external info struct.
3610 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
3611 // Set the template parameter lists info.
3612 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
3615 //===----------------------------------------------------------------------===//
3616 // EnumDecl Implementation
3617 //===----------------------------------------------------------------------===//
3619 void EnumDecl::anchor() { }
3621 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3622 SourceLocation StartLoc, SourceLocation IdLoc,
3624 EnumDecl *PrevDecl, bool IsScoped,
3625 bool IsScopedUsingClassTag, bool IsFixed) {
3626 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
3627 IsScoped, IsScopedUsingClassTag, IsFixed);
3628 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3629 C.getTypeDeclType(Enum, PrevDecl);
3633 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3635 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3636 nullptr, nullptr, false, false, false);
3637 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3641 SourceRange EnumDecl::getIntegerTypeRange() const {
3642 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3643 return TI->getTypeLoc().getSourceRange();
3644 return SourceRange();
3647 void EnumDecl::completeDefinition(QualType NewType,
3648 QualType NewPromotionType,
3649 unsigned NumPositiveBits,
3650 unsigned NumNegativeBits) {
3651 assert(!isCompleteDefinition() && "Cannot redefine enums!");
3653 IntegerType = NewType.getTypePtr();
3654 PromotionType = NewPromotionType;
3655 setNumPositiveBits(NumPositiveBits);
3656 setNumNegativeBits(NumNegativeBits);
3657 TagDecl::completeDefinition();
3660 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3661 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3662 return MSI->getTemplateSpecializationKind();
3664 return TSK_Undeclared;
3667 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3668 SourceLocation PointOfInstantiation) {
3669 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3670 assert(MSI && "Not an instantiated member enumeration?");
3671 MSI->setTemplateSpecializationKind(TSK);
3672 if (TSK != TSK_ExplicitSpecialization &&
3673 PointOfInstantiation.isValid() &&
3674 MSI->getPointOfInstantiation().isInvalid())
3675 MSI->setPointOfInstantiation(PointOfInstantiation);
3678 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3679 if (SpecializationInfo)
3680 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3685 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3686 TemplateSpecializationKind TSK) {
3687 assert(!SpecializationInfo && "Member enum is already a specialization");
3688 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3691 //===----------------------------------------------------------------------===//
3692 // RecordDecl Implementation
3693 //===----------------------------------------------------------------------===//
3695 RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3696 DeclContext *DC, SourceLocation StartLoc,
3697 SourceLocation IdLoc, IdentifierInfo *Id,
3698 RecordDecl *PrevDecl)
3699 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
3700 HasFlexibleArrayMember = false;
3701 AnonymousStructOrUnion = false;
3702 HasObjectMember = false;
3703 HasVolatileMember = false;
3704 LoadedFieldsFromExternalStorage = false;
3705 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
3708 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3709 SourceLocation StartLoc, SourceLocation IdLoc,
3710 IdentifierInfo *Id, RecordDecl* PrevDecl) {
3711 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
3712 StartLoc, IdLoc, Id, PrevDecl);
3713 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3715 C.getTypeDeclType(R, PrevDecl);
3719 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
3721 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
3722 SourceLocation(), nullptr, nullptr);
3723 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3727 bool RecordDecl::isInjectedClassName() const {
3728 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
3729 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3732 bool RecordDecl::isLambda() const {
3733 if (auto RD = dyn_cast<CXXRecordDecl>(this))
3734 return RD->isLambda();
3738 bool RecordDecl::isCapturedRecord() const {
3739 return hasAttr<CapturedRecordAttr>();
3742 void RecordDecl::setCapturedRecord() {
3743 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
3746 RecordDecl::field_iterator RecordDecl::field_begin() const {
3747 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3748 LoadFieldsFromExternalStorage();
3750 return field_iterator(decl_iterator(FirstDecl));
3753 /// completeDefinition - Notes that the definition of this type is now
3755 void RecordDecl::completeDefinition() {
3756 assert(!isCompleteDefinition() && "Cannot redefine record!");
3757 TagDecl::completeDefinition();
3760 /// isMsStruct - Get whether or not this record uses ms_struct layout.
3761 /// This which can be turned on with an attribute, pragma, or the
3762 /// -mms-bitfields command-line option.
3763 bool RecordDecl::isMsStruct(const ASTContext &C) const {
3764 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
3767 void RecordDecl::LoadFieldsFromExternalStorage() const {
3768 ExternalASTSource *Source = getASTContext().getExternalSource();
3769 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3771 // Notify that we have a RecordDecl doing some initialization.
3772 ExternalASTSource::Deserializing TheFields(Source);
3774 SmallVector<Decl*, 64> Decls;
3775 LoadedFieldsFromExternalStorage = true;
3776 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
3777 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3781 // Check that all decls we got were FieldDecls.
3782 for (unsigned i=0, e=Decls.size(); i != e; ++i)
3783 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
3789 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
3790 /*FieldsAlreadyLoaded=*/false);
3793 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
3794 ASTContext &Context = getASTContext();
3795 if (!Context.getLangOpts().Sanitize.hasOneOf(
3796 SanitizerKind::Address | SanitizerKind::KernelAddress) ||
3797 !Context.getLangOpts().SanitizeAddressFieldPadding)
3799 const auto &Blacklist = Context.getSanitizerBlacklist();
3800 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
3801 // We may be able to relax some of these requirements.
3802 int ReasonToReject = -1;
3803 if (!CXXRD || CXXRD->isExternCContext())
3804 ReasonToReject = 0; // is not C++.
3805 else if (CXXRD->hasAttr<PackedAttr>())
3806 ReasonToReject = 1; // is packed.
3807 else if (CXXRD->isUnion())
3808 ReasonToReject = 2; // is a union.
3809 else if (CXXRD->isTriviallyCopyable())
3810 ReasonToReject = 3; // is trivially copyable.
3811 else if (CXXRD->hasTrivialDestructor())
3812 ReasonToReject = 4; // has trivial destructor.
3813 else if (CXXRD->isStandardLayout())
3814 ReasonToReject = 5; // is standard layout.
3815 else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
3816 ReasonToReject = 6; // is in a blacklisted file.
3817 else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(),
3819 ReasonToReject = 7; // is blacklisted.
3822 if (ReasonToReject >= 0)
3823 Context.getDiagnostics().Report(
3825 diag::remark_sanitize_address_insert_extra_padding_rejected)
3826 << getQualifiedNameAsString() << ReasonToReject;
3828 Context.getDiagnostics().Report(
3830 diag::remark_sanitize_address_insert_extra_padding_accepted)
3831 << getQualifiedNameAsString();
3833 return ReasonToReject < 0;
3836 const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
3837 for (const auto *I : fields()) {
3838 if (I->getIdentifier())
3841 if (const auto *RT = I->getType()->getAs<RecordType>())
3842 if (const FieldDecl *NamedDataMember =
3843 RT->getDecl()->findFirstNamedDataMember())
3844 return NamedDataMember;
3847 // We didn't find a named data member.
3852 //===----------------------------------------------------------------------===//
3853 // BlockDecl Implementation
3854 //===----------------------------------------------------------------------===//
3856 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
3857 assert(!ParamInfo && "Already has param info!");
3859 // Zero params -> null pointer.
3860 if (!NewParamInfo.empty()) {
3861 NumParams = NewParamInfo.size();
3862 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3863 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3867 void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
3868 bool CapturesCXXThis) {
3869 this->CapturesCXXThis = CapturesCXXThis;
3870 this->NumCaptures = Captures.size();
3872 if (Captures.empty()) {
3873 this->Captures = nullptr;
3877 this->Captures = Captures.copy(Context).data();
3880 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3881 for (const auto &I : captures())
3882 // Only auto vars can be captured, so no redeclaration worries.
3883 if (I.getVariable() == variable)
3889 SourceRange BlockDecl::getSourceRange() const {
3890 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3893 //===----------------------------------------------------------------------===//
3894 // Other Decl Allocation/Deallocation Method Implementations
3895 //===----------------------------------------------------------------------===//
3897 void TranslationUnitDecl::anchor() { }
3899 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
3900 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
3903 void ExternCContextDecl::anchor() { }
3905 ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
3906 TranslationUnitDecl *DC) {
3907 return new (C, DC) ExternCContextDecl(DC);
3910 void LabelDecl::anchor() { }
3912 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3913 SourceLocation IdentL, IdentifierInfo *II) {
3914 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
3917 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3918 SourceLocation IdentL, IdentifierInfo *II,
3919 SourceLocation GnuLabelL) {
3920 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
3921 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
3924 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3925 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
3929 void LabelDecl::setMSAsmLabel(StringRef Name) {
3930 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
3931 memcpy(Buffer, Name.data(), Name.size());
3932 Buffer[Name.size()] = '\0';
3936 void ValueDecl::anchor() { }
3938 bool ValueDecl::isWeak() const {
3939 for (const auto *I : attrs())
3940 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
3943 return isWeakImported();
3946 void ImplicitParamDecl::anchor() { }
3948 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
3949 SourceLocation IdLoc,
3952 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type);
3955 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
3957 return new (C, ID) ImplicitParamDecl(C, nullptr, SourceLocation(), nullptr,
3961 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
3962 SourceLocation StartLoc,
3963 const DeclarationNameInfo &NameInfo,
3964 QualType T, TypeSourceInfo *TInfo,
3966 bool isInlineSpecified,
3967 bool hasWrittenPrototype,
3968 bool isConstexprSpecified) {
3970 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
3971 SC, isInlineSpecified, isConstexprSpecified);
3972 New->HasWrittenPrototype = hasWrittenPrototype;
3976 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3977 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
3978 DeclarationNameInfo(), QualType(), nullptr,
3979 SC_None, false, false);
3982 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3983 return new (C, DC) BlockDecl(DC, L);
3986 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3987 return new (C, ID) BlockDecl(nullptr, SourceLocation());
3990 CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
3991 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
3992 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
3994 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
3995 unsigned NumParams) {
3996 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
3997 CapturedDecl(DC, NumParams);
4000 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4001 unsigned NumParams) {
4002 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
4003 CapturedDecl(nullptr, NumParams);
4006 Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4007 void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4009 bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4010 void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4012 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4014 IdentifierInfo *Id, QualType T,
4015 Expr *E, const llvm::APSInt &V) {
4016 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
4020 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4021 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4022 QualType(), nullptr, llvm::APSInt());
4025 void IndirectFieldDecl::anchor() { }
4027 IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4028 SourceLocation L, DeclarationName N,
4029 QualType T, NamedDecl **CH, unsigned CHS)
4030 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH), ChainingSize(CHS) {
4031 // In C++, indirect field declarations conflict with tag declarations in the
4032 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4033 if (C.getLangOpts().CPlusPlus)
4034 IdentifierNamespace |= IDNS_Tag;
4038 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
4039 IdentifierInfo *Id, QualType T, NamedDecl **CH,
4041 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH, CHS);
4044 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4046 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
4047 DeclarationName(), QualType(), nullptr,
4051 SourceRange EnumConstantDecl::getSourceRange() const {
4052 SourceLocation End = getLocation();
4054 End = Init->getLocEnd();
4055 return SourceRange(getLocation(), End);
4058 void TypeDecl::anchor() { }
4060 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
4061 SourceLocation StartLoc, SourceLocation IdLoc,
4062 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
4063 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
4066 void TypedefNameDecl::anchor() { }
4068 TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4069 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4070 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4071 auto *ThisTypedef = this;
4072 if (AnyRedecl && OwningTypedef) {
4073 OwningTypedef = OwningTypedef->getCanonicalDecl();
4074 ThisTypedef = ThisTypedef->getCanonicalDecl();
4076 if (OwningTypedef == ThisTypedef)
4077 return TT->getDecl();
4083 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4084 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
4088 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4089 SourceLocation StartLoc,
4090 SourceLocation IdLoc, IdentifierInfo *Id,
4091 TypeSourceInfo *TInfo) {
4092 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
4095 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4096 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
4097 SourceLocation(), nullptr, nullptr);
4100 SourceRange TypedefDecl::getSourceRange() const {
4101 SourceLocation RangeEnd = getLocation();
4102 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4103 if (typeIsPostfix(TInfo->getType()))
4104 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4106 return SourceRange(getLocStart(), RangeEnd);
4109 SourceRange TypeAliasDecl::getSourceRange() const {
4110 SourceLocation RangeEnd = getLocStart();
4111 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4112 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4113 return SourceRange(getLocStart(), RangeEnd);
4116 void FileScopeAsmDecl::anchor() { }
4118 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
4120 SourceLocation AsmLoc,
4121 SourceLocation RParenLoc) {
4122 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
4125 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
4127 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4131 void EmptyDecl::anchor() {}
4133 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
4134 return new (C, DC) EmptyDecl(DC, L);
4137 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4138 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
4141 //===----------------------------------------------------------------------===//
4142 // ImportDecl Implementation
4143 //===----------------------------------------------------------------------===//
4145 /// \brief Retrieve the number of module identifiers needed to name the given
4147 static unsigned getNumModuleIdentifiers(Module *Mod) {
4148 unsigned Result = 1;
4149 while (Mod->Parent) {
4156 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
4158 ArrayRef<SourceLocation> IdentifierLocs)
4159 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
4162 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
4163 auto *StoredLocs = getTrailingObjects<SourceLocation>();
4164 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4168 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
4169 Module *Imported, SourceLocation EndLoc)
4170 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
4173 *getTrailingObjects<SourceLocation>() = EndLoc;
4176 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
4177 SourceLocation StartLoc, Module *Imported,
4178 ArrayRef<SourceLocation> IdentifierLocs) {
4180 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
4181 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
4184 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
4185 SourceLocation StartLoc,
4187 SourceLocation EndLoc) {
4188 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
4189 ImportDecl(DC, StartLoc, Imported, EndLoc);
4190 Import->setImplicit();
4194 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4195 unsigned NumLocations) {
4196 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
4197 ImportDecl(EmptyShell());
4200 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4201 if (!ImportedAndComplete.getInt())
4204 const auto *StoredLocs = getTrailingObjects<SourceLocation>();
4205 return llvm::makeArrayRef(StoredLocs,
4206 getNumModuleIdentifiers(getImportedModule()));
4209 SourceRange ImportDecl::getSourceRange() const {
4210 if (!ImportedAndComplete.getInt())
4211 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
4213 return SourceRange(getLocation(), getIdentifierLocs().back());