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/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/PrettyPrinter.h"
24 #include "clang/AST/Stmt.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/Basic/Builtins.h"
27 #include "clang/Basic/IdentifierTable.h"
28 #include "clang/Basic/Module.h"
29 #include "clang/Basic/Specifiers.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/type_traits.h"
35 using namespace clang;
37 //===----------------------------------------------------------------------===//
38 // NamedDecl Implementation
39 //===----------------------------------------------------------------------===//
41 // Visibility rules aren't rigorously externally specified, but here
42 // are the basic principles behind what we implement:
44 // 1. An explicit visibility attribute is generally a direct expression
45 // of the user's intent and should be honored. Only the innermost
46 // visibility attribute applies. If no visibility attribute applies,
47 // global visibility settings are considered.
49 // 2. There is one caveat to the above: on or in a template pattern,
50 // an explicit visibility attribute is just a default rule, and
51 // visibility can be decreased by the visibility of template
52 // arguments. But this, too, has an exception: an attribute on an
53 // explicit specialization or instantiation causes all the visibility
54 // restrictions of the template arguments to be ignored.
56 // 3. A variable that does not otherwise have explicit visibility can
57 // be restricted by the visibility of its type.
59 // 4. A visibility restriction is explicit if it comes from an
60 // attribute (or something like it), not a global visibility setting.
61 // When emitting a reference to an external symbol, visibility
62 // restrictions are ignored unless they are explicit.
64 // 5. When computing the visibility of a non-type, including a
65 // non-type member of a class, only non-type visibility restrictions
66 // are considered: the 'visibility' attribute, global value-visibility
67 // settings, and a few special cases like __private_extern.
69 // 6. When computing the visibility of a type, including a type member
70 // of a class, only type visibility restrictions are considered:
71 // the 'type_visibility' attribute and global type-visibility settings.
72 // However, a 'visibility' attribute counts as a 'type_visibility'
73 // attribute on any declaration that only has the former.
75 // The visibility of a "secondary" entity, like a template argument,
76 // is computed using the kind of that entity, not the kind of the
77 // primary entity for which we are computing visibility. For example,
78 // the visibility of a specialization of either of these templates:
79 // template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
80 // template <class T, bool (&compare)(T, X)> class matcher;
81 // is restricted according to the type visibility of the argument 'T',
82 // the type visibility of 'bool(&)(T,X)', and the value visibility of
83 // the argument function 'compare'. That 'has_match' is a value
84 // and 'matcher' is a type only matters when looking for attributes
85 // and settings from the immediate context.
87 const unsigned IgnoreExplicitVisibilityBit = 2;
89 /// Kinds of LV computation. The linkage side of the computation is
90 /// always the same, but different things can change how visibility is
92 enum LVComputationKind {
93 /// Do an LV computation for, ultimately, a type.
94 /// Visibility may be restricted by type visibility settings and
95 /// the visibility of template arguments.
96 LVForType = NamedDecl::VisibilityForType,
98 /// Do an LV computation for, ultimately, a non-type declaration.
99 /// Visibility may be restricted by value visibility settings and
100 /// the visibility of template arguments.
101 LVForValue = NamedDecl::VisibilityForValue,
103 /// Do an LV computation for, ultimately, a type that already has
104 /// some sort of explicit visibility. Visibility may only be
105 /// restricted by the visibility of template arguments.
106 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
108 /// Do an LV computation for, ultimately, a non-type declaration
109 /// that already has some sort of explicit visibility. Visibility
110 /// may only be restricted by the visibility of template arguments.
111 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit)
114 /// Does this computation kind permit us to consider additional
115 /// visibility settings from attributes and the like?
116 static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
117 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
120 /// Given an LVComputationKind, return one of the same type/value sort
121 /// that records that it already has explicit visibility.
122 static LVComputationKind
123 withExplicitVisibilityAlready(LVComputationKind oldKind) {
124 LVComputationKind newKind =
125 static_cast<LVComputationKind>(unsigned(oldKind) |
126 IgnoreExplicitVisibilityBit);
127 assert(oldKind != LVForType || newKind == LVForExplicitType);
128 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
129 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
130 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
134 static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
135 LVComputationKind kind) {
136 assert(!hasExplicitVisibilityAlready(kind) &&
137 "asking for explicit visibility when we shouldn't be");
138 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
141 /// Is the given declaration a "type" or a "value" for the purposes of
142 /// visibility computation?
143 static bool usesTypeVisibility(const NamedDecl *D) {
144 return isa<TypeDecl>(D) ||
145 isa<ClassTemplateDecl>(D) ||
146 isa<ObjCInterfaceDecl>(D);
149 /// Does the given declaration have member specialization information,
150 /// and if so, is it an explicit specialization?
151 template <class T> static typename
152 llvm::enable_if_c<!llvm::is_base_of<RedeclarableTemplateDecl, T>::value,
154 isExplicitMemberSpecialization(const T *D) {
155 if (const MemberSpecializationInfo *member =
156 D->getMemberSpecializationInfo()) {
157 return member->isExplicitSpecialization();
162 /// For templates, this question is easier: a member template can't be
163 /// explicitly instantiated, so there's a single bit indicating whether
164 /// or not this is an explicit member specialization.
165 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
166 return D->isMemberSpecialization();
169 /// Given a visibility attribute, return the explicit visibility
170 /// associated with it.
172 static Visibility getVisibilityFromAttr(const T *attr) {
173 switch (attr->getVisibility()) {
175 return DefaultVisibility;
177 return HiddenVisibility;
179 return ProtectedVisibility;
181 llvm_unreachable("bad visibility kind");
184 /// Return the explicit visibility of the given declaration.
185 static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
186 NamedDecl::ExplicitVisibilityKind kind) {
187 // If we're ultimately computing the visibility of a type, look for
188 // a 'type_visibility' attribute before looking for 'visibility'.
189 if (kind == NamedDecl::VisibilityForType) {
190 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
191 return getVisibilityFromAttr(A);
195 // If this declaration has an explicit visibility attribute, use it.
196 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
197 return getVisibilityFromAttr(A);
200 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
201 // implies visibility(default).
202 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
203 for (specific_attr_iterator<AvailabilityAttr>
204 A = D->specific_attr_begin<AvailabilityAttr>(),
205 AEnd = D->specific_attr_end<AvailabilityAttr>();
207 if ((*A)->getPlatform()->getName().equals("macosx"))
208 return DefaultVisibility;
214 /// \brief Get the most restrictive linkage for the types in the given
215 /// template parameter list. For visibility purposes, template
216 /// parameters are part of the signature of a template.
218 getLVForTemplateParameterList(const TemplateParameterList *params) {
220 for (TemplateParameterList::const_iterator P = params->begin(),
221 PEnd = params->end();
224 // Template type parameters are the most common and never
225 // contribute to visibility, pack or not.
226 if (isa<TemplateTypeParmDecl>(*P))
229 // Non-type template parameters can be restricted by the value type, e.g.
230 // template <enum X> class A { ... };
231 // We have to be careful here, though, because we can be dealing with
233 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
234 // Handle the non-pack case first.
235 if (!NTTP->isExpandedParameterPack()) {
236 if (!NTTP->getType()->isDependentType()) {
237 LV.merge(NTTP->getType()->getLinkageAndVisibility());
242 // Look at all the types in an expanded pack.
243 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
244 QualType type = NTTP->getExpansionType(i);
245 if (!type->isDependentType())
246 LV.merge(type->getLinkageAndVisibility());
251 // Template template parameters can be restricted by their
252 // template parameters, recursively.
253 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
255 // Handle the non-pack case first.
256 if (!TTP->isExpandedParameterPack()) {
257 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters()));
261 // Look at all expansions in an expanded pack.
262 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
264 LV.merge(getLVForTemplateParameterList(
265 TTP->getExpansionTemplateParameters(i)));
272 /// getLVForDecl - Get the linkage and visibility for the given declaration.
273 static LinkageInfo getLVForDecl(const NamedDecl *D,
274 LVComputationKind computation);
276 /// \brief Get the most restrictive linkage for the types and
277 /// declarations in the given template argument list.
279 /// Note that we don't take an LVComputationKind because we always
280 /// want to honor the visibility of template arguments in the same way.
282 getLVForTemplateArgumentList(ArrayRef<TemplateArgument> args) {
285 for (unsigned i = 0, e = args.size(); i != e; ++i) {
286 const TemplateArgument &arg = args[i];
287 switch (arg.getKind()) {
288 case TemplateArgument::Null:
289 case TemplateArgument::Integral:
290 case TemplateArgument::Expression:
293 case TemplateArgument::Type:
294 LV.merge(arg.getAsType()->getLinkageAndVisibility());
297 case TemplateArgument::Declaration:
298 if (NamedDecl *ND = dyn_cast<NamedDecl>(arg.getAsDecl())) {
299 assert(!usesTypeVisibility(ND));
300 LV.merge(getLVForDecl(ND, LVForValue));
304 case TemplateArgument::NullPtr:
305 LV.merge(arg.getNullPtrType()->getLinkageAndVisibility());
308 case TemplateArgument::Template:
309 case TemplateArgument::TemplateExpansion:
310 if (TemplateDecl *Template
311 = arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
312 LV.merge(getLVForDecl(Template, LVForValue));
315 case TemplateArgument::Pack:
316 LV.merge(getLVForTemplateArgumentList(arg.getPackAsArray()));
319 llvm_unreachable("bad template argument kind");
326 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs) {
327 return getLVForTemplateArgumentList(TArgs.asArray());
330 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
331 const FunctionTemplateSpecializationInfo *specInfo) {
332 // Include visibility from the template parameters and arguments
333 // only if this is not an explicit instantiation or specialization
334 // with direct explicit visibility. (Implicit instantiations won't
335 // have a direct attribute.)
336 if (!specInfo->isExplicitInstantiationOrSpecialization())
339 return !fn->hasAttr<VisibilityAttr>();
342 /// Merge in template-related linkage and visibility for the given
343 /// function template specialization.
345 /// We don't need a computation kind here because we can assume
348 /// \param[out] LV the computation to use for the parent
350 mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
351 const FunctionTemplateSpecializationInfo *specInfo) {
352 bool considerVisibility =
353 shouldConsiderTemplateVisibility(fn, specInfo);
355 // Merge information from the template parameters.
356 FunctionTemplateDecl *temp = specInfo->getTemplate();
358 getLVForTemplateParameterList(temp->getTemplateParameters());
359 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
361 // Merge information from the template arguments.
362 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
363 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
364 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
367 /// Does the given declaration have a direct visibility attribute
368 /// that would match the given rules?
369 static bool hasDirectVisibilityAttribute(const NamedDecl *D,
370 LVComputationKind computation) {
371 switch (computation) {
373 case LVForExplicitType:
374 if (D->hasAttr<TypeVisibilityAttr>())
378 case LVForExplicitValue:
379 if (D->hasAttr<VisibilityAttr>())
383 llvm_unreachable("bad visibility computation kind");
386 /// Should we consider visibility associated with the template
387 /// arguments and parameters of the given class template specialization?
388 static bool shouldConsiderTemplateVisibility(
389 const ClassTemplateSpecializationDecl *spec,
390 LVComputationKind computation) {
391 // Include visibility from the template parameters and arguments
392 // only if this is not an explicit instantiation or specialization
393 // with direct explicit visibility (and note that implicit
394 // instantiations won't have a direct attribute).
396 // Furthermore, we want to ignore template parameters and arguments
397 // for an explicit specialization when computing the visibility of a
398 // member thereof with explicit visibility.
400 // This is a bit complex; let's unpack it.
402 // An explicit class specialization is an independent, top-level
403 // declaration. As such, if it or any of its members has an
404 // explicit visibility attribute, that must directly express the
405 // user's intent, and we should honor it. The same logic applies to
406 // an explicit instantiation of a member of such a thing.
408 // Fast path: if this is not an explicit instantiation or
409 // specialization, we always want to consider template-related
410 // visibility restrictions.
411 if (!spec->isExplicitInstantiationOrSpecialization())
414 // This is the 'member thereof' check.
415 if (spec->isExplicitSpecialization() &&
416 hasExplicitVisibilityAlready(computation))
419 return !hasDirectVisibilityAttribute(spec, computation);
422 /// Merge in template-related linkage and visibility for the given
423 /// class template specialization.
424 static void mergeTemplateLV(LinkageInfo &LV,
425 const ClassTemplateSpecializationDecl *spec,
426 LVComputationKind computation) {
427 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
429 // Merge information from the template parameters, but ignore
430 // visibility if we're only considering template arguments.
432 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
434 getLVForTemplateParameterList(temp->getTemplateParameters());
435 LV.mergeMaybeWithVisibility(tempLV,
436 considerVisibility && !hasExplicitVisibilityAlready(computation));
438 // Merge information from the template arguments. We ignore
439 // template-argument visibility if we've got an explicit
440 // instantiation with a visibility attribute.
441 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
442 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
443 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
446 static bool useInlineVisibilityHidden(const NamedDecl *D) {
447 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
448 const LangOptions &Opts = D->getASTContext().getLangOpts();
449 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
452 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
456 TemplateSpecializationKind TSK = TSK_Undeclared;
457 if (FunctionTemplateSpecializationInfo *spec
458 = FD->getTemplateSpecializationInfo()) {
459 TSK = spec->getTemplateSpecializationKind();
460 } else if (MemberSpecializationInfo *MSI =
461 FD->getMemberSpecializationInfo()) {
462 TSK = MSI->getTemplateSpecializationKind();
465 const FunctionDecl *Def = 0;
466 // InlineVisibilityHidden only applies to definitions, and
467 // isInlined() only gives meaningful answers on definitions
469 return TSK != TSK_ExplicitInstantiationDeclaration &&
470 TSK != TSK_ExplicitInstantiationDefinition &&
471 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
474 template <typename T> static bool isInExternCContext(T *D) {
475 const T *First = D->getFirstDeclaration();
476 return First->getDeclContext()->isExternCContext();
479 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
480 LVComputationKind computation) {
481 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
482 "Not a name having namespace scope");
483 ASTContext &Context = D->getASTContext();
485 // C++ [basic.link]p3:
486 // A name having namespace scope (3.3.6) has internal linkage if it
488 // - an object, reference, function or function template that is
489 // explicitly declared static; or,
490 // (This bullet corresponds to C99 6.2.2p3.)
491 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
492 // Explicitly declared static.
493 if (Var->getStorageClass() == SC_Static)
494 return LinkageInfo::internal();
496 // - a non-volatile object or reference that is explicitly declared const
497 // or constexpr and neither explicitly declared extern nor previously
498 // declared to have external linkage; or (there is no equivalent in C99)
499 if (Context.getLangOpts().CPlusPlus &&
500 Var->getType().isConstQualified() &&
501 !Var->getType().isVolatileQualified()) {
502 const VarDecl *PrevVar = Var->getPreviousDecl();
504 return PrevVar->getLinkageAndVisibility();
506 if (Var->getStorageClass() != SC_Extern &&
507 Var->getStorageClass() != SC_PrivateExtern)
508 return LinkageInfo::internal();
511 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
512 PrevVar = PrevVar->getPreviousDecl()) {
513 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
514 Var->getStorageClass() == SC_None)
515 return PrevVar->getLinkageAndVisibility();
516 // Explicitly declared static.
517 if (PrevVar->getStorageClass() == SC_Static)
518 return LinkageInfo::internal();
520 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
522 // A non-member function template can have internal linkage; any
523 // other template name shall have external linkage.
524 const FunctionDecl *Function = 0;
525 if (const FunctionTemplateDecl *FunTmpl
526 = dyn_cast<FunctionTemplateDecl>(D))
527 Function = FunTmpl->getTemplatedDecl();
529 Function = cast<FunctionDecl>(D);
531 // Explicitly declared static.
532 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
533 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
534 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
535 // - a data member of an anonymous union.
536 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
537 return LinkageInfo::internal();
540 if (D->isInAnonymousNamespace()) {
541 const VarDecl *Var = dyn_cast<VarDecl>(D);
542 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
543 if ((!Var || !isInExternCContext(Var)) &&
544 (!Func || !isInExternCContext(Func)))
545 return LinkageInfo::uniqueExternal();
548 // Set up the defaults.
551 // If the declaration of an identifier for an object has file
552 // scope and no storage-class specifier, its linkage is
556 if (!hasExplicitVisibilityAlready(computation)) {
557 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
558 LV.mergeVisibility(*Vis, true);
560 // If we're declared in a namespace with a visibility attribute,
561 // use that namespace's visibility, and it still counts as explicit.
562 for (const DeclContext *DC = D->getDeclContext();
563 !isa<TranslationUnitDecl>(DC);
564 DC = DC->getParent()) {
565 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
567 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
568 LV.mergeVisibility(*Vis, true);
574 // Add in global settings if the above didn't give us direct visibility.
575 if (!LV.isVisibilityExplicit()) {
576 // Use global type/value visibility as appropriate.
577 Visibility globalVisibility;
578 if (computation == LVForValue) {
579 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
581 assert(computation == LVForType);
582 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
584 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
586 // If we're paying attention to global visibility, apply
587 // -finline-visibility-hidden if this is an inline method.
588 if (useInlineVisibilityHidden(D))
589 LV.mergeVisibility(HiddenVisibility, true);
593 // C++ [basic.link]p4:
595 // A name having namespace scope has external linkage if it is the
598 // - an object or reference, unless it has internal linkage; or
599 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
600 // GCC applies the following optimization to variables and static
601 // data members, but not to functions:
603 // Modify the variable's LV by the LV of its type unless this is
604 // C or extern "C". This follows from [basic.link]p9:
605 // A type without linkage shall not be used as the type of a
606 // variable or function with external linkage unless
607 // - the entity has C language linkage, or
608 // - the entity is declared within an unnamed namespace, or
609 // - the entity is not used or is defined in the same
611 // and [basic.link]p10:
612 // ...the types specified by all declarations referring to a
613 // given variable or function shall be identical...
614 // C does not have an equivalent rule.
616 // Ignore this if we've got an explicit attribute; the user
617 // probably knows what they're doing.
619 // Note that we don't want to make the variable non-external
620 // because of this, but unique-external linkage suits us.
621 if (Context.getLangOpts().CPlusPlus && !isInExternCContext(Var)) {
622 LinkageInfo TypeLV = Var->getType()->getLinkageAndVisibility();
623 if (TypeLV.getLinkage() != ExternalLinkage)
624 return LinkageInfo::uniqueExternal();
625 if (!LV.isVisibilityExplicit())
626 LV.mergeVisibility(TypeLV);
629 if (Var->getStorageClass() == SC_PrivateExtern)
630 LV.mergeVisibility(HiddenVisibility, true);
632 // Note that Sema::MergeVarDecl already takes care of implementing
633 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
636 // - a function, unless it has internal linkage; or
637 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
638 // In theory, we can modify the function's LV by the LV of its
639 // type unless it has C linkage (see comment above about variables
640 // for justification). In practice, GCC doesn't do this, so it's
641 // just too painful to make work.
643 if (Function->getStorageClass() == SC_PrivateExtern)
644 LV.mergeVisibility(HiddenVisibility, true);
646 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
647 // merging storage classes and visibility attributes, so we don't have to
648 // look at previous decls in here.
650 // In C++, then if the type of the function uses a type with
651 // unique-external linkage, it's not legally usable from outside
652 // this translation unit. However, we should use the C linkage
653 // rules instead for extern "C" declarations.
654 if (Context.getLangOpts().CPlusPlus &&
655 !Function->getDeclContext()->isExternCContext() &&
656 Function->getType()->getLinkage() == UniqueExternalLinkage)
657 return LinkageInfo::uniqueExternal();
659 // Consider LV from the template and the template arguments.
660 // We're at file scope, so we do not need to worry about nested
662 if (FunctionTemplateSpecializationInfo *specInfo
663 = Function->getTemplateSpecializationInfo()) {
664 mergeTemplateLV(LV, Function, specInfo);
667 // - a named class (Clause 9), or an unnamed class defined in a
668 // typedef declaration in which the class has the typedef name
669 // for linkage purposes (7.1.3); or
670 // - a named enumeration (7.2), or an unnamed enumeration
671 // defined in a typedef declaration in which the enumeration
672 // has the typedef name for linkage purposes (7.1.3); or
673 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
674 // Unnamed tags have no linkage.
675 if (!Tag->hasNameForLinkage())
676 return LinkageInfo::none();
678 // If this is a class template specialization, consider the
679 // linkage of the template and template arguments. We're at file
680 // scope, so we do not need to worry about nested specializations.
681 if (const ClassTemplateSpecializationDecl *spec
682 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
683 mergeTemplateLV(LV, spec, computation);
686 // - an enumerator belonging to an enumeration with external linkage;
687 } else if (isa<EnumConstantDecl>(D)) {
688 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
690 if (!isExternalLinkage(EnumLV.getLinkage()))
691 return LinkageInfo::none();
694 // - a template, unless it is a function template that has
695 // internal linkage (Clause 14);
696 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
697 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
699 getLVForTemplateParameterList(temp->getTemplateParameters());
700 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
702 // - a namespace (7.3), unless it is declared within an unnamed
704 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
707 // By extension, we assign external linkage to Objective-C
709 } else if (isa<ObjCInterfaceDecl>(D)) {
712 // Everything not covered here has no linkage.
714 return LinkageInfo::none();
717 // If we ended up with non-external linkage, visibility should
718 // always be default.
719 if (LV.getLinkage() != ExternalLinkage)
720 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
725 static LinkageInfo getLVForClassMember(const NamedDecl *D,
726 LVComputationKind computation) {
727 // Only certain class members have linkage. Note that fields don't
728 // really have linkage, but it's convenient to say they do for the
729 // purposes of calculating linkage of pointer-to-data-member
730 // template arguments.
731 if (!(isa<CXXMethodDecl>(D) ||
735 return LinkageInfo::none();
739 // If we have an explicit visibility attribute, merge that in.
740 if (!hasExplicitVisibilityAlready(computation)) {
741 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
742 LV.mergeVisibility(*Vis, true);
743 // If we're paying attention to global visibility, apply
744 // -finline-visibility-hidden if this is an inline method.
746 // Note that we do this before merging information about
747 // the class visibility.
748 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
749 LV.mergeVisibility(HiddenVisibility, true);
752 // If this class member has an explicit visibility attribute, the only
753 // thing that can change its visibility is the template arguments, so
754 // only look for them when processing the class.
755 LVComputationKind classComputation = computation;
756 if (LV.isVisibilityExplicit())
757 classComputation = withExplicitVisibilityAlready(computation);
759 LinkageInfo classLV =
760 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
761 if (!isExternalLinkage(classLV.getLinkage()))
762 return LinkageInfo::none();
764 // If the class already has unique-external linkage, we can't improve.
765 if (classLV.getLinkage() == UniqueExternalLinkage)
766 return LinkageInfo::uniqueExternal();
768 // Otherwise, don't merge in classLV yet, because in certain cases
769 // we need to completely ignore the visibility from it.
771 // Specifically, if this decl exists and has an explicit attribute.
772 const NamedDecl *explicitSpecSuppressor = 0;
774 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
775 // If the type of the function uses a type with unique-external
776 // linkage, it's not legally usable from outside this translation unit.
777 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
778 return LinkageInfo::uniqueExternal();
780 // If this is a method template specialization, use the linkage for
781 // the template parameters and arguments.
782 if (FunctionTemplateSpecializationInfo *spec
783 = MD->getTemplateSpecializationInfo()) {
784 mergeTemplateLV(LV, MD, spec);
785 if (spec->isExplicitSpecialization()) {
786 explicitSpecSuppressor = MD;
787 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
788 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
790 } else if (isExplicitMemberSpecialization(MD)) {
791 explicitSpecSuppressor = MD;
794 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
795 if (const ClassTemplateSpecializationDecl *spec
796 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
797 mergeTemplateLV(LV, spec, computation);
798 if (spec->isExplicitSpecialization()) {
799 explicitSpecSuppressor = spec;
801 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
802 if (isExplicitMemberSpecialization(temp)) {
803 explicitSpecSuppressor = temp->getTemplatedDecl();
806 } else if (isExplicitMemberSpecialization(RD)) {
807 explicitSpecSuppressor = RD;
810 // Static data members.
811 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
812 // Modify the variable's linkage by its type, but ignore the
813 // type's visibility unless it's a definition.
814 LinkageInfo typeLV = VD->getType()->getLinkageAndVisibility();
815 LV.mergeMaybeWithVisibility(typeLV,
816 !LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit());
818 if (isExplicitMemberSpecialization(VD)) {
819 explicitSpecSuppressor = VD;
823 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
824 bool considerVisibility =
825 (!LV.isVisibilityExplicit() &&
826 !classLV.isVisibilityExplicit() &&
827 !hasExplicitVisibilityAlready(computation));
829 getLVForTemplateParameterList(temp->getTemplateParameters());
830 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
832 if (const RedeclarableTemplateDecl *redeclTemp =
833 dyn_cast<RedeclarableTemplateDecl>(temp)) {
834 if (isExplicitMemberSpecialization(redeclTemp)) {
835 explicitSpecSuppressor = temp->getTemplatedDecl();
840 // We should never be looking for an attribute directly on a template.
841 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
843 // If this member is an explicit member specialization, and it has
844 // an explicit attribute, ignore visibility from the parent.
845 bool considerClassVisibility = true;
846 if (explicitSpecSuppressor &&
847 // optimization: hasDVA() is true only with explicit visibility.
848 LV.isVisibilityExplicit() &&
849 classLV.getVisibility() != DefaultVisibility &&
850 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
851 considerClassVisibility = false;
854 // Finally, merge in information from the class.
855 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
859 void NamedDecl::anchor() { }
861 bool NamedDecl::isLinkageValid() const {
862 if (!HasCachedLinkage)
865 return getLVForDecl(this, LVForExplicitValue).getLinkage() ==
866 Linkage(CachedLinkage);
869 bool NamedDecl::hasExternalLinkageUncached() const {
870 return getLVForDecl(this, LVForExplicitValue).getLinkage() == ExternalLinkage;
873 Linkage NamedDecl::getLinkage() const {
874 if (HasCachedLinkage)
875 return Linkage(CachedLinkage);
877 // We don't care about visibility here, so ask for the cheapest
878 // possible visibility analysis.
879 CachedLinkage = getLVForDecl(this, LVForExplicitValue).getLinkage();
880 HasCachedLinkage = 1;
886 return Linkage(CachedLinkage);
889 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
890 LVComputationKind computation =
891 (usesTypeVisibility(this) ? LVForType : LVForValue);
892 LinkageInfo LI = getLVForDecl(this, computation);
893 if (HasCachedLinkage) {
894 assert(Linkage(CachedLinkage) == LI.getLinkage());
897 HasCachedLinkage = 1;
898 CachedLinkage = LI.getLinkage();
907 void NamedDecl::verifyLinkage() const {
908 // In C (because of gnu inline) and in c++ with microsoft extensions an
909 // static can follow an extern, so we can have two decls with different
911 const LangOptions &Opts = getASTContext().getLangOpts();
912 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
915 // We have just computed the linkage for this decl. By induction we know
916 // that all other computed linkages match, check that the one we just computed
919 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
920 NamedDecl *T = cast<NamedDecl>(*I);
923 if (T->HasCachedLinkage != 0) {
928 assert(!D || D->CachedLinkage == CachedLinkage);
932 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
933 // Check the declaration itself first.
934 if (Optional<Visibility> V = getVisibilityOf(this, kind))
937 // If this is a member class of a specialization of a class template
938 // and the corresponding decl has explicit visibility, use that.
939 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(this)) {
940 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
941 if (InstantiatedFrom)
942 return getVisibilityOf(InstantiatedFrom, kind);
945 // If there wasn't explicit visibility there, and this is a
946 // specialization of a class template, check for visibility
948 if (const ClassTemplateSpecializationDecl *spec
949 = dyn_cast<ClassTemplateSpecializationDecl>(this))
950 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
953 // Use the most recent declaration.
954 const NamedDecl *MostRecent = cast<NamedDecl>(this->getMostRecentDecl());
955 if (MostRecent != this)
956 return MostRecent->getExplicitVisibility(kind);
958 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
959 if (Var->isStaticDataMember()) {
960 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
961 if (InstantiatedFrom)
962 return getVisibilityOf(InstantiatedFrom, kind);
967 // Also handle function template specializations.
968 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
969 // If the function is a specialization of a template with an
970 // explicit visibility attribute, use that.
971 if (FunctionTemplateSpecializationInfo *templateInfo
972 = fn->getTemplateSpecializationInfo())
973 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
976 // If the function is a member of a specialization of a class template
977 // and the corresponding decl has explicit visibility, use that.
978 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
979 if (InstantiatedFrom)
980 return getVisibilityOf(InstantiatedFrom, kind);
985 // The visibility of a template is stored in the templated decl.
986 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(this))
987 return getVisibilityOf(TD->getTemplatedDecl(), kind);
992 static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
993 LVComputationKind computation) {
994 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
995 if (Function->isInAnonymousNamespace() &&
996 !Function->getDeclContext()->isExternCContext())
997 return LinkageInfo::uniqueExternal();
999 // This is a "void f();" which got merged with a file static.
1000 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1001 return LinkageInfo::internal();
1004 if (!hasExplicitVisibilityAlready(computation)) {
1005 if (Optional<Visibility> Vis =
1006 getExplicitVisibility(Function, computation))
1007 LV.mergeVisibility(*Vis, true);
1010 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1011 // merging storage classes and visibility attributes, so we don't have to
1012 // look at previous decls in here.
1017 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1018 if (Var->hasExternalStorage()) {
1019 if (Var->isInAnonymousNamespace() &&
1020 !Var->getDeclContext()->isExternCContext())
1021 return LinkageInfo::uniqueExternal();
1024 if (Var->getStorageClass() == SC_PrivateExtern)
1025 LV.mergeVisibility(HiddenVisibility, true);
1026 else if (!hasExplicitVisibilityAlready(computation)) {
1027 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
1028 LV.mergeVisibility(*Vis, true);
1031 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1032 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1033 if (PrevLV.getLinkage())
1034 LV.setLinkage(PrevLV.getLinkage());
1035 LV.mergeVisibility(PrevLV);
1042 return LinkageInfo::none();
1045 static LinkageInfo getLVForDecl(const NamedDecl *D,
1046 LVComputationKind computation) {
1047 // Objective-C: treat all Objective-C declarations as having external
1049 switch (D->getKind()) {
1053 return LinkageInfo::none();
1054 case Decl::TemplateTemplateParm: // count these as external
1055 case Decl::NonTypeTemplateParm:
1056 case Decl::ObjCAtDefsField:
1057 case Decl::ObjCCategory:
1058 case Decl::ObjCCategoryImpl:
1059 case Decl::ObjCCompatibleAlias:
1060 case Decl::ObjCImplementation:
1061 case Decl::ObjCMethod:
1062 case Decl::ObjCProperty:
1063 case Decl::ObjCPropertyImpl:
1064 case Decl::ObjCProtocol:
1065 return LinkageInfo::external();
1067 case Decl::CXXRecord: {
1068 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1069 if (Record->isLambda()) {
1070 if (!Record->getLambdaManglingNumber()) {
1071 // This lambda has no mangling number, so it's internal.
1072 return LinkageInfo::internal();
1075 // This lambda has its linkage/visibility determined by its owner.
1076 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
1077 if (Decl *ContextDecl = Record->getLambdaContextDecl()) {
1078 if (isa<ParmVarDecl>(ContextDecl))
1079 DC = ContextDecl->getDeclContext()->getRedeclContext();
1081 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1084 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
1085 return getLVForDecl(ND, computation);
1087 return LinkageInfo::external();
1094 // Handle linkage for namespace-scope names.
1095 if (D->getDeclContext()->getRedeclContext()->isFileContext())
1096 return getLVForNamespaceScopeDecl(D, computation);
1098 // C++ [basic.link]p5:
1099 // In addition, a member function, static data member, a named
1100 // class or enumeration of class scope, or an unnamed class or
1101 // enumeration defined in a class-scope typedef declaration such
1102 // that the class or enumeration has the typedef name for linkage
1103 // purposes (7.1.3), has external linkage if the name of the class
1104 // has external linkage.
1105 if (D->getDeclContext()->isRecord())
1106 return getLVForClassMember(D, computation);
1108 // C++ [basic.link]p6:
1109 // The name of a function declared in block scope and the name of
1110 // an object declared by a block scope extern declaration have
1111 // linkage. If there is a visible declaration of an entity with
1112 // linkage having the same name and type, ignoring entities
1113 // declared outside the innermost enclosing namespace scope, the
1114 // block scope declaration declares that same entity and receives
1115 // the linkage of the previous declaration. If there is more than
1116 // one such matching entity, the program is ill-formed. Otherwise,
1117 // if no matching entity is found, the block scope entity receives
1118 // external linkage.
1119 if (D->getDeclContext()->isFunctionOrMethod())
1120 return getLVForLocalDecl(D, computation);
1122 // C++ [basic.link]p6:
1123 // Names not covered by these rules have no linkage.
1124 return LinkageInfo::none();
1127 std::string NamedDecl::getQualifiedNameAsString() const {
1128 return getQualifiedNameAsString(getASTContext().getPrintingPolicy());
1131 std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
1132 std::string QualName;
1133 llvm::raw_string_ostream OS(QualName);
1134 printQualifiedName(OS, P);
1138 void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1139 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1142 void NamedDecl::printQualifiedName(raw_ostream &OS,
1143 const PrintingPolicy &P) const {
1144 const DeclContext *Ctx = getDeclContext();
1146 if (Ctx->isFunctionOrMethod()) {
1151 typedef SmallVector<const DeclContext *, 8> ContextsTy;
1152 ContextsTy Contexts;
1154 // Collect contexts.
1155 while (Ctx && isa<NamedDecl>(Ctx)) {
1156 Contexts.push_back(Ctx);
1157 Ctx = Ctx->getParent();
1160 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1162 if (const ClassTemplateSpecializationDecl *Spec
1163 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
1164 OS << Spec->getName();
1165 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1166 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1167 TemplateArgs.data(),
1168 TemplateArgs.size(),
1170 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
1171 if (ND->isAnonymousNamespace())
1172 OS << "<anonymous namespace>";
1175 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1176 if (!RD->getIdentifier())
1177 OS << "<anonymous " << RD->getKindName() << '>';
1180 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1181 const FunctionProtoType *FT = 0;
1182 if (FD->hasWrittenPrototype())
1183 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1187 unsigned NumParams = FD->getNumParams();
1188 for (unsigned i = 0; i < NumParams; ++i) {
1191 OS << FD->getParamDecl(i)->getType().stream(P);
1194 if (FT->isVariadic()) {
1202 OS << *cast<NamedDecl>(*I);
1210 OS << "<anonymous>";
1213 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1214 const PrintingPolicy &Policy,
1215 bool Qualified) const {
1217 printQualifiedName(OS, Policy);
1222 bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
1223 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1225 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1226 // We want to keep it, unless it nominates same namespace.
1227 if (getKind() == Decl::UsingDirective) {
1228 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1229 ->getOriginalNamespace() ==
1230 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1231 ->getOriginalNamespace();
1234 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1235 // For function declarations, we keep track of redeclarations.
1236 return FD->getPreviousDecl() == OldD;
1238 // For function templates, the underlying function declarations are linked.
1239 if (const FunctionTemplateDecl *FunctionTemplate
1240 = dyn_cast<FunctionTemplateDecl>(this))
1241 if (const FunctionTemplateDecl *OldFunctionTemplate
1242 = dyn_cast<FunctionTemplateDecl>(OldD))
1243 return FunctionTemplate->getTemplatedDecl()
1244 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
1246 // For method declarations, we keep track of redeclarations.
1247 if (isa<ObjCMethodDecl>(this))
1250 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1253 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1254 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1255 cast<UsingShadowDecl>(OldD)->getTargetDecl();
1257 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1258 ASTContext &Context = getASTContext();
1259 return Context.getCanonicalNestedNameSpecifier(
1260 cast<UsingDecl>(this)->getQualifier()) ==
1261 Context.getCanonicalNestedNameSpecifier(
1262 cast<UsingDecl>(OldD)->getQualifier());
1265 // A typedef of an Objective-C class type can replace an Objective-C class
1266 // declaration or definition, and vice versa.
1267 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1268 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1271 // For non-function declarations, if the declarations are of the
1272 // same kind then this must be a redeclaration, or semantic analysis
1273 // would not have given us the new declaration.
1274 return this->getKind() == OldD->getKind();
1277 bool NamedDecl::hasLinkage() const {
1278 return getLinkage() != NoLinkage;
1281 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1282 NamedDecl *ND = this;
1283 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1284 ND = UD->getTargetDecl();
1286 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1287 return AD->getClassInterface();
1292 bool NamedDecl::isCXXInstanceMember() const {
1293 if (!isCXXClassMember())
1296 const NamedDecl *D = this;
1297 if (isa<UsingShadowDecl>(D))
1298 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1300 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
1302 if (isa<CXXMethodDecl>(D))
1303 return cast<CXXMethodDecl>(D)->isInstance();
1304 if (isa<FunctionTemplateDecl>(D))
1305 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
1306 ->getTemplatedDecl())->isInstance();
1310 //===----------------------------------------------------------------------===//
1311 // DeclaratorDecl Implementation
1312 //===----------------------------------------------------------------------===//
1314 template <typename DeclT>
1315 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1316 if (decl->getNumTemplateParameterLists() > 0)
1317 return decl->getTemplateParameterList(0)->getTemplateLoc();
1319 return decl->getInnerLocStart();
1322 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1323 TypeSourceInfo *TSI = getTypeSourceInfo();
1324 if (TSI) return TSI->getTypeLoc().getBeginLoc();
1325 return SourceLocation();
1328 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1330 // Make sure the extended decl info is allocated.
1331 if (!hasExtInfo()) {
1332 // Save (non-extended) type source info pointer.
1333 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1334 // Allocate external info struct.
1335 DeclInfo = new (getASTContext()) ExtInfo;
1336 // Restore savedTInfo into (extended) decl info.
1337 getExtInfo()->TInfo = savedTInfo;
1339 // Set qualifier info.
1340 getExtInfo()->QualifierLoc = QualifierLoc;
1342 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1344 if (getExtInfo()->NumTemplParamLists == 0) {
1345 // Save type source info pointer.
1346 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1347 // Deallocate the extended decl info.
1348 getASTContext().Deallocate(getExtInfo());
1349 // Restore savedTInfo into (non-extended) decl info.
1350 DeclInfo = savedTInfo;
1353 getExtInfo()->QualifierLoc = QualifierLoc;
1359 DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1360 unsigned NumTPLists,
1361 TemplateParameterList **TPLists) {
1362 assert(NumTPLists > 0);
1363 // Make sure the extended decl info is allocated.
1364 if (!hasExtInfo()) {
1365 // Save (non-extended) type source info pointer.
1366 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1367 // Allocate external info struct.
1368 DeclInfo = new (getASTContext()) ExtInfo;
1369 // Restore savedTInfo into (extended) decl info.
1370 getExtInfo()->TInfo = savedTInfo;
1372 // Set the template parameter lists info.
1373 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1376 SourceLocation DeclaratorDecl::getOuterLocStart() const {
1377 return getTemplateOrInnerLocStart(this);
1382 // Helper function: returns true if QT is or contains a type
1383 // having a postfix component.
1384 bool typeIsPostfix(clang::QualType QT) {
1386 const Type* T = QT.getTypePtr();
1387 switch (T->getTypeClass()) {
1391 QT = cast<PointerType>(T)->getPointeeType();
1393 case Type::BlockPointer:
1394 QT = cast<BlockPointerType>(T)->getPointeeType();
1396 case Type::MemberPointer:
1397 QT = cast<MemberPointerType>(T)->getPointeeType();
1399 case Type::LValueReference:
1400 case Type::RValueReference:
1401 QT = cast<ReferenceType>(T)->getPointeeType();
1403 case Type::PackExpansion:
1404 QT = cast<PackExpansionType>(T)->getPattern();
1407 case Type::ConstantArray:
1408 case Type::DependentSizedArray:
1409 case Type::IncompleteArray:
1410 case Type::VariableArray:
1411 case Type::FunctionProto:
1412 case Type::FunctionNoProto:
1420 SourceRange DeclaratorDecl::getSourceRange() const {
1421 SourceLocation RangeEnd = getLocation();
1422 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1423 if (typeIsPostfix(TInfo->getType()))
1424 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1426 return SourceRange(getOuterLocStart(), RangeEnd);
1430 QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1431 unsigned NumTPLists,
1432 TemplateParameterList **TPLists) {
1433 assert((NumTPLists == 0 || TPLists != 0) &&
1434 "Empty array of template parameters with positive size!");
1436 // Free previous template parameters (if any).
1437 if (NumTemplParamLists > 0) {
1438 Context.Deallocate(TemplParamLists);
1439 TemplParamLists = 0;
1440 NumTemplParamLists = 0;
1442 // Set info on matched template parameter lists (if any).
1443 if (NumTPLists > 0) {
1444 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
1445 NumTemplParamLists = NumTPLists;
1446 for (unsigned i = NumTPLists; i-- > 0; )
1447 TemplParamLists[i] = TPLists[i];
1451 //===----------------------------------------------------------------------===//
1452 // VarDecl Implementation
1453 //===----------------------------------------------------------------------===//
1455 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1457 case SC_None: break;
1458 case SC_Auto: return "auto";
1459 case SC_Extern: return "extern";
1460 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1461 case SC_PrivateExtern: return "__private_extern__";
1462 case SC_Register: return "register";
1463 case SC_Static: return "static";
1466 llvm_unreachable("Invalid storage class");
1469 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1470 SourceLocation StartL, SourceLocation IdL,
1471 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1473 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S);
1476 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1477 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
1478 return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1479 QualType(), 0, SC_None);
1482 void VarDecl::setStorageClass(StorageClass SC) {
1483 assert(isLegalForVariable(SC));
1484 VarDeclBits.SClass = SC;
1487 SourceRange VarDecl::getSourceRange() const {
1488 if (const Expr *Init = getInit()) {
1489 SourceLocation InitEnd = Init->getLocEnd();
1490 // If Init is implicit, ignore its source range and fallback on
1491 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1492 if (InitEnd.isValid() && InitEnd != getLocation())
1493 return SourceRange(getOuterLocStart(), InitEnd);
1495 return DeclaratorDecl::getSourceRange();
1498 template<typename T>
1499 static LanguageLinkage getLanguageLinkageTemplate(const T &D) {
1500 // C++ [dcl.link]p1: All function types, function names with external linkage,
1501 // and variable names with external linkage have a language linkage.
1502 if (!isExternalLinkage(D.getLinkage()))
1503 return NoLanguageLinkage;
1505 // Language linkage is a C++ concept, but saying that everything else in C has
1506 // C language linkage fits the implementation nicely.
1507 ASTContext &Context = D.getASTContext();
1508 if (!Context.getLangOpts().CPlusPlus)
1509 return CLanguageLinkage;
1511 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1512 // language linkage of the names of class members and the function type of
1513 // class member functions.
1514 const DeclContext *DC = D.getDeclContext();
1516 return CXXLanguageLinkage;
1518 // If the first decl is in an extern "C" context, any other redeclaration
1519 // will have C language linkage. If the first one is not in an extern "C"
1520 // context, we would have reported an error for any other decl being in one.
1521 const T *First = D.getFirstDeclaration();
1522 if (First->getDeclContext()->isExternCContext())
1523 return CLanguageLinkage;
1524 return CXXLanguageLinkage;
1527 template<typename T>
1528 static bool isExternCTemplate(const T &D) {
1529 // Since the context is ignored for class members, they can only have C++
1530 // language linkage or no language linkage.
1531 const DeclContext *DC = D.getDeclContext();
1532 if (DC->isRecord()) {
1533 assert(D.getASTContext().getLangOpts().CPlusPlus);
1537 return D.getLanguageLinkage() == CLanguageLinkage;
1540 LanguageLinkage VarDecl::getLanguageLinkage() const {
1541 return getLanguageLinkageTemplate(*this);
1544 bool VarDecl::isExternC() const {
1545 return isExternCTemplate(*this);
1548 VarDecl *VarDecl::getCanonicalDecl() {
1549 return getFirstDeclaration();
1552 VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1553 ASTContext &C) const
1555 // C++ [basic.def]p2:
1556 // A declaration is a definition unless [...] it contains the 'extern'
1557 // specifier or a linkage-specification and neither an initializer [...],
1558 // it declares a static data member in a class declaration [...].
1559 // C++ [temp.expl.spec]p15:
1560 // An explicit specialization of a static data member of a template is a
1561 // definition if the declaration includes an initializer; otherwise, it is
1563 if (isStaticDataMember()) {
1564 if (isOutOfLine() && (hasInit() ||
1565 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1568 return DeclarationOnly;
1571 // A definition of an identifier is a declaration for that identifier that
1572 // [...] causes storage to be reserved for that object.
1573 // Note: that applies for all non-file-scope objects.
1575 // If the declaration of an identifier for an object has file scope and an
1576 // initializer, the declaration is an external definition for the identifier
1579 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1580 if (hasExternalStorage())
1581 return DeclarationOnly;
1583 if (hasExternalStorage()) {
1584 for (const VarDecl *PrevVar = getPreviousDecl();
1585 PrevVar; PrevVar = PrevVar->getPreviousDecl()) {
1586 if (PrevVar->getLinkage() == InternalLinkage)
1587 return DeclarationOnly;
1591 // A declaration of an object that has file scope without an initializer,
1592 // and without a storage class specifier or the scs 'static', constitutes
1593 // a tentative definition.
1594 // No such thing in C++.
1595 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
1596 return TentativeDefinition;
1598 // What's left is (in C, block-scope) declarations without initializers or
1599 // external storage. These are definitions.
1603 VarDecl *VarDecl::getActingDefinition() {
1604 DefinitionKind Kind = isThisDeclarationADefinition();
1605 if (Kind != TentativeDefinition)
1608 VarDecl *LastTentative = 0;
1609 VarDecl *First = getFirstDeclaration();
1610 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1612 Kind = (*I)->isThisDeclarationADefinition();
1613 if (Kind == Definition)
1615 else if (Kind == TentativeDefinition)
1618 return LastTentative;
1621 bool VarDecl::isTentativeDefinitionNow() const {
1622 DefinitionKind Kind = isThisDeclarationADefinition();
1623 if (Kind != TentativeDefinition)
1626 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1627 if ((*I)->isThisDeclarationADefinition() == Definition)
1633 VarDecl *VarDecl::getDefinition(ASTContext &C) {
1634 VarDecl *First = getFirstDeclaration();
1635 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1637 if ((*I)->isThisDeclarationADefinition(C) == Definition)
1643 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
1644 DefinitionKind Kind = DeclarationOnly;
1646 const VarDecl *First = getFirstDeclaration();
1647 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1649 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition(C));
1650 if (Kind == Definition)
1657 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
1658 redecl_iterator I = redecls_begin(), E = redecls_end();
1659 while (I != E && !I->getInit())
1664 return I->getInit();
1669 bool VarDecl::isOutOfLine() const {
1670 if (Decl::isOutOfLine())
1673 if (!isStaticDataMember())
1676 // If this static data member was instantiated from a static data member of
1677 // a class template, check whether that static data member was defined
1679 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1680 return VD->isOutOfLine();
1685 VarDecl *VarDecl::getOutOfLineDefinition() {
1686 if (!isStaticDataMember())
1689 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1690 RD != RDEnd; ++RD) {
1691 if (RD->getLexicalDeclContext()->isFileContext())
1698 void VarDecl::setInit(Expr *I) {
1699 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1700 Eval->~EvaluatedStmt();
1701 getASTContext().Deallocate(Eval);
1707 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
1708 const LangOptions &Lang = C.getLangOpts();
1710 if (!Lang.CPlusPlus)
1713 // In C++11, any variable of reference type can be used in a constant
1714 // expression if it is initialized by a constant expression.
1715 if (Lang.CPlusPlus11 && getType()->isReferenceType())
1718 // Only const objects can be used in constant expressions in C++. C++98 does
1719 // not require the variable to be non-volatile, but we consider this to be a
1721 if (!getType().isConstQualified() || getType().isVolatileQualified())
1724 // In C++, const, non-volatile variables of integral or enumeration types
1725 // can be used in constant expressions.
1726 if (getType()->isIntegralOrEnumerationType())
1729 // Additionally, in C++11, non-volatile constexpr variables can be used in
1730 // constant expressions.
1731 return Lang.CPlusPlus11 && isConstexpr();
1734 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1735 /// form, which contains extra information on the evaluated value of the
1737 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1738 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1740 Stmt *S = Init.get<Stmt *>();
1741 Eval = new (getASTContext()) EvaluatedStmt;
1748 APValue *VarDecl::evaluateValue() const {
1749 SmallVector<PartialDiagnosticAt, 8> Notes;
1750 return evaluateValue(Notes);
1753 APValue *VarDecl::evaluateValue(
1754 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
1755 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1757 // We only produce notes indicating why an initializer is non-constant the
1758 // first time it is evaluated. FIXME: The notes won't always be emitted the
1759 // first time we try evaluation, so might not be produced at all.
1760 if (Eval->WasEvaluated)
1761 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
1763 const Expr *Init = cast<Expr>(Eval->Value);
1764 assert(!Init->isValueDependent());
1766 if (Eval->IsEvaluating) {
1767 // FIXME: Produce a diagnostic for self-initialization.
1768 Eval->CheckedICE = true;
1769 Eval->IsICE = false;
1773 Eval->IsEvaluating = true;
1775 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1778 // Ensure the result is an uninitialized APValue if evaluation fails.
1780 Eval->Evaluated = APValue();
1782 Eval->IsEvaluating = false;
1783 Eval->WasEvaluated = true;
1785 // In C++11, we have determined whether the initializer was a constant
1786 // expression as a side-effect.
1787 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
1788 Eval->CheckedICE = true;
1789 Eval->IsICE = Result && Notes.empty();
1792 return Result ? &Eval->Evaluated : 0;
1795 bool VarDecl::checkInitIsICE() const {
1796 // Initializers of weak variables are never ICEs.
1800 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1801 if (Eval->CheckedICE)
1802 // We have already checked whether this subexpression is an
1803 // integral constant expression.
1806 const Expr *Init = cast<Expr>(Eval->Value);
1807 assert(!Init->isValueDependent());
1809 // In C++11, evaluate the initializer to check whether it's a constant
1811 if (getASTContext().getLangOpts().CPlusPlus11) {
1812 SmallVector<PartialDiagnosticAt, 8> Notes;
1813 evaluateValue(Notes);
1817 // It's an ICE whether or not the definition we found is
1818 // out-of-line. See DR 721 and the discussion in Clang PR
1819 // 6206 for details.
1821 if (Eval->CheckingICE)
1823 Eval->CheckingICE = true;
1825 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1826 Eval->CheckingICE = false;
1827 Eval->CheckedICE = true;
1831 bool VarDecl::extendsLifetimeOfTemporary() const {
1832 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
1834 const Expr *E = getInit();
1838 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1839 E = Cleanups->getSubExpr();
1841 return isa<MaterializeTemporaryExpr>(E);
1844 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
1845 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
1846 return cast<VarDecl>(MSI->getInstantiatedFrom());
1851 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
1852 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
1853 return MSI->getTemplateSpecializationKind();
1855 return TSK_Undeclared;
1858 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
1859 return getASTContext().getInstantiatedFromStaticDataMember(this);
1862 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1863 SourceLocation PointOfInstantiation) {
1864 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
1865 assert(MSI && "Not an instantiated static data member?");
1866 MSI->setTemplateSpecializationKind(TSK);
1867 if (TSK != TSK_ExplicitSpecialization &&
1868 PointOfInstantiation.isValid() &&
1869 MSI->getPointOfInstantiation().isInvalid())
1870 MSI->setPointOfInstantiation(PointOfInstantiation);
1873 //===----------------------------------------------------------------------===//
1874 // ParmVarDecl Implementation
1875 //===----------------------------------------------------------------------===//
1877 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
1878 SourceLocation StartLoc,
1879 SourceLocation IdLoc, IdentifierInfo *Id,
1880 QualType T, TypeSourceInfo *TInfo,
1881 StorageClass S, Expr *DefArg) {
1882 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
1886 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1887 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
1888 return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
1889 0, QualType(), 0, SC_None, 0);
1892 SourceRange ParmVarDecl::getSourceRange() const {
1893 if (!hasInheritedDefaultArg()) {
1894 SourceRange ArgRange = getDefaultArgRange();
1895 if (ArgRange.isValid())
1896 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1899 return DeclaratorDecl::getSourceRange();
1902 Expr *ParmVarDecl::getDefaultArg() {
1903 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1904 assert(!hasUninstantiatedDefaultArg() &&
1905 "Default argument is not yet instantiated!");
1907 Expr *Arg = getInit();
1908 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
1909 return E->getSubExpr();
1914 SourceRange ParmVarDecl::getDefaultArgRange() const {
1915 if (const Expr *E = getInit())
1916 return E->getSourceRange();
1918 if (hasUninstantiatedDefaultArg())
1919 return getUninstantiatedDefaultArg()->getSourceRange();
1921 return SourceRange();
1924 bool ParmVarDecl::isParameterPack() const {
1925 return isa<PackExpansionType>(getType());
1928 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1929 getASTContext().setParameterIndex(this, parameterIndex);
1930 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1933 unsigned ParmVarDecl::getParameterIndexLarge() const {
1934 return getASTContext().getParameterIndex(this);
1937 //===----------------------------------------------------------------------===//
1938 // FunctionDecl Implementation
1939 //===----------------------------------------------------------------------===//
1941 void FunctionDecl::getNameForDiagnostic(
1942 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
1943 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
1944 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1946 TemplateSpecializationType::PrintTemplateArgumentList(
1947 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
1950 bool FunctionDecl::isVariadic() const {
1951 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1952 return FT->isVariadic();
1956 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1957 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1958 if (I->Body || I->IsLateTemplateParsed) {
1967 bool FunctionDecl::hasTrivialBody() const
1969 Stmt *S = getBody();
1971 // Since we don't have a body for this function, we don't know if it's
1976 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
1981 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
1982 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1983 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
1984 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
1992 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
1993 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1996 return I->Body.get(getASTContext().getExternalSource());
1997 } else if (I->IsLateTemplateParsed) {
2006 void FunctionDecl::setBody(Stmt *B) {
2009 EndRangeLoc = B->getLocEnd();
2012 void FunctionDecl::setPure(bool P) {
2015 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2016 Parent->markedVirtualFunctionPure();
2019 bool FunctionDecl::isMain() const {
2020 const TranslationUnitDecl *tunit =
2021 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2023 !tunit->getASTContext().getLangOpts().Freestanding &&
2025 getIdentifier()->isStr("main");
2028 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2029 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2030 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2031 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2032 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2033 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2035 if (isa<CXXRecordDecl>(getDeclContext())) return false;
2036 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
2038 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
2039 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
2041 ASTContext &Context =
2042 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2045 // The result type and first argument type are constant across all
2046 // these operators. The second argument must be exactly void*.
2047 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
2050 LanguageLinkage FunctionDecl::getLanguageLinkage() const {
2051 // Users expect to be able to write
2052 // extern "C" void *__builtin_alloca (size_t);
2053 // so consider builtins as having C language linkage.
2055 return CLanguageLinkage;
2057 return getLanguageLinkageTemplate(*this);
2060 bool FunctionDecl::isExternC() const {
2061 return isExternCTemplate(*this);
2064 bool FunctionDecl::isGlobal() const {
2065 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2066 return Method->isStatic();
2068 if (getCanonicalDecl()->getStorageClass() == SC_Static)
2071 for (const DeclContext *DC = getDeclContext();
2073 DC = DC->getParent()) {
2074 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2075 if (!Namespace->getDeclName())
2084 bool FunctionDecl::isNoReturn() const {
2085 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2086 hasAttr<C11NoReturnAttr>() ||
2087 getType()->getAs<FunctionType>()->getNoReturnAttr();
2091 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2092 redeclarable_base::setPreviousDeclaration(PrevDecl);
2094 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2095 FunctionTemplateDecl *PrevFunTmpl
2096 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
2097 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2098 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
2101 if (PrevDecl && PrevDecl->IsInline)
2105 const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
2106 return getFirstDeclaration();
2109 FunctionDecl *FunctionDecl::getCanonicalDecl() {
2110 return getFirstDeclaration();
2113 /// \brief Returns a value indicating whether this function
2114 /// corresponds to a builtin function.
2116 /// The function corresponds to a built-in function if it is
2117 /// declared at translation scope or within an extern "C" block and
2118 /// its name matches with the name of a builtin. The returned value
2119 /// will be 0 for functions that do not correspond to a builtin, a
2120 /// value of type \c Builtin::ID if in the target-independent range
2121 /// \c [1,Builtin::First), or a target-specific builtin value.
2122 unsigned FunctionDecl::getBuiltinID() const {
2123 if (!getIdentifier())
2126 unsigned BuiltinID = getIdentifier()->getBuiltinID();
2130 ASTContext &Context = getASTContext();
2131 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2134 // This function has the name of a known C library
2135 // function. Determine whether it actually refers to the C library
2136 // function or whether it just has the same name.
2138 // If this is a static function, it's not a builtin.
2139 if (getStorageClass() == SC_Static)
2142 // If this function is at translation-unit scope and we're not in
2143 // C++, it refers to the C library function.
2144 if (!Context.getLangOpts().CPlusPlus &&
2145 getDeclContext()->isTranslationUnit())
2148 // If the function is in an extern "C" linkage specification and is
2149 // not marked "overloadable", it's the real function.
2150 if (isa<LinkageSpecDecl>(getDeclContext()) &&
2151 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
2152 == LinkageSpecDecl::lang_c &&
2153 !getAttr<OverloadableAttr>())
2161 /// getNumParams - Return the number of parameters this function must have
2162 /// based on its FunctionType. This is the length of the ParamInfo array
2163 /// after it has been created.
2164 unsigned FunctionDecl::getNumParams() const {
2165 const FunctionType *FT = getType()->castAs<FunctionType>();
2166 if (isa<FunctionNoProtoType>(FT))
2168 return cast<FunctionProtoType>(FT)->getNumArgs();
2172 void FunctionDecl::setParams(ASTContext &C,
2173 ArrayRef<ParmVarDecl *> NewParamInfo) {
2174 assert(ParamInfo == 0 && "Already has param info!");
2175 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
2177 // Zero params -> null pointer.
2178 if (!NewParamInfo.empty()) {
2179 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2180 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
2184 void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
2185 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2187 if (!NewDecls.empty()) {
2188 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2189 std::copy(NewDecls.begin(), NewDecls.end(), A);
2190 DeclsInPrototypeScope = ArrayRef<NamedDecl *>(A, NewDecls.size());
2194 /// getMinRequiredArguments - Returns the minimum number of arguments
2195 /// needed to call this function. This may be fewer than the number of
2196 /// function parameters, if some of the parameters have default
2197 /// arguments (in C++) or the last parameter is a parameter pack.
2198 unsigned FunctionDecl::getMinRequiredArguments() const {
2199 if (!getASTContext().getLangOpts().CPlusPlus)
2200 return getNumParams();
2202 unsigned NumRequiredArgs = getNumParams();
2204 // If the last parameter is a parameter pack, we don't need an argument for
2206 if (NumRequiredArgs > 0 &&
2207 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
2210 // If this parameter has a default argument, we don't need an argument for
2212 while (NumRequiredArgs > 0 &&
2213 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
2216 // We might have parameter packs before the end. These can't be deduced,
2217 // but they can still handle multiple arguments.
2218 unsigned ArgIdx = NumRequiredArgs;
2219 while (ArgIdx > 0) {
2220 if (getParamDecl(ArgIdx - 1)->isParameterPack())
2221 NumRequiredArgs = ArgIdx;
2226 return NumRequiredArgs;
2229 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2230 // Only consider file-scope declarations in this test.
2231 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2234 // Only consider explicit declarations; the presence of a builtin for a
2235 // libcall shouldn't affect whether a definition is externally visible.
2236 if (Redecl->isImplicit())
2239 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2240 return true; // Not an inline definition
2245 /// \brief For a function declaration in C or C++, determine whether this
2246 /// declaration causes the definition to be externally visible.
2248 /// Specifically, this determines if adding the current declaration to the set
2249 /// of redeclarations of the given functions causes
2250 /// isInlineDefinitionExternallyVisible to change from false to true.
2251 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2252 assert(!doesThisDeclarationHaveABody() &&
2253 "Must have a declaration without a body.");
2255 ASTContext &Context = getASTContext();
2257 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2258 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2259 // an externally visible definition.
2261 // FIXME: What happens if gnu_inline gets added on after the first
2263 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
2266 const FunctionDecl *Prev = this;
2267 bool FoundBody = false;
2268 while ((Prev = Prev->getPreviousDecl())) {
2269 FoundBody |= Prev->Body;
2272 // If it's not the case that both 'inline' and 'extern' are
2273 // specified on the definition, then it is always externally visible.
2274 if (!Prev->isInlineSpecified() ||
2275 Prev->getStorageClass() != SC_Extern)
2277 } else if (Prev->isInlineSpecified() &&
2278 Prev->getStorageClass() != SC_Extern) {
2285 if (Context.getLangOpts().CPlusPlus)
2289 // [...] If all of the file scope declarations for a function in a
2290 // translation unit include the inline function specifier without extern,
2291 // then the definition in that translation unit is an inline definition.
2292 if (isInlineSpecified() && getStorageClass() != SC_Extern)
2294 const FunctionDecl *Prev = this;
2295 bool FoundBody = false;
2296 while ((Prev = Prev->getPreviousDecl())) {
2297 FoundBody |= Prev->Body;
2298 if (RedeclForcesDefC99(Prev))
2304 /// \brief For an inline function definition in C, or for a gnu_inline function
2305 /// in C++, determine whether the definition will be externally visible.
2307 /// Inline function definitions are always available for inlining optimizations.
2308 /// However, depending on the language dialect, declaration specifiers, and
2309 /// attributes, the definition of an inline function may or may not be
2310 /// "externally" visible to other translation units in the program.
2312 /// In C99, inline definitions are not externally visible by default. However,
2313 /// if even one of the global-scope declarations is marked "extern inline", the
2314 /// inline definition becomes externally visible (C99 6.7.4p6).
2316 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2317 /// definition, we use the GNU semantics for inline, which are nearly the
2318 /// opposite of C99 semantics. In particular, "inline" by itself will create
2319 /// an externally visible symbol, but "extern inline" will not create an
2320 /// externally visible symbol.
2321 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
2322 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
2323 assert(isInlined() && "Function must be inline");
2324 ASTContext &Context = getASTContext();
2326 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2327 // Note: If you change the logic here, please change
2328 // doesDeclarationForceExternallyVisibleDefinition as well.
2330 // If it's not the case that both 'inline' and 'extern' are
2331 // specified on the definition, then this inline definition is
2332 // externally visible.
2333 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
2336 // If any declaration is 'inline' but not 'extern', then this definition
2337 // is externally visible.
2338 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2339 Redecl != RedeclEnd;
2341 if (Redecl->isInlineSpecified() &&
2342 Redecl->getStorageClass() != SC_Extern)
2349 // The rest of this function is C-only.
2350 assert(!Context.getLangOpts().CPlusPlus &&
2351 "should not use C inline rules in C++");
2354 // [...] If all of the file scope declarations for a function in a
2355 // translation unit include the inline function specifier without extern,
2356 // then the definition in that translation unit is an inline definition.
2357 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2358 Redecl != RedeclEnd;
2360 if (RedeclForcesDefC99(*Redecl))
2365 // An inline definition does not provide an external definition for the
2366 // function, and does not forbid an external definition in another
2367 // translation unit.
2371 /// getOverloadedOperator - Which C++ overloaded operator this
2372 /// function represents, if any.
2373 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
2374 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2375 return getDeclName().getCXXOverloadedOperator();
2380 /// getLiteralIdentifier - The literal suffix identifier this function
2381 /// represents, if any.
2382 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2383 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2384 return getDeclName().getCXXLiteralIdentifier();
2389 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2390 if (TemplateOrSpecialization.isNull())
2391 return TK_NonTemplate;
2392 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2393 return TK_FunctionTemplate;
2394 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2395 return TK_MemberSpecialization;
2396 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2397 return TK_FunctionTemplateSpecialization;
2398 if (TemplateOrSpecialization.is
2399 <DependentFunctionTemplateSpecializationInfo*>())
2400 return TK_DependentFunctionTemplateSpecialization;
2402 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
2405 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
2406 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
2407 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2413 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2415 TemplateSpecializationKind TSK) {
2416 assert(TemplateOrSpecialization.isNull() &&
2417 "Member function is already a specialization");
2418 MemberSpecializationInfo *Info
2419 = new (C) MemberSpecializationInfo(FD, TSK);
2420 TemplateOrSpecialization = Info;
2423 bool FunctionDecl::isImplicitlyInstantiable() const {
2424 // If the function is invalid, it can't be implicitly instantiated.
2425 if (isInvalidDecl())
2428 switch (getTemplateSpecializationKind()) {
2429 case TSK_Undeclared:
2430 case TSK_ExplicitInstantiationDefinition:
2433 case TSK_ImplicitInstantiation:
2436 // It is possible to instantiate TSK_ExplicitSpecialization kind
2437 // if the FunctionDecl has a class scope specialization pattern.
2438 case TSK_ExplicitSpecialization:
2439 return getClassScopeSpecializationPattern() != 0;
2441 case TSK_ExplicitInstantiationDeclaration:
2446 // Find the actual template from which we will instantiate.
2447 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
2448 bool HasPattern = false;
2450 HasPattern = PatternDecl->hasBody(PatternDecl);
2452 // C++0x [temp.explicit]p9:
2453 // Except for inline functions, other explicit instantiation declarations
2454 // have the effect of suppressing the implicit instantiation of the entity
2455 // to which they refer.
2456 if (!HasPattern || !PatternDecl)
2459 return PatternDecl->isInlined();
2462 bool FunctionDecl::isTemplateInstantiation() const {
2463 switch (getTemplateSpecializationKind()) {
2464 case TSK_Undeclared:
2465 case TSK_ExplicitSpecialization:
2467 case TSK_ImplicitInstantiation:
2468 case TSK_ExplicitInstantiationDeclaration:
2469 case TSK_ExplicitInstantiationDefinition:
2472 llvm_unreachable("All TSK values handled.");
2475 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
2476 // Handle class scope explicit specialization special case.
2477 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2478 return getClassScopeSpecializationPattern();
2480 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2481 while (Primary->getInstantiatedFromMemberTemplate()) {
2482 // If we have hit a point where the user provided a specialization of
2483 // this template, we're done looking.
2484 if (Primary->isMemberSpecialization())
2487 Primary = Primary->getInstantiatedFromMemberTemplate();
2490 return Primary->getTemplatedDecl();
2493 return getInstantiatedFromMemberFunction();
2496 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
2497 if (FunctionTemplateSpecializationInfo *Info
2498 = TemplateOrSpecialization
2499 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2500 return Info->Template.getPointer();
2505 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2506 return getASTContext().getClassScopeSpecializationPattern(this);
2509 const TemplateArgumentList *
2510 FunctionDecl::getTemplateSpecializationArgs() const {
2511 if (FunctionTemplateSpecializationInfo *Info
2512 = TemplateOrSpecialization
2513 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2514 return Info->TemplateArguments;
2519 const ASTTemplateArgumentListInfo *
2520 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2521 if (FunctionTemplateSpecializationInfo *Info
2522 = TemplateOrSpecialization
2523 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2524 return Info->TemplateArgumentsAsWritten;
2530 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2531 FunctionTemplateDecl *Template,
2532 const TemplateArgumentList *TemplateArgs,
2534 TemplateSpecializationKind TSK,
2535 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2536 SourceLocation PointOfInstantiation) {
2537 assert(TSK != TSK_Undeclared &&
2538 "Must specify the type of function template specialization");
2539 FunctionTemplateSpecializationInfo *Info
2540 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2542 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2544 TemplateArgsAsWritten,
2545 PointOfInstantiation);
2546 TemplateOrSpecialization = Info;
2547 Template->addSpecialization(Info, InsertPos);
2551 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2552 const UnresolvedSetImpl &Templates,
2553 const TemplateArgumentListInfo &TemplateArgs) {
2554 assert(TemplateOrSpecialization.isNull());
2555 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2556 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
2557 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
2558 void *Buffer = Context.Allocate(Size);
2559 DependentFunctionTemplateSpecializationInfo *Info =
2560 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2562 TemplateOrSpecialization = Info;
2565 DependentFunctionTemplateSpecializationInfo::
2566 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2567 const TemplateArgumentListInfo &TArgs)
2568 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2570 d.NumTemplates = Ts.size();
2571 d.NumArgs = TArgs.size();
2573 FunctionTemplateDecl **TsArray =
2574 const_cast<FunctionTemplateDecl**>(getTemplates());
2575 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2576 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2578 TemplateArgumentLoc *ArgsArray =
2579 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2580 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2581 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2584 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
2585 // For a function template specialization, query the specialization
2586 // information object.
2587 FunctionTemplateSpecializationInfo *FTSInfo
2588 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2590 return FTSInfo->getTemplateSpecializationKind();
2592 MemberSpecializationInfo *MSInfo
2593 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2595 return MSInfo->getTemplateSpecializationKind();
2597 return TSK_Undeclared;
2601 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2602 SourceLocation PointOfInstantiation) {
2603 if (FunctionTemplateSpecializationInfo *FTSInfo
2604 = TemplateOrSpecialization.dyn_cast<
2605 FunctionTemplateSpecializationInfo*>()) {
2606 FTSInfo->setTemplateSpecializationKind(TSK);
2607 if (TSK != TSK_ExplicitSpecialization &&
2608 PointOfInstantiation.isValid() &&
2609 FTSInfo->getPointOfInstantiation().isInvalid())
2610 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2611 } else if (MemberSpecializationInfo *MSInfo
2612 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2613 MSInfo->setTemplateSpecializationKind(TSK);
2614 if (TSK != TSK_ExplicitSpecialization &&
2615 PointOfInstantiation.isValid() &&
2616 MSInfo->getPointOfInstantiation().isInvalid())
2617 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2619 llvm_unreachable("Function cannot have a template specialization kind");
2622 SourceLocation FunctionDecl::getPointOfInstantiation() const {
2623 if (FunctionTemplateSpecializationInfo *FTSInfo
2624 = TemplateOrSpecialization.dyn_cast<
2625 FunctionTemplateSpecializationInfo*>())
2626 return FTSInfo->getPointOfInstantiation();
2627 else if (MemberSpecializationInfo *MSInfo
2628 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
2629 return MSInfo->getPointOfInstantiation();
2631 return SourceLocation();
2634 bool FunctionDecl::isOutOfLine() const {
2635 if (Decl::isOutOfLine())
2638 // If this function was instantiated from a member function of a
2639 // class template, check whether that member function was defined out-of-line.
2640 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2641 const FunctionDecl *Definition;
2642 if (FD->hasBody(Definition))
2643 return Definition->isOutOfLine();
2646 // If this function was instantiated from a function template,
2647 // check whether that function template was defined out-of-line.
2648 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2649 const FunctionDecl *Definition;
2650 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
2651 return Definition->isOutOfLine();
2657 SourceRange FunctionDecl::getSourceRange() const {
2658 return SourceRange(getOuterLocStart(), EndRangeLoc);
2661 unsigned FunctionDecl::getMemoryFunctionKind() const {
2662 IdentifierInfo *FnInfo = getIdentifier();
2667 // Builtin handling.
2668 switch (getBuiltinID()) {
2669 case Builtin::BI__builtin_memset:
2670 case Builtin::BI__builtin___memset_chk:
2671 case Builtin::BImemset:
2672 return Builtin::BImemset;
2674 case Builtin::BI__builtin_memcpy:
2675 case Builtin::BI__builtin___memcpy_chk:
2676 case Builtin::BImemcpy:
2677 return Builtin::BImemcpy;
2679 case Builtin::BI__builtin_memmove:
2680 case Builtin::BI__builtin___memmove_chk:
2681 case Builtin::BImemmove:
2682 return Builtin::BImemmove;
2684 case Builtin::BIstrlcpy:
2685 return Builtin::BIstrlcpy;
2686 case Builtin::BIstrlcat:
2687 return Builtin::BIstrlcat;
2689 case Builtin::BI__builtin_memcmp:
2690 case Builtin::BImemcmp:
2691 return Builtin::BImemcmp;
2693 case Builtin::BI__builtin_strncpy:
2694 case Builtin::BI__builtin___strncpy_chk:
2695 case Builtin::BIstrncpy:
2696 return Builtin::BIstrncpy;
2698 case Builtin::BI__builtin_strncmp:
2699 case Builtin::BIstrncmp:
2700 return Builtin::BIstrncmp;
2702 case Builtin::BI__builtin_strncasecmp:
2703 case Builtin::BIstrncasecmp:
2704 return Builtin::BIstrncasecmp;
2706 case Builtin::BI__builtin_strncat:
2707 case Builtin::BI__builtin___strncat_chk:
2708 case Builtin::BIstrncat:
2709 return Builtin::BIstrncat;
2711 case Builtin::BI__builtin_strndup:
2712 case Builtin::BIstrndup:
2713 return Builtin::BIstrndup;
2715 case Builtin::BI__builtin_strlen:
2716 case Builtin::BIstrlen:
2717 return Builtin::BIstrlen;
2721 if (FnInfo->isStr("memset"))
2722 return Builtin::BImemset;
2723 else if (FnInfo->isStr("memcpy"))
2724 return Builtin::BImemcpy;
2725 else if (FnInfo->isStr("memmove"))
2726 return Builtin::BImemmove;
2727 else if (FnInfo->isStr("memcmp"))
2728 return Builtin::BImemcmp;
2729 else if (FnInfo->isStr("strncpy"))
2730 return Builtin::BIstrncpy;
2731 else if (FnInfo->isStr("strncmp"))
2732 return Builtin::BIstrncmp;
2733 else if (FnInfo->isStr("strncasecmp"))
2734 return Builtin::BIstrncasecmp;
2735 else if (FnInfo->isStr("strncat"))
2736 return Builtin::BIstrncat;
2737 else if (FnInfo->isStr("strndup"))
2738 return Builtin::BIstrndup;
2739 else if (FnInfo->isStr("strlen"))
2740 return Builtin::BIstrlen;
2747 //===----------------------------------------------------------------------===//
2748 // FieldDecl Implementation
2749 //===----------------------------------------------------------------------===//
2751 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
2752 SourceLocation StartLoc, SourceLocation IdLoc,
2753 IdentifierInfo *Id, QualType T,
2754 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2755 InClassInitStyle InitStyle) {
2756 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
2757 BW, Mutable, InitStyle);
2760 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2761 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
2762 return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
2763 0, QualType(), 0, 0, false, ICIS_NoInit);
2766 bool FieldDecl::isAnonymousStructOrUnion() const {
2767 if (!isImplicit() || getDeclName())
2770 if (const RecordType *Record = getType()->getAs<RecordType>())
2771 return Record->getDecl()->isAnonymousStructOrUnion();
2776 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2777 assert(isBitField() && "not a bitfield");
2778 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2779 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2782 unsigned FieldDecl::getFieldIndex() const {
2783 if (CachedFieldIndex) return CachedFieldIndex - 1;
2786 const RecordDecl *RD = getParent();
2787 const FieldDecl *LastFD = 0;
2788 bool IsMsStruct = RD->isMsStruct(getASTContext());
2790 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2791 I != E; ++I, ++Index) {
2792 I->CachedFieldIndex = Index + 1;
2795 // Zero-length bitfields following non-bitfield members are ignored.
2796 if (getASTContext().ZeroBitfieldFollowsNonBitfield(*I, LastFD)) {
2804 assert(CachedFieldIndex && "failed to find field in parent");
2805 return CachedFieldIndex - 1;
2808 SourceRange FieldDecl::getSourceRange() const {
2809 if (const Expr *E = InitializerOrBitWidth.getPointer())
2810 return SourceRange(getInnerLocStart(), E->getLocEnd());
2811 return DeclaratorDecl::getSourceRange();
2814 void FieldDecl::setBitWidth(Expr *Width) {
2815 assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
2816 "bit width or initializer already set");
2817 InitializerOrBitWidth.setPointer(Width);
2820 void FieldDecl::setInClassInitializer(Expr *Init) {
2821 assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
2822 "bit width or initializer already set");
2823 InitializerOrBitWidth.setPointer(Init);
2826 //===----------------------------------------------------------------------===//
2827 // TagDecl Implementation
2828 //===----------------------------------------------------------------------===//
2830 SourceLocation TagDecl::getOuterLocStart() const {
2831 return getTemplateOrInnerLocStart(this);
2834 SourceRange TagDecl::getSourceRange() const {
2835 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
2836 return SourceRange(getOuterLocStart(), E);
2839 TagDecl* TagDecl::getCanonicalDecl() {
2840 return getFirstDeclaration();
2843 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2844 TypedefNameDeclOrQualifier = TDD;
2846 assert(TypeForDecl->isLinkageValid());
2847 assert(isLinkageValid());
2850 void TagDecl::startDefinition() {
2851 IsBeingDefined = true;
2853 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
2854 struct CXXRecordDecl::DefinitionData *Data =
2855 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
2856 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2857 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
2861 void TagDecl::completeDefinition() {
2862 assert((!isa<CXXRecordDecl>(this) ||
2863 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2864 "definition completed but not started");
2866 IsCompleteDefinition = true;
2867 IsBeingDefined = false;
2869 if (ASTMutationListener *L = getASTMutationListener())
2870 L->CompletedTagDefinition(this);
2873 TagDecl *TagDecl::getDefinition() const {
2874 if (isCompleteDefinition())
2875 return const_cast<TagDecl *>(this);
2877 // If it's possible for us to have an out-of-date definition, check now.
2878 if (MayHaveOutOfDateDef) {
2879 if (IdentifierInfo *II = getIdentifier()) {
2880 if (II->isOutOfDate()) {
2881 updateOutOfDate(*II);
2886 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2887 return CXXRD->getDefinition();
2889 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
2891 if (R->isCompleteDefinition())
2897 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2899 // Make sure the extended qualifier info is allocated.
2901 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
2902 // Set qualifier info.
2903 getExtInfo()->QualifierLoc = QualifierLoc;
2905 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
2907 if (getExtInfo()->NumTemplParamLists == 0) {
2908 getASTContext().Deallocate(getExtInfo());
2909 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
2912 getExtInfo()->QualifierLoc = QualifierLoc;
2917 void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2918 unsigned NumTPLists,
2919 TemplateParameterList **TPLists) {
2920 assert(NumTPLists > 0);
2921 // Make sure the extended decl info is allocated.
2923 // Allocate external info struct.
2924 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
2925 // Set the template parameter lists info.
2926 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2929 //===----------------------------------------------------------------------===//
2930 // EnumDecl Implementation
2931 //===----------------------------------------------------------------------===//
2933 void EnumDecl::anchor() { }
2935 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2936 SourceLocation StartLoc, SourceLocation IdLoc,
2938 EnumDecl *PrevDecl, bool IsScoped,
2939 bool IsScopedUsingClassTag, bool IsFixed) {
2940 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
2941 IsScoped, IsScopedUsingClassTag, IsFixed);
2942 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
2943 C.getTypeDeclType(Enum, PrevDecl);
2947 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2948 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
2949 EnumDecl *Enum = new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(),
2950 0, 0, false, false, false);
2951 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
2955 void EnumDecl::completeDefinition(QualType NewType,
2956 QualType NewPromotionType,
2957 unsigned NumPositiveBits,
2958 unsigned NumNegativeBits) {
2959 assert(!isCompleteDefinition() && "Cannot redefine enums!");
2961 IntegerType = NewType.getTypePtr();
2962 PromotionType = NewPromotionType;
2963 setNumPositiveBits(NumPositiveBits);
2964 setNumNegativeBits(NumNegativeBits);
2965 TagDecl::completeDefinition();
2968 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
2969 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2970 return MSI->getTemplateSpecializationKind();
2972 return TSK_Undeclared;
2975 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2976 SourceLocation PointOfInstantiation) {
2977 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
2978 assert(MSI && "Not an instantiated member enumeration?");
2979 MSI->setTemplateSpecializationKind(TSK);
2980 if (TSK != TSK_ExplicitSpecialization &&
2981 PointOfInstantiation.isValid() &&
2982 MSI->getPointOfInstantiation().isInvalid())
2983 MSI->setPointOfInstantiation(PointOfInstantiation);
2986 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
2987 if (SpecializationInfo)
2988 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
2993 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
2994 TemplateSpecializationKind TSK) {
2995 assert(!SpecializationInfo && "Member enum is already a specialization");
2996 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
2999 //===----------------------------------------------------------------------===//
3000 // RecordDecl Implementation
3001 //===----------------------------------------------------------------------===//
3003 RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
3004 SourceLocation StartLoc, SourceLocation IdLoc,
3005 IdentifierInfo *Id, RecordDecl *PrevDecl)
3006 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
3007 HasFlexibleArrayMember = false;
3008 AnonymousStructOrUnion = false;
3009 HasObjectMember = false;
3010 HasVolatileMember = false;
3011 LoadedFieldsFromExternalStorage = false;
3012 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
3015 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3016 SourceLocation StartLoc, SourceLocation IdLoc,
3017 IdentifierInfo *Id, RecordDecl* PrevDecl) {
3018 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
3020 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3022 C.getTypeDeclType(R, PrevDecl);
3026 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
3027 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
3028 RecordDecl *R = new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
3029 SourceLocation(), 0, 0);
3030 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3034 bool RecordDecl::isInjectedClassName() const {
3035 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
3036 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3039 RecordDecl::field_iterator RecordDecl::field_begin() const {
3040 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3041 LoadFieldsFromExternalStorage();
3043 return field_iterator(decl_iterator(FirstDecl));
3046 /// completeDefinition - Notes that the definition of this type is now
3048 void RecordDecl::completeDefinition() {
3049 assert(!isCompleteDefinition() && "Cannot redefine record!");
3050 TagDecl::completeDefinition();
3053 /// isMsStruct - Get whether or not this record uses ms_struct layout.
3054 /// This which can be turned on with an attribute, pragma, or the
3055 /// -mms-bitfields command-line option.
3056 bool RecordDecl::isMsStruct(const ASTContext &C) const {
3057 return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3060 static bool isFieldOrIndirectField(Decl::Kind K) {
3061 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3064 void RecordDecl::LoadFieldsFromExternalStorage() const {
3065 ExternalASTSource *Source = getASTContext().getExternalSource();
3066 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3068 // Notify that we have a RecordDecl doing some initialization.
3069 ExternalASTSource::Deserializing TheFields(Source);
3071 SmallVector<Decl*, 64> Decls;
3072 LoadedFieldsFromExternalStorage = true;
3073 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3078 case ELR_AlreadyLoaded:
3084 // Check that all decls we got were FieldDecls.
3085 for (unsigned i=0, e=Decls.size(); i != e; ++i)
3086 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
3092 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
3093 /*FieldsAlreadyLoaded=*/false);
3096 //===----------------------------------------------------------------------===//
3097 // BlockDecl Implementation
3098 //===----------------------------------------------------------------------===//
3100 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
3101 assert(ParamInfo == 0 && "Already has param info!");
3103 // Zero params -> null pointer.
3104 if (!NewParamInfo.empty()) {
3105 NumParams = NewParamInfo.size();
3106 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3107 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3111 void BlockDecl::setCaptures(ASTContext &Context,
3112 const Capture *begin,
3114 bool capturesCXXThis) {
3115 CapturesCXXThis = capturesCXXThis;
3123 NumCaptures = end - begin;
3125 // Avoid new Capture[] because we don't want to provide a default
3127 size_t allocationSize = NumCaptures * sizeof(Capture);
3128 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3129 memcpy(buffer, begin, allocationSize);
3130 Captures = static_cast<Capture*>(buffer);
3133 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3134 for (capture_const_iterator
3135 i = capture_begin(), e = capture_end(); i != e; ++i)
3136 // Only auto vars can be captured, so no redeclaration worries.
3137 if (i->getVariable() == variable)
3143 SourceRange BlockDecl::getSourceRange() const {
3144 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3147 //===----------------------------------------------------------------------===//
3148 // Other Decl Allocation/Deallocation Method Implementations
3149 //===----------------------------------------------------------------------===//
3151 void TranslationUnitDecl::anchor() { }
3153 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
3154 return new (C) TranslationUnitDecl(C);
3157 void LabelDecl::anchor() { }
3159 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3160 SourceLocation IdentL, IdentifierInfo *II) {
3161 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
3164 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3165 SourceLocation IdentL, IdentifierInfo *II,
3166 SourceLocation GnuLabelL) {
3167 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
3168 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
3171 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3172 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
3173 return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
3176 void ValueDecl::anchor() { }
3178 bool ValueDecl::isWeak() const {
3179 for (attr_iterator I = attr_begin(), E = attr_end(); I != E; ++I)
3180 if (isa<WeakAttr>(*I) || isa<WeakRefAttr>(*I))
3183 return isWeakImported();
3186 void ImplicitParamDecl::anchor() { }
3188 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
3189 SourceLocation IdLoc,
3192 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
3195 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
3197 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
3198 return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
3201 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
3202 SourceLocation StartLoc,
3203 const DeclarationNameInfo &NameInfo,
3204 QualType T, TypeSourceInfo *TInfo,
3206 bool isInlineSpecified,
3207 bool hasWrittenPrototype,
3208 bool isConstexprSpecified) {
3209 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
3212 isConstexprSpecified);
3213 New->HasWrittenPrototype = hasWrittenPrototype;
3217 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3218 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
3219 return new (Mem) FunctionDecl(Function, 0, SourceLocation(),
3220 DeclarationNameInfo(), QualType(), 0,
3221 SC_None, false, false);
3224 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3225 return new (C) BlockDecl(DC, L);
3228 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3229 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
3230 return new (Mem) BlockDecl(0, SourceLocation());
3233 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3235 IdentifierInfo *Id, QualType T,
3236 Expr *E, const llvm::APSInt &V) {
3237 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
3241 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3242 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
3243 return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
3247 void IndirectFieldDecl::anchor() { }
3250 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3251 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3253 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
3256 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3258 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
3259 return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
3263 SourceRange EnumConstantDecl::getSourceRange() const {
3264 SourceLocation End = getLocation();
3266 End = Init->getLocEnd();
3267 return SourceRange(getLocation(), End);
3270 void TypeDecl::anchor() { }
3272 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
3273 SourceLocation StartLoc, SourceLocation IdLoc,
3274 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
3275 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
3278 void TypedefNameDecl::anchor() { }
3280 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3281 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
3282 return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3285 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3286 SourceLocation StartLoc,
3287 SourceLocation IdLoc, IdentifierInfo *Id,
3288 TypeSourceInfo *TInfo) {
3289 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
3292 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3293 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
3294 return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3297 SourceRange TypedefDecl::getSourceRange() const {
3298 SourceLocation RangeEnd = getLocation();
3299 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3300 if (typeIsPostfix(TInfo->getType()))
3301 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3303 return SourceRange(getLocStart(), RangeEnd);
3306 SourceRange TypeAliasDecl::getSourceRange() const {
3307 SourceLocation RangeEnd = getLocStart();
3308 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3309 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3310 return SourceRange(getLocStart(), RangeEnd);
3313 void FileScopeAsmDecl::anchor() { }
3315 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
3317 SourceLocation AsmLoc,
3318 SourceLocation RParenLoc) {
3319 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
3322 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
3324 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
3325 return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
3328 void EmptyDecl::anchor() {}
3330 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3331 return new (C) EmptyDecl(DC, L);
3334 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3335 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EmptyDecl));
3336 return new (Mem) EmptyDecl(0, SourceLocation());
3339 //===----------------------------------------------------------------------===//
3340 // ImportDecl Implementation
3341 //===----------------------------------------------------------------------===//
3343 /// \brief Retrieve the number of module identifiers needed to name the given
3345 static unsigned getNumModuleIdentifiers(Module *Mod) {
3346 unsigned Result = 1;
3347 while (Mod->Parent) {
3354 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3356 ArrayRef<SourceLocation> IdentifierLocs)
3357 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
3360 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3361 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3362 memcpy(StoredLocs, IdentifierLocs.data(),
3363 IdentifierLocs.size() * sizeof(SourceLocation));
3366 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3367 Module *Imported, SourceLocation EndLoc)
3368 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
3371 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3374 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
3375 SourceLocation StartLoc, Module *Imported,
3376 ArrayRef<SourceLocation> IdentifierLocs) {
3377 void *Mem = C.Allocate(sizeof(ImportDecl) +
3378 IdentifierLocs.size() * sizeof(SourceLocation));
3379 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
3382 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
3383 SourceLocation StartLoc,
3385 SourceLocation EndLoc) {
3386 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
3387 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
3388 Import->setImplicit();
3392 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3393 unsigned NumLocations) {
3394 void *Mem = AllocateDeserializedDecl(C, ID,
3395 (sizeof(ImportDecl) +
3396 NumLocations * sizeof(SourceLocation)));
3397 return new (Mem) ImportDecl(EmptyShell());
3400 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3401 if (!ImportedAndComplete.getInt())
3402 return ArrayRef<SourceLocation>();
3404 const SourceLocation *StoredLocs
3405 = reinterpret_cast<const SourceLocation *>(this + 1);
3406 return ArrayRef<SourceLocation>(StoredLocs,
3407 getNumModuleIdentifiers(getImportedModule()));
3410 SourceRange ImportDecl::getSourceRange() const {
3411 if (!ImportedAndComplete.getInt())
3412 return SourceRange(getLocation(),
3413 *reinterpret_cast<const SourceLocation *>(this + 1));
3415 return SourceRange(getLocation(), getIdentifierLocs().back());