blob: 038c7acb0f8b1db2ebd2e13f8ecf30eb0674192f [file] [log] [blame]
Chris Lattnera11999d2006-10-15 22:34:45 +00001//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera11999d2006-10-15 22:34:45 +00007//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidis63018842008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Chris Lattnera11999d2006-10-15 22:34:45 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
Chris Lattnera7b32872008-03-15 06:12:44 +000015#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000021#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000023#include "clang/AST/PrettyPrinter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000024#include "clang/AST/Stmt.h"
25#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000027#include "clang/Basic/IdentifierTable.h"
Douglas Gregorba345522011-12-02 23:23:56 +000028#include "clang/Basic/Module.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000029#include "clang/Basic/Specifiers.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000030#include "clang/Basic/TargetInfo.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000031#include "llvm/Support/ErrorHandling.h"
David Blaikie9c70e042011-09-21 18:16:56 +000032#include <algorithm>
33
Chris Lattner6d9a6852006-10-25 05:11:20 +000034using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000035
Richard Smith0b87e072013-10-07 08:02:11 +000036Decl *clang::getPrimaryMergedDecl(Decl *D) {
37 return D->getASTContext().getPrimaryMergedDecl(D);
38}
39
Chris Lattner88f70d62008-03-15 05:43:15 +000040//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000041// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000042//===----------------------------------------------------------------------===//
43
John McCalldf25c432013-02-16 00:17:33 +000044// Visibility rules aren't rigorously externally specified, but here
45// are the basic principles behind what we implement:
46//
47// 1. An explicit visibility attribute is generally a direct expression
48// of the user's intent and should be honored. Only the innermost
49// visibility attribute applies. If no visibility attribute applies,
50// global visibility settings are considered.
51//
52// 2. There is one caveat to the above: on or in a template pattern,
53// an explicit visibility attribute is just a default rule, and
54// visibility can be decreased by the visibility of template
55// arguments. But this, too, has an exception: an attribute on an
56// explicit specialization or instantiation causes all the visibility
57// restrictions of the template arguments to be ignored.
58//
59// 3. A variable that does not otherwise have explicit visibility can
60// be restricted by the visibility of its type.
61//
62// 4. A visibility restriction is explicit if it comes from an
63// attribute (or something like it), not a global visibility setting.
64// When emitting a reference to an external symbol, visibility
65// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +000066//
67// 5. When computing the visibility of a non-type, including a
68// non-type member of a class, only non-type visibility restrictions
69// are considered: the 'visibility' attribute, global value-visibility
70// settings, and a few special cases like __private_extern.
71//
72// 6. When computing the visibility of a type, including a type member
73// of a class, only type visibility restrictions are considered:
74// the 'type_visibility' attribute and global type-visibility settings.
75// However, a 'visibility' attribute counts as a 'type_visibility'
76// attribute on any declaration that only has the former.
77//
78// The visibility of a "secondary" entity, like a template argument,
79// is computed using the kind of that entity, not the kind of the
80// primary entity for which we are computing visibility. For example,
81// the visibility of a specialization of either of these templates:
82// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
83// template <class T, bool (&compare)(T, X)> class matcher;
84// is restricted according to the type visibility of the argument 'T',
85// the type visibility of 'bool(&)(T,X)', and the value visibility of
86// the argument function 'compare'. That 'has_match' is a value
87// and 'matcher' is a type only matters when looking for attributes
88// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +000089
John McCall5f46c482013-02-21 23:42:58 +000090const unsigned IgnoreExplicitVisibilityBit = 2;
Rafael Espindola9551d3b2013-05-28 19:43:11 +000091const unsigned IgnoreAllVisibilityBit = 4;
John McCall5f46c482013-02-21 23:42:58 +000092
John McCalldf25c432013-02-16 00:17:33 +000093/// Kinds of LV computation. The linkage side of the computation is
94/// always the same, but different things can change how visibility is
95/// computed.
96enum LVComputationKind {
John McCall5f46c482013-02-21 23:42:58 +000097 /// Do an LV computation for, ultimately, a type.
98 /// Visibility may be restricted by type visibility settings and
99 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000100 LVForType = NamedDecl::VisibilityForType,
John McCalldf25c432013-02-16 00:17:33 +0000101
John McCall5f46c482013-02-21 23:42:58 +0000102 /// Do an LV computation for, ultimately, a non-type declaration.
103 /// Visibility may be restricted by value visibility settings and
104 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000105 LVForValue = NamedDecl::VisibilityForValue,
106
John McCall5f46c482013-02-21 23:42:58 +0000107 /// Do an LV computation for, ultimately, a type that already has
108 /// some sort of explicit visibility. Visibility may only be
109 /// restricted by the visibility of template arguments.
110 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
John McCalld041a9b2013-02-20 01:54:26 +0000111
John McCall5f46c482013-02-21 23:42:58 +0000112 /// Do an LV computation for, ultimately, a non-type declaration
113 /// that already has some sort of explicit visibility. Visibility
114 /// may only be restricted by the visibility of template arguments.
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000115 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
116
117 /// Do an LV computation when we only care about the linkage.
118 LVForLinkageOnly =
119 LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
John McCalldf25c432013-02-16 00:17:33 +0000120};
121
John McCalld041a9b2013-02-20 01:54:26 +0000122/// Does this computation kind permit us to consider additional
123/// visibility settings from attributes and the like?
124static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000125 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
John McCalld041a9b2013-02-20 01:54:26 +0000126}
127
128/// Given an LVComputationKind, return one of the same type/value sort
129/// that records that it already has explicit visibility.
130static LVComputationKind
131withExplicitVisibilityAlready(LVComputationKind oldKind) {
132 LVComputationKind newKind =
John McCall5f46c482013-02-21 23:42:58 +0000133 static_cast<LVComputationKind>(unsigned(oldKind) |
134 IgnoreExplicitVisibilityBit);
John McCalld041a9b2013-02-20 01:54:26 +0000135 assert(oldKind != LVForType || newKind == LVForExplicitType);
136 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
137 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
138 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
139 return newKind;
140}
141
David Blaikie05785d12013-02-20 22:23:23 +0000142static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
143 LVComputationKind kind) {
John McCalld041a9b2013-02-20 01:54:26 +0000144 assert(!hasExplicitVisibilityAlready(kind) &&
145 "asking for explicit visibility when we shouldn't be");
146 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
147}
148
John McCalldf25c432013-02-16 00:17:33 +0000149/// Is the given declaration a "type" or a "value" for the purposes of
150/// visibility computation?
151static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000152 return isa<TypeDecl>(D) ||
153 isa<ClassTemplateDecl>(D) ||
154 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000155}
156
John McCall5f46c482013-02-21 23:42:58 +0000157/// Does the given declaration have member specialization information,
158/// and if so, is it an explicit specialization?
159template <class T> static typename
Benjamin Kramered2f4762014-03-07 14:30:23 +0000160std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-02-21 23:42:58 +0000161isExplicitMemberSpecialization(const T *D) {
162 if (const MemberSpecializationInfo *member =
163 D->getMemberSpecializationInfo()) {
164 return member->isExplicitSpecialization();
165 }
166 return false;
167}
168
169/// For templates, this question is easier: a member template can't be
170/// explicitly instantiated, so there's a single bit indicating whether
171/// or not this is an explicit member specialization.
172static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
173 return D->isMemberSpecialization();
174}
175
John McCalld041a9b2013-02-20 01:54:26 +0000176/// Given a visibility attribute, return the explicit visibility
177/// associated with it.
178template <class T>
179static Visibility getVisibilityFromAttr(const T *attr) {
180 switch (attr->getVisibility()) {
181 case T::Default:
182 return DefaultVisibility;
183 case T::Hidden:
184 return HiddenVisibility;
185 case T::Protected:
186 return ProtectedVisibility;
187 }
188 llvm_unreachable("bad visibility kind");
189}
190
John McCalldf25c432013-02-16 00:17:33 +0000191/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000192static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000193 NamedDecl::ExplicitVisibilityKind kind) {
194 // If we're ultimately computing the visibility of a type, look for
195 // a 'type_visibility' attribute before looking for 'visibility'.
196 if (kind == NamedDecl::VisibilityForType) {
197 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
198 return getVisibilityFromAttr(A);
199 }
200 }
201
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000202 // If this declaration has an explicit visibility attribute, use it.
203 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000204 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000205 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000206
207 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
208 // implies visibility(default).
Douglas Gregore8bbc122011-09-02 00:18:52 +0000209 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000210 for (const auto *A : D->specific_attrs<AvailabilityAttr>())
211 if (A->getPlatform()->getName().equals("macosx"))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000212 return DefaultVisibility;
213 }
214
David Blaikie7a30dc52013-02-21 01:47:18 +0000215 return None;
John McCall457a04e2010-10-22 21:05:15 +0000216}
217
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000218static LinkageInfo
219getLVForType(const Type &T, LVComputationKind computation) {
220 if (computation == LVForLinkageOnly)
221 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
222 return T.getLinkageAndVisibility();
223}
224
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000225/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000226/// template parameter list. For visibility purposes, template
227/// parameters are part of the signature of a template.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000228static LinkageInfo
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000229getLVForTemplateParameterList(const TemplateParameterList *params,
230 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000231 LinkageInfo LV;
232 for (TemplateParameterList::const_iterator P = params->begin(),
233 PEnd = params->end();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000234 P != PEnd; ++P) {
John McCalldf25c432013-02-16 00:17:33 +0000235
236 // Template type parameters are the most common and never
237 // contribute to visibility, pack or not.
238 if (isa<TemplateTypeParmDecl>(*P))
239 continue;
240
241 // Non-type template parameters can be restricted by the value type, e.g.
242 // template <enum X> class A { ... };
243 // We have to be careful here, though, because we can be dealing with
244 // dependent types.
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000245 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
John McCalldf25c432013-02-16 00:17:33 +0000246 // Handle the non-pack case first.
247 if (!NTTP->isExpandedParameterPack()) {
248 if (!NTTP->getType()->isDependentType()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000249 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000250 }
251 continue;
252 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000253
John McCalldf25c432013-02-16 00:17:33 +0000254 // Look at all the types in an expanded pack.
255 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
256 QualType type = NTTP->getExpansionType(i);
257 if (!type->isDependentType())
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000258 LV.merge(type->getLinkageAndVisibility());
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000259 }
John McCalldf25c432013-02-16 00:17:33 +0000260 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000261 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000262
John McCalldf25c432013-02-16 00:17:33 +0000263 // Template template parameters can be restricted by their
264 // template parameters, recursively.
265 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
266
267 // Handle the non-pack case first.
268 if (!TTP->isExpandedParameterPack()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000269 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
270 computation));
John McCalldf25c432013-02-16 00:17:33 +0000271 continue;
272 }
273
274 // Look at all expansions in an expanded pack.
275 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
276 i != n; ++i) {
277 LV.merge(getLVForTemplateParameterList(
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000278 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000279 }
280 }
281
John McCall457a04e2010-10-22 21:05:15 +0000282 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000283}
284
Rafael Espindola19de5612013-01-12 06:42:30 +0000285/// getLVForDecl - Get the linkage and visibility for the given declaration.
John McCalldf25c432013-02-16 00:17:33 +0000286static LinkageInfo getLVForDecl(const NamedDecl *D,
287 LVComputationKind computation);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000288
Eli Friedman7e346a82013-07-01 20:22:57 +0000289static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
290 const Decl *Ret = NULL;
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000291 const DeclContext *DC = D->getDeclContext();
292 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman7e346a82013-07-01 20:22:57 +0000293 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
294 Ret = cast<Decl>(DC);
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000295 DC = DC->getParent();
296 }
297 return Ret;
298}
299
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000300/// \brief Get the most restrictive linkage for the types and
301/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000302///
303/// Note that we don't take an LVComputationKind because we always
304/// want to honor the visibility of template arguments in the same way.
305static LinkageInfo
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000306getLVForTemplateArgumentList(ArrayRef<TemplateArgument> args,
307 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000308 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000309
John McCalldf25c432013-02-16 00:17:33 +0000310 for (unsigned i = 0, e = args.size(); i != e; ++i) {
311 const TemplateArgument &arg = args[i];
312 switch (arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000313 case TemplateArgument::Null:
314 case TemplateArgument::Integral:
315 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000316 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000317
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000318 case TemplateArgument::Type:
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000319 LV.merge(getLVForType(*arg.getAsType(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000320 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000321
322 case TemplateArgument::Declaration:
John McCalldf25c432013-02-16 00:17:33 +0000323 if (NamedDecl *ND = dyn_cast<NamedDecl>(arg.getAsDecl())) {
324 assert(!usesTypeVisibility(ND));
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000325 LV.merge(getLVForDecl(ND, computation));
John McCalldf25c432013-02-16 00:17:33 +0000326 }
327 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +0000328
329 case TemplateArgument::NullPtr:
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000330 LV.merge(arg.getNullPtrType()->getLinkageAndVisibility());
John McCalldf25c432013-02-16 00:17:33 +0000331 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000332
333 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000334 case TemplateArgument::TemplateExpansion:
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000335 if (TemplateDecl *Template
John McCalldf25c432013-02-16 00:17:33 +0000336 = arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000337 LV.merge(getLVForDecl(Template, computation));
John McCalldf25c432013-02-16 00:17:33 +0000338 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000339
340 case TemplateArgument::Pack:
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000341 LV.merge(getLVForTemplateArgumentList(arg.getPackAsArray(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000342 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000343 }
John McCalldf25c432013-02-16 00:17:33 +0000344 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000345 }
346
John McCall457a04e2010-10-22 21:05:15 +0000347 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000348}
349
Rafael Espindola2f869a32012-01-14 00:30:36 +0000350static LinkageInfo
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000351getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
352 LVComputationKind computation) {
353 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall8823c652010-08-13 08:35:10 +0000354}
355
John McCall5f46c482013-02-21 23:42:58 +0000356static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
357 const FunctionTemplateSpecializationInfo *specInfo) {
358 // Include visibility from the template parameters and arguments
359 // only if this is not an explicit instantiation or specialization
360 // with direct explicit visibility. (Implicit instantiations won't
361 // have a direct attribute.)
362 if (!specInfo->isExplicitInstantiationOrSpecialization())
363 return true;
364
365 return !fn->hasAttr<VisibilityAttr>();
366}
367
John McCalldf25c432013-02-16 00:17:33 +0000368/// Merge in template-related linkage and visibility for the given
369/// function template specialization.
370///
371/// We don't need a computation kind here because we can assume
372/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000373///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000374/// \param[out] LV the computation to use for the parent
John McCall5f46c482013-02-21 23:42:58 +0000375static void
376mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000377 const FunctionTemplateSpecializationInfo *specInfo,
378 LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000379 bool considerVisibility =
380 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000381
382 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000383 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000384 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000385 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000386 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
387
388 // Merge information from the template arguments.
389 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000390 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCalldf25c432013-02-16 00:17:33 +0000391 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000392}
393
John McCall5f46c482013-02-21 23:42:58 +0000394/// Does the given declaration have a direct visibility attribute
395/// that would match the given rules?
396static bool hasDirectVisibilityAttribute(const NamedDecl *D,
397 LVComputationKind computation) {
398 switch (computation) {
399 case LVForType:
400 case LVForExplicitType:
401 if (D->hasAttr<TypeVisibilityAttr>())
402 return true;
403 // fallthrough
404 case LVForValue:
405 case LVForExplicitValue:
406 if (D->hasAttr<VisibilityAttr>())
407 return true;
408 return false;
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000409 case LVForLinkageOnly:
410 return false;
John McCall5f46c482013-02-21 23:42:58 +0000411 }
412 llvm_unreachable("bad visibility computation kind");
413}
414
John McCalld041a9b2013-02-20 01:54:26 +0000415/// Should we consider visibility associated with the template
416/// arguments and parameters of the given class template specialization?
417static bool shouldConsiderTemplateVisibility(
418 const ClassTemplateSpecializationDecl *spec,
419 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000420 // Include visibility from the template parameters and arguments
421 // only if this is not an explicit instantiation or specialization
422 // with direct explicit visibility (and note that implicit
423 // instantiations won't have a direct attribute).
424 //
425 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000426 // for an explicit specialization when computing the visibility of a
427 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000428 //
429 // This is a bit complex; let's unpack it.
430 //
431 // An explicit class specialization is an independent, top-level
432 // declaration. As such, if it or any of its members has an
433 // explicit visibility attribute, that must directly express the
434 // user's intent, and we should honor it. The same logic applies to
435 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000436
437 // Fast path: if this is not an explicit instantiation or
438 // specialization, we always want to consider template-related
439 // visibility restrictions.
440 if (!spec->isExplicitInstantiationOrSpecialization())
441 return true;
442
443 // This is the 'member thereof' check.
444 if (spec->isExplicitSpecialization() &&
445 hasExplicitVisibilityAlready(computation))
446 return false;
447
John McCall5f46c482013-02-21 23:42:58 +0000448 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000449}
450
451/// Merge in template-related linkage and visibility for the given
452/// class template specialization.
453static void mergeTemplateLV(LinkageInfo &LV,
454 const ClassTemplateSpecializationDecl *spec,
455 LVComputationKind computation) {
456 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000457
458 // Merge information from the template parameters, but ignore
459 // visibility if we're only considering template arguments.
460
John McCalld041a9b2013-02-20 01:54:26 +0000461 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000462 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000463 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000464 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000465 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000466
467 // Merge information from the template arguments. We ignore
468 // template-argument visibility if we've got an explicit
469 // instantiation with a visibility attribute.
470 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000471 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000472 if (considerVisibility)
473 LV.mergeVisibility(argsLV);
474 LV.mergeExternalVisibility(argsLV);
John McCallb8c604a2011-06-27 23:06:04 +0000475}
476
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000477static bool useInlineVisibilityHidden(const NamedDecl *D) {
478 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000479 const LangOptions &Opts = D->getASTContext().getLangOpts();
480 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000481 return false;
482
483 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
484 if (!FD)
485 return false;
486
487 TemplateSpecializationKind TSK = TSK_Undeclared;
488 if (FunctionTemplateSpecializationInfo *spec
489 = FD->getTemplateSpecializationInfo()) {
490 TSK = spec->getTemplateSpecializationKind();
491 } else if (MemberSpecializationInfo *MSI =
492 FD->getMemberSpecializationInfo()) {
493 TSK = MSI->getTemplateSpecializationKind();
494 }
495
496 const FunctionDecl *Def = 0;
497 // InlineVisibilityHidden only applies to definitions, and
498 // isInlined() only gives meaningful answers on definitions
499 // anyway.
500 return TSK != TSK_ExplicitInstantiationDeclaration &&
501 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000502 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000503}
504
Rafael Espindola593537a2013-05-05 20:15:21 +0000505template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000506 const T *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +0000507 return First->isInExternCContext();
Rafael Espindolaf4187652013-02-14 01:18:37 +0000508}
509
Richard Smith03c05032014-02-17 23:34:47 +0000510static bool isSingleLineLanguageLinkage(const Decl &D) {
Rafael Espindola327be3c2013-04-26 01:30:23 +0000511 if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Richard Smith03c05032014-02-17 23:34:47 +0000512 if (!SD->hasBraces())
Rafael Espindola327be3c2013-04-26 01:30:23 +0000513 return true;
514 return false;
515}
516
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000517static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
John McCalldf25c432013-02-16 00:17:33 +0000518 LVComputationKind computation) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000519 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000520 "Not a name having namespace scope");
521 ASTContext &Context = D->getASTContext();
522
523 // C++ [basic.link]p3:
524 // A name having namespace scope (3.3.6) has internal linkage if it
525 // is the name of
526 // - an object, reference, function or function template that is
527 // explicitly declared static; or,
528 // (This bullet corresponds to C99 6.2.2p3.)
529 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
530 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000531 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000532 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000533
Richard Smithdc0ef452012-10-19 06:37:48 +0000534 // - a non-volatile object or reference that is explicitly declared const
535 // or constexpr and neither explicitly declared extern nor previously
536 // declared to have external linkage; or (there is no equivalent in C99)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000537 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000538 Var->getType().isConstQualified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000539 !Var->getType().isVolatileQualified()) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000540 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000541 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000542 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000543
544 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000545 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000546 !isSingleLineLanguageLinkage(*Var))
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000547 return LinkageInfo::internal();
548 }
549
550 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
551 PrevVar = PrevVar->getPreviousDecl()) {
552 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
553 Var->getStorageClass() == SC_None)
554 return PrevVar->getLinkageAndVisibility();
555 // Explicitly declared static.
556 if (PrevVar->getStorageClass() == SC_Static)
557 return LinkageInfo::internal();
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000558 }
Alp Tokera2794f92014-01-22 07:29:52 +0000559 } else if (const FunctionDecl *Function = D->getAsFunction()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000560 // C++ [temp]p4:
561 // A non-member function template can have internal linkage; any
562 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000563
564 // Explicitly declared static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000565 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000566 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000567 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000568 // - a data member of an anonymous union.
569 assert(!isa<IndirectFieldDecl>(D) && "Didn't expect an IndirectFieldDecl!");
570 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000571
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000572 if (D->isInAnonymousNamespace()) {
573 const VarDecl *Var = dyn_cast<VarDecl>(D);
574 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
Rafael Espindola593537a2013-05-05 20:15:21 +0000575 if ((!Var || !isFirstInExternCContext(Var)) &&
576 (!Func || !isFirstInExternCContext(Func)))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000577 return LinkageInfo::uniqueExternal();
578 }
John McCallb7139c42010-10-28 04:18:25 +0000579
John McCall457a04e2010-10-22 21:05:15 +0000580 // Set up the defaults.
581
582 // C99 6.2.2p5:
583 // If the declaration of an identifier for an object has file
584 // scope and no storage-class specifier, its linkage is
585 // external.
John McCallc273f242010-10-30 11:50:40 +0000586 LinkageInfo LV;
587
John McCalld041a9b2013-02-20 01:54:26 +0000588 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000589 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000590 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000591 } else {
592 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000593 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000594 for (const DeclContext *DC = D->getDeclContext();
595 !isa<TranslationUnitDecl>(DC);
596 DC = DC->getParent()) {
597 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
598 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000599 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000600 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000601 break;
602 }
603 }
604 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000605
John McCalldf25c432013-02-16 00:17:33 +0000606 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000607 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000608 // Use global type/value visibility as appropriate.
609 Visibility globalVisibility;
610 if (computation == LVForValue) {
611 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
612 } else {
613 assert(computation == LVForType);
614 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
615 }
616 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000617
618 // If we're paying attention to global visibility, apply
619 // -finline-visibility-hidden if this is an inline method.
620 if (useInlineVisibilityHidden(D))
621 LV.mergeVisibility(HiddenVisibility, true);
622 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000623 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000624
Douglas Gregorf73b2822009-11-25 22:24:25 +0000625 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000626
Douglas Gregorf73b2822009-11-25 22:24:25 +0000627 // A name having namespace scope has external linkage if it is the
628 // name of
629 //
630 // - an object or reference, unless it has internal linkage; or
631 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000632 // GCC applies the following optimization to variables and static
633 // data members, but not to functions:
634 //
John McCall457a04e2010-10-22 21:05:15 +0000635 // Modify the variable's LV by the LV of its type unless this is
636 // C or extern "C". This follows from [basic.link]p9:
637 // A type without linkage shall not be used as the type of a
638 // variable or function with external linkage unless
639 // - the entity has C language linkage, or
640 // - the entity is declared within an unnamed namespace, or
641 // - the entity is not used or is defined in the same
642 // translation unit.
643 // and [basic.link]p10:
644 // ...the types specified by all declarations referring to a
645 // given variable or function shall be identical...
646 // C does not have an equivalent rule.
647 //
John McCall5fe84122010-10-26 04:59:26 +0000648 // Ignore this if we've got an explicit attribute; the user
649 // probably knows what they're doing.
650 //
John McCall457a04e2010-10-22 21:05:15 +0000651 // Note that we don't want to make the variable non-external
652 // because of this, but unique-external linkage suits us.
Rafael Espindola593537a2013-05-05 20:15:21 +0000653 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000654 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Rafael Espindola4a5da442013-02-27 02:56:45 +0000655 if (TypeLV.getLinkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000656 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000657 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000658 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000659 }
660
John McCall23032652010-11-02 18:38:13 +0000661 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000662 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000663
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000664 // Note that Sema::MergeVarDecl already takes care of implementing
665 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
666 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000667
Douglas Gregorf73b2822009-11-25 22:24:25 +0000668 // - a function, unless it has internal linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000669 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000670 // In theory, we can modify the function's LV by the LV of its
671 // type unless it has C linkage (see comment above about variables
672 // for justification). In practice, GCC doesn't do this, so it's
673 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000674
John McCall23032652010-11-02 18:38:13 +0000675 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000676 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000677
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000678 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
679 // merging storage classes and visibility attributes, so we don't have to
680 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000681
John McCallf768aa72011-02-10 06:50:24 +0000682 // In C++, then if the type of the function uses a type with
683 // unique-external linkage, it's not legally usable from outside
684 // this translation unit. However, we should use the C linkage
685 // rules instead for extern "C" declarations.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000686 if (Context.getLangOpts().CPlusPlus &&
Richard Smith50f4afc2013-05-12 23:17:59 +0000687 !Function->isInExternCContext()) {
688 // Only look at the type-as-written. If this function has an auto-deduced
689 // return type, we can't compute the linkage of that type because it could
690 // require looking at the linkage of this function, and we don't need this
691 // for correctness because the type is not part of the function's
692 // signature.
Faisal Valid2598e92013-10-08 04:15:04 +0000693 // FIXME: This is a hack. We should be able to solve this circularity and
694 // the one in getLVForClassMember for Functions some other way.
Richard Smith50f4afc2013-05-12 23:17:59 +0000695 QualType TypeAsWritten = Function->getType();
696 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
697 TypeAsWritten = TSI->getType();
698 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
699 return LinkageInfo::uniqueExternal();
700 }
John McCallf768aa72011-02-10 06:50:24 +0000701
John McCall5f46c482013-02-21 23:42:58 +0000702 // Consider LV from the template and the template arguments.
703 // We're at file scope, so we do not need to worry about nested
704 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000705 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000706 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000707 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000708 }
709
Douglas Gregorf73b2822009-11-25 22:24:25 +0000710 // - a named class (Clause 9), or an unnamed class defined in a
711 // typedef declaration in which the class has the typedef name
712 // for linkage purposes (7.1.3); or
713 // - a named enumeration (7.2), or an unnamed enumeration
714 // defined in a typedef declaration in which the enumeration
715 // has the typedef name for linkage purposes (7.1.3); or
John McCall457a04e2010-10-22 21:05:15 +0000716 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
717 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000718 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000719 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000720
John McCall457a04e2010-10-22 21:05:15 +0000721 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000722 // linkage of the template and template arguments. We're at file
723 // scope, so we do not need to worry about nested specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000724 if (const ClassTemplateSpecializationDecl *spec
John McCall457a04e2010-10-22 21:05:15 +0000725 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000726 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000727 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000728
729 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000730 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000731 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000732 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000733 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000734 return LinkageInfo::none();
735 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000736
737 // - a template, unless it is a function template that has
738 // internal linkage (Clause 14);
John McCall8bc6d5b2011-03-04 10:39:25 +0000739 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000740 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000741 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000742 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000743 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
744
Douglas Gregorf73b2822009-11-25 22:24:25 +0000745 // - a namespace (7.3), unless it is declared within an unnamed
746 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000747 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
748 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000749
John McCall457a04e2010-10-22 21:05:15 +0000750 // By extension, we assign external linkage to Objective-C
751 // interfaces.
752 } else if (isa<ObjCInterfaceDecl>(D)) {
753 // fallout
754
755 // Everything not covered here has no linkage.
756 } else {
John McCallc273f242010-10-30 11:50:40 +0000757 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000758 }
759
760 // If we ended up with non-external linkage, visibility should
761 // always be default.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000762 if (LV.getLinkage() != ExternalLinkage)
763 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000764
John McCall457a04e2010-10-22 21:05:15 +0000765 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000766}
767
John McCalldf25c432013-02-16 00:17:33 +0000768static LinkageInfo getLVForClassMember(const NamedDecl *D,
769 LVComputationKind computation) {
John McCall457a04e2010-10-22 21:05:15 +0000770 // Only certain class members have linkage. Note that fields don't
771 // really have linkage, but it's convenient to say they do for the
772 // purposes of calculating linkage of pointer-to-data-member
773 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000774 //
775 // Templates also don't officially have linkage, but since we ignore
776 // the C++ standard and look at template arguments when determining
777 // linkage and visibility of a template specialization, we might hit
778 // a template template argument that way. If we do, we need to
779 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000780 if (!(isa<CXXMethodDecl>(D) ||
781 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000782 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000783 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000784 isa<TagDecl>(D) ||
785 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000786 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000787
John McCall07072662010-11-02 01:45:15 +0000788 LinkageInfo LV;
789
John McCall07072662010-11-02 01:45:15 +0000790 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000791 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000792 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000793 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000794 // If we're paying attention to global visibility, apply
795 // -finline-visibility-hidden if this is an inline method.
796 //
797 // Note that we do this before merging information about
798 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000799 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000800 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000801 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000802
803 // If this class member has an explicit visibility attribute, the only
804 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000805 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000806 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000807 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000808 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000809
John McCall5f46c482013-02-21 23:42:58 +0000810 LinkageInfo classLV =
811 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
John McCall8823c652010-08-13 08:35:10 +0000812 // If the class already has unique-external linkage, we can't improve.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000813 if (classLV.getLinkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000814 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000815
Rafael Espindolae6190db2013-05-28 02:22:10 +0000816 if (!isExternallyVisible(classLV.getLinkage()))
817 return LinkageInfo::none();
818
819
John McCall5f46c482013-02-21 23:42:58 +0000820 // Otherwise, don't merge in classLV yet, because in certain cases
821 // we need to completely ignore the visibility from it.
822
823 // Specifically, if this decl exists and has an explicit attribute.
824 const NamedDecl *explicitSpecSuppressor = 0;
825
John McCall8823c652010-08-13 08:35:10 +0000826 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000827 // If the type of the function uses a type with unique-external
828 // linkage, it's not legally usable from outside this translation unit.
Faisal Valid2598e92013-10-08 04:15:04 +0000829 // But only look at the type-as-written. If this function has an auto-deduced
830 // return type, we can't compute the linkage of that type because it could
831 // require looking at the linkage of this function, and we don't need this
832 // for correctness because the type is not part of the function's
833 // signature.
834 // FIXME: This is a hack. We should be able to solve this circularity and the
835 // one in getLVForNamespaceScopeDecl for Functions some other way.
836 {
837 QualType TypeAsWritten = MD->getType();
838 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
839 TypeAsWritten = TSI->getType();
840 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
841 return LinkageInfo::uniqueExternal();
842 }
John McCall457a04e2010-10-22 21:05:15 +0000843 // If this is a method template specialization, use the linkage for
844 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000845 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000846 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000847 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000848 if (spec->isExplicitSpecialization()) {
849 explicitSpecSuppressor = MD;
850 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
851 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
852 }
853 } else if (isExplicitMemberSpecialization(MD)) {
854 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000855 }
John McCall457a04e2010-10-22 21:05:15 +0000856
John McCall37bb6c92010-10-29 22:22:43 +0000857 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCallb8c604a2011-06-27 23:06:04 +0000858 if (const ClassTemplateSpecializationDecl *spec
John McCall37bb6c92010-10-29 22:22:43 +0000859 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000860 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000861 if (spec->isExplicitSpecialization()) {
862 explicitSpecSuppressor = spec;
863 } else {
864 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
865 if (isExplicitMemberSpecialization(temp)) {
866 explicitSpecSuppressor = temp->getTemplatedDecl();
867 }
868 }
869 } else if (isExplicitMemberSpecialization(RD)) {
870 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000871 }
872
John McCall37bb6c92010-10-29 22:22:43 +0000873 // Static data members.
874 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCall36cd5cc2010-10-30 09:18:49 +0000875 // Modify the variable's linkage by its type, but ignore the
876 // type's visibility unless it's a definition.
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000877 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000878 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
879 LV.mergeVisibility(typeLV);
880 LV.mergeExternalVisibility(typeLV);
John McCall5f46c482013-02-21 23:42:58 +0000881
882 if (isExplicitMemberSpecialization(VD)) {
883 explicitSpecSuppressor = VD;
884 }
John McCalldf25c432013-02-16 00:17:33 +0000885
886 // Template members.
887 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
888 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +0000889 (!LV.isVisibilityExplicit() &&
890 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000891 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000892 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000893 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000894 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +0000895
896 if (const RedeclarableTemplateDecl *redeclTemp =
897 dyn_cast<RedeclarableTemplateDecl>(temp)) {
898 if (isExplicitMemberSpecialization(redeclTemp)) {
899 explicitSpecSuppressor = temp->getTemplatedDecl();
900 }
901 }
John McCall37bb6c92010-10-29 22:22:43 +0000902 }
903
John McCall5f46c482013-02-21 23:42:58 +0000904 // We should never be looking for an attribute directly on a template.
905 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
906
907 // If this member is an explicit member specialization, and it has
908 // an explicit attribute, ignore visibility from the parent.
909 bool considerClassVisibility = true;
910 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +0000911 // optimization: hasDVA() is true only with explicit visibility.
912 LV.isVisibilityExplicit() &&
913 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +0000914 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
915 considerClassVisibility = false;
916 }
917
918 // Finally, merge in information from the class.
919 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +0000920 return LV;
John McCall8823c652010-08-13 08:35:10 +0000921}
922
David Blaikie68e081d2011-12-20 02:48:34 +0000923void NamedDecl::anchor() { }
924
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000925static LinkageInfo computeLVForDecl(const NamedDecl *D,
926 LVComputationKind computation);
927
Rafael Espindola0e0d0092013-03-14 03:07:35 +0000928bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +0000929 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +0000930 return true;
John McCalld396b972011-02-08 19:01:05 +0000931
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000932 return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
Rafael Espindola50df3a02013-05-25 17:16:20 +0000933 getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +0000934}
935
Rafael Espindola3ae00052013-05-13 00:12:11 +0000936Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +0000937 // We don't care about visibility here, so ask for the cheapest
938 // possible visibility analysis.
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000939 return getLVForDecl(this, LVForLinkageOnly).getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +0000940}
941
John McCallc273f242010-10-30 11:50:40 +0000942LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCalldf25c432013-02-16 00:17:33 +0000943 LVComputationKind computation =
944 (usesTypeVisibility(this) ? LVForType : LVForValue);
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000945 return getLVForDecl(this, computation);
John McCall033caa52010-10-29 00:29:13 +0000946}
Ted Kremenek926d8602010-04-20 23:15:35 +0000947
Rafael Espindola9ad61122013-11-26 16:09:08 +0000948static Optional<Visibility>
949getExplicitVisibilityAux(const NamedDecl *ND,
950 NamedDecl::ExplicitVisibilityKind kind,
951 bool IsMostRecent) {
952 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
953
Rafael Espindola3a52c442013-02-26 19:33:14 +0000954 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +0000955 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +0000956 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000957
Rafael Espindola3a52c442013-02-26 19:33:14 +0000958 // If this is a member class of a specialization of a class template
959 // and the corresponding decl has explicit visibility, use that.
Rafael Espindola9ad61122013-11-26 16:09:08 +0000960 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +0000961 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
962 if (InstantiatedFrom)
963 return getVisibilityOf(InstantiatedFrom, kind);
964 }
965
966 // If there wasn't explicit visibility there, and this is a
967 // specialization of a class template, check for visibility
968 // on the pattern.
969 if (const ClassTemplateSpecializationDecl *spec
Rafael Espindola9ad61122013-11-26 16:09:08 +0000970 = dyn_cast<ClassTemplateSpecializationDecl>(ND))
Rafael Espindola3a52c442013-02-26 19:33:14 +0000971 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
972 kind);
973
974 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +0000975 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +0000976 const NamedDecl *MostRecent = ND->getMostRecentDecl();
977 if (MostRecent != ND)
978 return getExplicitVisibilityAux(MostRecent, kind, true);
979 }
Rafael Espindola3a52c442013-02-26 19:33:14 +0000980
Rafael Espindola9ad61122013-11-26 16:09:08 +0000981 if (const VarDecl *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +0000982 if (Var->isStaticDataMember()) {
983 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
984 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +0000985 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +0000986 }
987
David Blaikie7a30dc52013-02-21 01:47:18 +0000988 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +0000989 }
Rafael Espindola3a52c442013-02-26 19:33:14 +0000990 // Also handle function template specializations.
Rafael Espindola9ad61122013-11-26 16:09:08 +0000991 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000992 // If the function is a specialization of a template with an
993 // explicit visibility attribute, use that.
994 if (FunctionTemplateSpecializationInfo *templateInfo
995 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +0000996 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
997 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000998
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000999 // If the function is a member of a specialization of a class template
1000 // and the corresponding decl has explicit visibility, use that.
1001 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1002 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001003 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001004
David Blaikie7a30dc52013-02-21 01:47:18 +00001005 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001006 }
1007
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001008 // The visibility of a template is stored in the templated decl.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001009 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001010 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001011
David Blaikie7a30dc52013-02-21 01:47:18 +00001012 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001013}
1014
Rafael Espindola9ad61122013-11-26 16:09:08 +00001015Optional<Visibility>
1016NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1017 return getExplicitVisibilityAux(this, kind, false);
1018}
1019
Eli Friedman7e346a82013-07-01 20:22:57 +00001020static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
1021 LVComputationKind computation) {
1022 // This lambda has its linkage/visibility determined by its owner.
1023 if (ContextDecl) {
1024 if (isa<ParmVarDecl>(ContextDecl))
1025 DC = ContextDecl->getDeclContext()->getRedeclContext();
1026 else
1027 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1028 }
Faisal Vali98b8e182013-09-29 20:27:06 +00001029
Eli Friedman7e346a82013-07-01 20:22:57 +00001030 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
1031 return getLVForDecl(ND, computation);
Faisal Vali98b8e182013-09-29 20:27:06 +00001032
Eli Friedman7e346a82013-07-01 20:22:57 +00001033 return LinkageInfo::external();
1034}
1035
John McCalldf25c432013-02-16 00:17:33 +00001036static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1037 LVComputationKind computation) {
1038 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1039 if (Function->isInAnonymousNamespace() &&
Rafael Espindola593537a2013-05-05 20:15:21 +00001040 !Function->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001041 return LinkageInfo::uniqueExternal();
1042
1043 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001044 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCalldf25c432013-02-16 00:17:33 +00001045 return LinkageInfo::internal();
1046
1047 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001048 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001049 if (Optional<Visibility> Vis =
1050 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001051 LV.mergeVisibility(*Vis, true);
1052 }
1053
1054 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1055 // merging storage classes and visibility attributes, so we don't have to
1056 // look at previous decls in here.
1057
1058 return LV;
1059 }
1060
1061 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001062 if (Var->hasExternalStorage()) {
Rafael Espindola593537a2013-05-05 20:15:21 +00001063 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001064 return LinkageInfo::uniqueExternal();
1065
John McCalldf25c432013-02-16 00:17:33 +00001066 LinkageInfo LV;
1067 if (Var->getStorageClass() == SC_PrivateExtern)
1068 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001069 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001070 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001071 LV.mergeVisibility(*Vis, true);
1072 }
1073
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001074 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1075 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1076 if (PrevLV.getLinkage())
1077 LV.setLinkage(PrevLV.getLinkage());
1078 LV.mergeVisibility(PrevLV);
1079 }
1080
John McCalldf25c432013-02-16 00:17:33 +00001081 return LV;
1082 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001083
1084 if (!Var->isStaticLocal())
1085 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001086 }
1087
Rafael Espindolaa4184182013-06-17 20:04:51 +00001088 ASTContext &Context = D->getASTContext();
1089 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001090 return LinkageInfo::none();
1091
Eli Friedman7e346a82013-07-01 20:22:57 +00001092 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1093 if (!OuterD)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001094 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001095
Eli Friedman7e346a82013-07-01 20:22:57 +00001096 LinkageInfo LV;
1097 if (const BlockDecl *BD = dyn_cast<BlockDecl>(OuterD)) {
1098 if (!BD->getBlockManglingNumber())
1099 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001100
Eli Friedman7e346a82013-07-01 20:22:57 +00001101 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1102 BD->getBlockManglingContextDecl(), computation);
1103 } else {
1104 const FunctionDecl *FD = cast<FunctionDecl>(OuterD);
1105 if (!FD->isInlined() &&
1106 FD->getTemplateSpecializationKind() == TSK_Undeclared)
1107 return LinkageInfo::none();
1108
1109 LV = getLVForDecl(FD, computation);
1110 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001111 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001112 return LinkageInfo::none();
1113 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1114 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001115}
1116
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001117static inline const CXXRecordDecl*
1118getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1119 const CXXRecordDecl *Ret = Record;
1120 while (Record && Record->isLambda()) {
1121 Ret = Record;
1122 if (!Record->getParent()) break;
1123 // Get the Containing Class of this Lambda Class
1124 Record = dyn_cast_or_null<CXXRecordDecl>(
1125 Record->getParent()->getParent());
1126 }
1127 return Ret;
1128}
1129
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001130static LinkageInfo computeLVForDecl(const NamedDecl *D,
1131 LVComputationKind computation) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001132 // Objective-C: treat all Objective-C declarations as having external
1133 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001134 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001135 default:
1136 break;
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001137 case Decl::ParmVar:
1138 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001139 case Decl::TemplateTemplateParm: // count these as external
1140 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001141 case Decl::ObjCAtDefsField:
1142 case Decl::ObjCCategory:
1143 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001144 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001145 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001146 case Decl::ObjCMethod:
1147 case Decl::ObjCProperty:
1148 case Decl::ObjCPropertyImpl:
1149 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +00001150 return LinkageInfo::external();
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001151
1152 case Decl::CXXRecord: {
1153 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1154 if (Record->isLambda()) {
1155 if (!Record->getLambdaManglingNumber()) {
1156 // This lambda has no mangling number, so it's internal.
1157 return LinkageInfo::internal();
1158 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001159
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001160 // This lambda has its linkage/visibility determined:
1161 // - either by the outermost lambda if that lambda has no mangling
1162 // number.
1163 // - or by the parent of the outer most lambda
1164 // This prevents infinite recursion in settings such as nested lambdas
1165 // used in NSDMI's, for e.g.
1166 // struct L {
1167 // int t{};
1168 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1169 // };
1170 const CXXRecordDecl *OuterMostLambda =
1171 getOutermostEnclosingLambda(Record);
1172 if (!OuterMostLambda->getLambdaManglingNumber())
1173 return LinkageInfo::internal();
1174
1175 return getLVForClosure(
1176 OuterMostLambda->getDeclContext()->getRedeclContext(),
1177 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001178 }
1179
1180 break;
1181 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001182 }
1183
Douglas Gregorf73b2822009-11-25 22:24:25 +00001184 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001185 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCalldf25c432013-02-16 00:17:33 +00001186 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001187
1188 // C++ [basic.link]p5:
1189 // In addition, a member function, static data member, a named
1190 // class or enumeration of class scope, or an unnamed class or
1191 // enumeration defined in a class-scope typedef declaration such
1192 // that the class or enumeration has the typedef name for linkage
1193 // purposes (7.1.3), has external linkage if the name of the class
1194 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001195 if (D->getDeclContext()->isRecord())
John McCalldf25c432013-02-16 00:17:33 +00001196 return getLVForClassMember(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001197
1198 // C++ [basic.link]p6:
1199 // The name of a function declared in block scope and the name of
1200 // an object declared by a block scope extern declaration have
1201 // linkage. If there is a visible declaration of an entity with
1202 // linkage having the same name and type, ignoring entities
1203 // declared outside the innermost enclosing namespace scope, the
1204 // block scope declaration declares that same entity and receives
1205 // the linkage of the previous declaration. If there is more than
1206 // one such matching entity, the program is ill-formed. Otherwise,
1207 // if no matching entity is found, the block scope entity receives
1208 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001209 if (D->getDeclContext()->isFunctionOrMethod())
1210 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001211
1212 // C++ [basic.link]p6:
1213 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001214 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001215}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001216
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001217namespace clang {
1218class LinkageComputer {
1219public:
1220 static LinkageInfo getLVForDecl(const NamedDecl *D,
1221 LVComputationKind computation) {
1222 if (computation == LVForLinkageOnly && D->hasCachedLinkage())
1223 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1224
1225 LinkageInfo LV = computeLVForDecl(D, computation);
1226 if (D->hasCachedLinkage())
1227 assert(D->getCachedLinkage() == LV.getLinkage());
1228
1229 D->setCachedLinkage(LV.getLinkage());
1230
1231#ifndef NDEBUG
1232 // In C (because of gnu inline) and in c++ with microsoft extensions an
1233 // static can follow an extern, so we can have two decls with different
1234 // linkages.
1235 const LangOptions &Opts = D->getASTContext().getLangOpts();
1236 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1237 return LV;
1238
1239 // We have just computed the linkage for this decl. By induction we know
1240 // that all other computed linkages match, check that the one we just
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001241 // computed also does.
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001242 NamedDecl *Old = NULL;
Aaron Ballman86c93902014-03-06 23:45:36 +00001243 for (auto I : D->redecls()) {
1244 NamedDecl *T = cast<NamedDecl>(I);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001245 if (T == D)
1246 continue;
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001247 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001248 Old = T;
1249 break;
1250 }
1251 }
1252 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1253#endif
1254
1255 return LV;
1256 }
1257};
1258}
1259
1260static LinkageInfo getLVForDecl(const NamedDecl *D,
1261 LVComputationKind computation) {
1262 return clang::LinkageComputer::getLVForDecl(D, computation);
1263}
1264
Douglas Gregor2ada0482009-02-04 17:27:36 +00001265std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001266 std::string QualName;
1267 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001268 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001269 return OS.str();
1270}
1271
1272void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1273 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1274}
1275
1276void NamedDecl::printQualifiedName(raw_ostream &OS,
1277 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001278 const DeclContext *Ctx = getDeclContext();
1279
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001280 if (Ctx->isFunctionOrMethod()) {
1281 printName(OS);
1282 return;
1283 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001284
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001285 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001286 ContextsTy Contexts;
1287
1288 // Collect contexts.
1289 while (Ctx && isa<NamedDecl>(Ctx)) {
1290 Contexts.push_back(Ctx);
1291 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001292 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001293
1294 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1295 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00001296 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001297 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001298 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001299 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00001300 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1301 TemplateArgs.data(),
1302 TemplateArgs.size(),
1303 P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001304 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Sam Weinig07d211e2009-12-24 23:15:03 +00001305 if (ND->isAnonymousNamespace())
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001306 OS << "<anonymous namespace>";
Sam Weinig07d211e2009-12-24 23:15:03 +00001307 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001308 OS << *ND;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001309 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1310 if (!RD->getIdentifier())
1311 OS << "<anonymous " << RD->getKindName() << '>';
1312 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001313 OS << *RD;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001314 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Sam Weinigb999f682009-12-28 03:19:38 +00001315 const FunctionProtoType *FT = 0;
1316 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001317 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001318
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001319 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001320 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001321 unsigned NumParams = FD->getNumParams();
1322 for (unsigned i = 0; i < NumParams; ++i) {
1323 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001324 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001325 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001326 }
1327
1328 if (FT->isVariadic()) {
1329 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001330 OS << ", ";
1331 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001332 }
1333 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001334 OS << ')';
1335 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001336 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001337 }
1338 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001339 }
1340
John McCalla2a3f7d2010-03-16 21:48:18 +00001341 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001342 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001343 else
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001344 OS << "<anonymous>";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001345}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001346
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001347void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1348 const PrintingPolicy &Policy,
1349 bool Qualified) const {
1350 if (Qualified)
1351 printQualifiedName(OS, Policy);
1352 else
1353 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001354}
1355
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001356bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001357 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1358
Douglas Gregor889ceb72009-02-03 19:21:40 +00001359 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1360 // We want to keep it, unless it nominates same namespace.
1361 if (getKind() == Decl::UsingDirective) {
Douglas Gregor12441b32011-02-25 16:33:46 +00001362 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1363 ->getOriginalNamespace() ==
1364 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1365 ->getOriginalNamespace();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001366 }
Mike Stump11289f42009-09-09 15:08:12 +00001367
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001368 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1369 // For function declarations, we keep track of redeclarations.
Douglas Gregorec9fd132012-01-14 16:38:05 +00001370 return FD->getPreviousDecl() == OldD;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001371
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001372 // For function templates, the underlying function declarations are linked.
1373 if (const FunctionTemplateDecl *FunctionTemplate
1374 = dyn_cast<FunctionTemplateDecl>(this))
1375 if (const FunctionTemplateDecl *OldFunctionTemplate
1376 = dyn_cast<FunctionTemplateDecl>(OldD))
1377 return FunctionTemplate->getTemplatedDecl()
1378 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001379
Steve Naroffc4173fa2009-02-22 19:35:57 +00001380 // For method declarations, we keep track of redeclarations.
1381 if (isa<ObjCMethodDecl>(this))
1382 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001383
John McCall9f3059a2009-10-09 21:13:30 +00001384 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1385 return true;
1386
John McCall3f746822009-11-17 05:59:44 +00001387 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1388 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1389 cast<UsingShadowDecl>(OldD)->getTargetDecl();
1390
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001391 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1392 ASTContext &Context = getASTContext();
1393 return Context.getCanonicalNestedNameSpecifier(
1394 cast<UsingDecl>(this)->getQualifier()) ==
1395 Context.getCanonicalNestedNameSpecifier(
1396 cast<UsingDecl>(OldD)->getQualifier());
1397 }
Argyrios Kyrtzidis4b520072010-11-04 08:48:52 +00001398
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001399 if (isa<UnresolvedUsingValueDecl>(this) &&
1400 isa<UnresolvedUsingValueDecl>(OldD)) {
1401 ASTContext &Context = getASTContext();
1402 return Context.getCanonicalNestedNameSpecifier(
1403 cast<UnresolvedUsingValueDecl>(this)->getQualifier()) ==
1404 Context.getCanonicalNestedNameSpecifier(
1405 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1406 }
1407
Douglas Gregorb59643b2012-01-03 23:26:26 +00001408 // A typedef of an Objective-C class type can replace an Objective-C class
1409 // declaration or definition, and vice versa.
1410 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1411 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1412 return true;
1413
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001414 // For non-function declarations, if the declarations are of the
1415 // same kind then this must be a redeclaration, or semantic analysis
1416 // would not have given us the new declaration.
1417 return this->getKind() == OldD->getKind();
1418}
1419
Douglas Gregoreddf4332009-02-24 20:03:32 +00001420bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001421 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001422}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001423
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001424NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001425 NamedDecl *ND = this;
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001426 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1427 ND = UD->getTargetDecl();
1428
1429 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1430 return AD->getClassInterface();
1431
1432 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001433}
1434
John McCalla8ae2222010-04-06 21:38:20 +00001435bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001436 if (!isCXXClassMember())
1437 return false;
1438
John McCalla8ae2222010-04-06 21:38:20 +00001439 const NamedDecl *D = this;
1440 if (isa<UsingShadowDecl>(D))
1441 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1442
John McCall5e77d762013-04-16 07:28:30 +00001443 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001444 return true;
Alp Tokera2794f92014-01-22 07:29:52 +00001445 if (const CXXMethodDecl *MD =
1446 dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1447 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001448 return false;
1449}
1450
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001451//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001452// DeclaratorDecl Implementation
1453//===----------------------------------------------------------------------===//
1454
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001455template <typename DeclT>
1456static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1457 if (decl->getNumTemplateParameterLists() > 0)
1458 return decl->getTemplateParameterList(0)->getTemplateLoc();
1459 else
1460 return decl->getInnerLocStart();
1461}
1462
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001463SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001464 TypeSourceInfo *TSI = getTypeSourceInfo();
1465 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001466 return SourceLocation();
1467}
1468
Douglas Gregor14454802011-02-25 02:25:35 +00001469void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1470 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001471 // Make sure the extended decl info is allocated.
1472 if (!hasExtInfo()) {
1473 // Save (non-extended) type source info pointer.
1474 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1475 // Allocate external info struct.
1476 DeclInfo = new (getASTContext()) ExtInfo;
1477 // Restore savedTInfo into (extended) decl info.
1478 getExtInfo()->TInfo = savedTInfo;
1479 }
1480 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001481 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001482 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001483 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001484 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001485 if (getExtInfo()->NumTemplParamLists == 0) {
1486 // Save type source info pointer.
1487 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1488 // Deallocate the extended decl info.
1489 getASTContext().Deallocate(getExtInfo());
1490 // Restore savedTInfo into (non-extended) decl info.
1491 DeclInfo = savedTInfo;
1492 }
1493 else
1494 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001495 }
1496 }
1497}
1498
Abramo Bagnara60804e12011-03-18 15:16:37 +00001499void
1500DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1501 unsigned NumTPLists,
1502 TemplateParameterList **TPLists) {
1503 assert(NumTPLists > 0);
1504 // Make sure the extended decl info is allocated.
1505 if (!hasExtInfo()) {
1506 // Save (non-extended) type source info pointer.
1507 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1508 // Allocate external info struct.
1509 DeclInfo = new (getASTContext()) ExtInfo;
1510 // Restore savedTInfo into (extended) decl info.
1511 getExtInfo()->TInfo = savedTInfo;
1512 }
1513 // Set the template parameter lists info.
1514 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1515}
1516
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001517SourceLocation DeclaratorDecl::getOuterLocStart() const {
1518 return getTemplateOrInnerLocStart(this);
1519}
1520
Abramo Bagnaraea947882011-03-08 16:41:52 +00001521namespace {
1522
1523// Helper function: returns true if QT is or contains a type
1524// having a postfix component.
1525bool typeIsPostfix(clang::QualType QT) {
1526 while (true) {
1527 const Type* T = QT.getTypePtr();
1528 switch (T->getTypeClass()) {
1529 default:
1530 return false;
1531 case Type::Pointer:
1532 QT = cast<PointerType>(T)->getPointeeType();
1533 break;
1534 case Type::BlockPointer:
1535 QT = cast<BlockPointerType>(T)->getPointeeType();
1536 break;
1537 case Type::MemberPointer:
1538 QT = cast<MemberPointerType>(T)->getPointeeType();
1539 break;
1540 case Type::LValueReference:
1541 case Type::RValueReference:
1542 QT = cast<ReferenceType>(T)->getPointeeType();
1543 break;
1544 case Type::PackExpansion:
1545 QT = cast<PackExpansionType>(T)->getPattern();
1546 break;
1547 case Type::Paren:
1548 case Type::ConstantArray:
1549 case Type::DependentSizedArray:
1550 case Type::IncompleteArray:
1551 case Type::VariableArray:
1552 case Type::FunctionProto:
1553 case Type::FunctionNoProto:
1554 return true;
1555 }
1556 }
1557}
1558
1559} // namespace
1560
1561SourceRange DeclaratorDecl::getSourceRange() const {
1562 SourceLocation RangeEnd = getLocation();
1563 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001564 // If the declaration has no name or the type extends past the name take the
1565 // end location of the type.
1566 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001567 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1568 }
1569 return SourceRange(getOuterLocStart(), RangeEnd);
1570}
1571
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001572void
Douglas Gregor20527e22010-06-15 17:44:38 +00001573QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1574 unsigned NumTPLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001575 TemplateParameterList **TPLists) {
1576 assert((NumTPLists == 0 || TPLists != 0) &&
1577 "Empty array of template parameters with positive size!");
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001578
1579 // Free previous template parameters (if any).
1580 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001581 Context.Deallocate(TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001582 TemplParamLists = 0;
1583 NumTemplParamLists = 0;
1584 }
1585 // Set info on matched template parameter lists (if any).
1586 if (NumTPLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001587 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001588 NumTemplParamLists = NumTPLists;
1589 for (unsigned i = NumTPLists; i-- > 0; )
1590 TemplParamLists[i] = TPLists[i];
1591 }
1592}
1593
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001594//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001595// VarDecl Implementation
1596//===----------------------------------------------------------------------===//
1597
Sebastian Redl833ef452010-01-26 22:01:41 +00001598const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1599 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001600 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001601 case SC_Auto: return "auto";
1602 case SC_Extern: return "extern";
1603 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1604 case SC_PrivateExtern: return "__private_extern__";
1605 case SC_Register: return "register";
1606 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001607 }
1608
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001609 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001610}
1611
Larisse Voufo39a1e502013-08-06 01:03:05 +00001612VarDecl::VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1613 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1614 TypeSourceInfo *TInfo, StorageClass SC)
1615 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), Init() {
1616 assert(sizeof(VarDeclBitfields) <= sizeof(unsigned));
1617 assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned));
1618 AllBits = 0;
1619 VarDeclBits.SClass = SC;
1620 // Everything else is implicitly initialized to false.
1621}
1622
Abramo Bagnaradff19302011-03-08 08:55:46 +00001623VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1624 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001625 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001626 StorageClass S) {
Richard Smithf7981722013-11-22 09:01:48 +00001627 return new (C, DC) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001628}
1629
Douglas Gregor72172e92012-01-05 21:55:30 +00001630VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00001631 return new (C, ID) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1632 QualType(), 0, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001633}
1634
Douglas Gregorbf62d642010-12-06 18:36:25 +00001635void VarDecl::setStorageClass(StorageClass SC) {
1636 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001637 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001638}
1639
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001640SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001641 if (const Expr *Init = getInit()) {
1642 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001643 // If Init is implicit, ignore its source range and fallback on
1644 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1645 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001646 return SourceRange(getOuterLocStart(), InitEnd);
1647 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001648 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001649}
1650
Rafael Espindola88510672013-01-04 21:18:45 +00001651template<typename T>
Rafael Espindolaf4187652013-02-14 01:18:37 +00001652static LanguageLinkage getLanguageLinkageTemplate(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001653 // C++ [dcl.link]p1: All function types, function names with external linkage,
1654 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001655 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001656 return NoLanguageLinkage;
1657
1658 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001659 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001660 ASTContext &Context = D.getASTContext();
1661 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001662 return CLanguageLinkage;
1663
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001664 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1665 // language linkage of the names of class members and the function type of
1666 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001667 const DeclContext *DC = D.getDeclContext();
1668 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001669 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001670
1671 // If the first decl is in an extern "C" context, any other redeclaration
1672 // will have C language linkage. If the first one is not in an extern "C"
1673 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00001674 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00001675 return CLanguageLinkage;
1676 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001677}
1678
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001679template<typename T>
1680static bool isExternCTemplate(const T &D) {
1681 // Since the context is ignored for class members, they can only have C++
1682 // language linkage or no language linkage.
1683 const DeclContext *DC = D.getDeclContext();
1684 if (DC->isRecord()) {
1685 assert(D.getASTContext().getLangOpts().CPlusPlus);
1686 return false;
1687 }
1688
1689 return D.getLanguageLinkage() == CLanguageLinkage;
1690}
1691
Rafael Espindolaf4187652013-02-14 01:18:37 +00001692LanguageLinkage VarDecl::getLanguageLinkage() const {
1693 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001694}
1695
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001696bool VarDecl::isExternC() const {
1697 return isExternCTemplate(*this);
1698}
1699
Rafael Espindola593537a2013-05-05 20:15:21 +00001700bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001701 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001702}
1703
1704bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001705 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001706}
1707
Rafael Espindola8db352d2013-10-17 15:37:26 +00001708VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00001709
Daniel Dunbar9d355812012-03-09 01:51:51 +00001710VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1711 ASTContext &C) const
1712{
Sebastian Redl35351a92010-01-31 22:27:38 +00001713 // C++ [basic.def]p2:
1714 // A declaration is a definition unless [...] it contains the 'extern'
1715 // specifier or a linkage-specification and neither an initializer [...],
1716 // it declares a static data member in a class declaration [...].
Richard Smith8809a0c2013-09-27 20:14:12 +00001717 // C++1y [temp.expl.spec]p15:
1718 // An explicit specialization of a static data member or an explicit
1719 // specialization of a static data member template is a definition if the
1720 // declaration includes an initializer; otherwise, it is a declaration.
1721 //
1722 // FIXME: How do you declare (but not define) a partial specialization of
1723 // a static data member template outside the containing class?
Sebastian Redl35351a92010-01-31 22:27:38 +00001724 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00001725 if (isOutOfLine() &&
1726 (hasInit() ||
1727 // If the first declaration is out-of-line, this may be an
1728 // instantiation of an out-of-line partial specialization of a variable
1729 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00001730 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00001731 ? getTemplateSpecializationKind() == TSK_Undeclared
1732 : getTemplateSpecializationKind() !=
1733 TSK_ExplicitSpecialization) ||
1734 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00001735 return Definition;
1736 else
1737 return DeclarationOnly;
1738 }
1739 // C99 6.7p5:
1740 // A definition of an identifier is a declaration for that identifier that
1741 // [...] causes storage to be reserved for that object.
1742 // Note: that applies for all non-file-scope objects.
1743 // C99 6.9.2p1:
1744 // If the declaration of an identifier for an object has file scope and an
1745 // initializer, the declaration is an external definition for the identifier
1746 if (hasInit())
1747 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00001748
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001749 if (hasAttr<AliasAttr>())
1750 return Definition;
1751
Richard Smith8809a0c2013-09-27 20:14:12 +00001752 // A variable template specialization (other than a static data member
1753 // template or an explicit specialization) is a declaration until we
1754 // instantiate its initializer.
1755 if (isa<VarTemplateSpecializationDecl>(this) &&
1756 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1757 return DeclarationOnly;
1758
Sebastian Redl35351a92010-01-31 22:27:38 +00001759 if (hasExternalStorage())
1760 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00001761
Rafael Espindolabff59562013-04-25 12:11:36 +00001762 // [dcl.link] p7:
1763 // A declaration directly contained in a linkage-specification is treated
1764 // as if it contains the extern specifier for the purpose of determining
1765 // the linkage of the declared name and whether it is a definition.
Richard Smith03c05032014-02-17 23:34:47 +00001766 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00001767 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00001768
Sebastian Redl35351a92010-01-31 22:27:38 +00001769 // C99 6.9.2p2:
1770 // A declaration of an object that has file scope without an initializer,
1771 // and without a storage class specifier or the scs 'static', constitutes
1772 // a tentative definition.
1773 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001774 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00001775 return TentativeDefinition;
1776
1777 // What's left is (in C, block-scope) declarations without initializers or
1778 // external storage. These are definitions.
1779 return Definition;
1780}
1781
Sebastian Redl35351a92010-01-31 22:27:38 +00001782VarDecl *VarDecl::getActingDefinition() {
1783 DefinitionKind Kind = isThisDeclarationADefinition();
1784 if (Kind != TentativeDefinition)
1785 return 0;
1786
Chris Lattner48eb14d2010-06-14 18:31:46 +00001787 VarDecl *LastTentative = 0;
Rafael Espindola8db352d2013-10-17 15:37:26 +00001788 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001789 for (auto I : First->redecls()) {
1790 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00001791 if (Kind == Definition)
1792 return 0;
1793 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00001794 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00001795 }
1796 return LastTentative;
1797}
1798
Daniel Dunbar9d355812012-03-09 01:51:51 +00001799VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001800 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001801 for (auto I : First->redecls()) {
1802 if (I->isThisDeclarationADefinition(C) == Definition)
1803 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00001804 }
1805 return 0;
1806}
1807
Daniel Dunbar9d355812012-03-09 01:51:51 +00001808VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00001809 DefinitionKind Kind = DeclarationOnly;
1810
Rafael Espindola8db352d2013-10-17 15:37:26 +00001811 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001812 for (auto I : First->redecls()) {
1813 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001814 if (Kind == Definition)
1815 break;
1816 }
John McCall37bb6c92010-10-29 22:22:43 +00001817
1818 return Kind;
1819}
1820
Sebastian Redl5ca79842010-02-01 20:16:42 +00001821const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00001822 for (auto I : redecls()) {
1823 if (auto Expr = I->getInit()) {
1824 D = I;
1825 return Expr;
1826 }
Sebastian Redl833ef452010-01-26 22:01:41 +00001827 }
1828 return 0;
1829}
1830
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001831bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00001832 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001833 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001834
1835 if (!isStaticDataMember())
1836 return false;
1837
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001838 // If this static data member was instantiated from a static data member of
1839 // a class template, check whether that static data member was defined
1840 // out-of-line.
1841 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1842 return VD->isOutOfLine();
1843
1844 return false;
1845}
1846
Douglas Gregor1d957a32009-10-27 18:42:08 +00001847VarDecl *VarDecl::getOutOfLineDefinition() {
1848 if (!isStaticDataMember())
1849 return 0;
1850
Aaron Ballman86c93902014-03-06 23:45:36 +00001851 for (auto RD : redecls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00001852 if (RD->getLexicalDeclContext()->isFileContext())
Aaron Ballman86c93902014-03-06 23:45:36 +00001853 return RD;
Douglas Gregor1d957a32009-10-27 18:42:08 +00001854 }
1855
1856 return 0;
1857}
1858
Douglas Gregord5058122010-02-11 01:19:42 +00001859void VarDecl::setInit(Expr *I) {
Sebastian Redl833ef452010-01-26 22:01:41 +00001860 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1861 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00001862 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00001863 }
1864
1865 Init = I;
1866}
1867
Daniel Dunbar9d355812012-03-09 01:51:51 +00001868bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001869 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00001870
Richard Smith35ecb362012-03-02 04:14:40 +00001871 if (!Lang.CPlusPlus)
1872 return false;
1873
1874 // In C++11, any variable of reference type can be used in a constant
1875 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001876 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00001877 return true;
1878
1879 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00001880 // not require the variable to be non-volatile, but we consider this to be a
1881 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00001882 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00001883 return false;
1884
1885 // In C++, const, non-volatile variables of integral or enumeration types
1886 // can be used in constant expressions.
1887 if (getType()->isIntegralOrEnumerationType())
1888 return true;
1889
Richard Smith35ecb362012-03-02 04:14:40 +00001890 // Additionally, in C++11, non-volatile constexpr variables can be used in
1891 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001892 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00001893}
1894
Richard Smithd0b4dd62011-12-19 06:19:21 +00001895/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1896/// form, which contains extra information on the evaluated value of the
1897/// initializer.
1898EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1899 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1900 if (!Eval) {
1901 Stmt *S = Init.get<Stmt *>();
Manuel Klimeka7328992013-06-03 13:51:33 +00001902 // Note: EvaluatedStmt contains an APValue, which usually holds
1903 // resources not allocated from the ASTContext. We need to do some
1904 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
1905 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00001906 Eval = new (getASTContext()) EvaluatedStmt;
1907 Eval->Value = S;
1908 Init = Eval;
1909 }
1910 return Eval;
1911}
1912
Richard Smithdafff942012-01-14 04:30:29 +00001913APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001914 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00001915 return evaluateValue(Notes);
1916}
1917
Manuel Klimeka7328992013-06-03 13:51:33 +00001918namespace {
1919// Destroy an APValue that was allocated in an ASTContext.
1920void DestroyAPValue(void* UntypedValue) {
1921 static_cast<APValue*>(UntypedValue)->~APValue();
1922}
1923} // namespace
1924
Richard Smithdafff942012-01-14 04:30:29 +00001925APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001926 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001927 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1928
1929 // We only produce notes indicating why an initializer is non-constant the
1930 // first time it is evaluated. FIXME: The notes won't always be emitted the
1931 // first time we try evaluation, so might not be produced at all.
1932 if (Eval->WasEvaluated)
Richard Smithdafff942012-01-14 04:30:29 +00001933 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001934
1935 const Expr *Init = cast<Expr>(Eval->Value);
1936 assert(!Init->isValueDependent());
1937
1938 if (Eval->IsEvaluating) {
1939 // FIXME: Produce a diagnostic for self-initialization.
1940 Eval->CheckedICE = true;
1941 Eval->IsICE = false;
Richard Smithdafff942012-01-14 04:30:29 +00001942 return 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001943 }
1944
1945 Eval->IsEvaluating = true;
1946
1947 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1948 this, Notes);
1949
Manuel Klimeka7328992013-06-03 13:51:33 +00001950 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
1951 // or that it's empty (so that there's nothing to clean up) if evaluation
1952 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00001953 if (!Result)
1954 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00001955 else if (Eval->Evaluated.needsCleanup())
1956 getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001957
1958 Eval->IsEvaluating = false;
1959 Eval->WasEvaluated = true;
1960
1961 // In C++11, we have determined whether the initializer was a constant
1962 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001963 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001964 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00001965 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00001966 }
1967
Richard Smithdafff942012-01-14 04:30:29 +00001968 return Result ? &Eval->Evaluated : 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001969}
1970
1971bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00001972 // Initializers of weak variables are never ICEs.
1973 if (isWeak())
1974 return false;
1975
Richard Smithd0b4dd62011-12-19 06:19:21 +00001976 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1977 if (Eval->CheckedICE)
1978 // We have already checked whether this subexpression is an
1979 // integral constant expression.
1980 return Eval->IsICE;
1981
1982 const Expr *Init = cast<Expr>(Eval->Value);
1983 assert(!Init->isValueDependent());
1984
1985 // In C++11, evaluate the initializer to check whether it's a constant
1986 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001987 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001988 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001989 evaluateValue(Notes);
1990 return Eval->IsICE;
1991 }
1992
1993 // It's an ICE whether or not the definition we found is
1994 // out-of-line. See DR 721 and the discussion in Clang PR
1995 // 6206 for details.
1996
1997 if (Eval->CheckingICE)
1998 return false;
1999 Eval->CheckingICE = true;
2000
2001 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2002 Eval->CheckingICE = false;
2003 Eval->CheckedICE = true;
2004 return Eval->IsICE;
2005}
2006
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002007VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002008 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002009 return cast<VarDecl>(MSI->getInstantiatedFrom());
2010
2011 return 0;
2012}
2013
Douglas Gregor3c74d412009-10-14 20:14:33 +00002014TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002015 if (const VarTemplateSpecializationDecl *Spec =
2016 dyn_cast<VarTemplateSpecializationDecl>(this))
2017 return Spec->getSpecializationKind();
2018
Sebastian Redl35351a92010-01-31 22:27:38 +00002019 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002020 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002021
Douglas Gregor86d142a2009-10-08 07:24:58 +00002022 return TSK_Undeclared;
2023}
2024
Richard Smith8809a0c2013-09-27 20:14:12 +00002025SourceLocation VarDecl::getPointOfInstantiation() const {
2026 if (const VarTemplateSpecializationDecl *Spec =
2027 dyn_cast<VarTemplateSpecializationDecl>(this))
2028 return Spec->getPointOfInstantiation();
2029
2030 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2031 return MSI->getPointOfInstantiation();
2032
2033 return SourceLocation();
2034}
2035
Larisse Voufo39a1e502013-08-06 01:03:05 +00002036VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2037 return getASTContext().getTemplateOrSpecializationInfo(this)
2038 .dyn_cast<VarTemplateDecl *>();
2039}
2040
2041void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2042 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2043}
2044
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002045MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002046 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002047 // FIXME: Remove ?
2048 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2049 return getASTContext().getTemplateOrSpecializationInfo(this)
2050 .dyn_cast<MemberSpecializationInfo *>();
Richard Smithb71782b2013-08-01 04:12:04 +00002051 return 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002052}
2053
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002054void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2055 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002056 assert((isa<VarTemplateSpecializationDecl>(this) ||
2057 getMemberSpecializationInfo()) &&
2058 "not a variable or static data member template specialization");
2059
Larisse Voufo39a1e502013-08-06 01:03:05 +00002060 if (VarTemplateSpecializationDecl *Spec =
2061 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2062 Spec->setSpecializationKind(TSK);
2063 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2064 Spec->getPointOfInstantiation().isInvalid())
2065 Spec->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002066 }
2067
2068 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2069 MSI->setTemplateSpecializationKind(TSK);
2070 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2071 MSI->getPointOfInstantiation().isInvalid())
2072 MSI->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002073 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002074}
2075
2076void
2077VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2078 TemplateSpecializationKind TSK) {
2079 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2080 "Previous template or instantiation?");
2081 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002082}
2083
Sebastian Redl833ef452010-01-26 22:01:41 +00002084//===----------------------------------------------------------------------===//
2085// ParmVarDecl Implementation
2086//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002087
Sebastian Redl833ef452010-01-26 22:01:41 +00002088ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002089 SourceLocation StartLoc,
2090 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002091 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002092 StorageClass S, Expr *DefArg) {
Richard Smithf7981722013-11-22 09:01:48 +00002093 return new (C, DC) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
2094 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002095}
2096
Reid Kleckner8a365022013-06-24 17:51:48 +00002097QualType ParmVarDecl::getOriginalType() const {
2098 TypeSourceInfo *TSI = getTypeSourceInfo();
2099 QualType T = TSI ? TSI->getType() : getType();
2100 if (const DecayedType *DT = dyn_cast<DecayedType>(T))
2101 return DT->getOriginalType();
2102 return T;
2103}
2104
Douglas Gregor72172e92012-01-05 21:55:30 +00002105ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00002106 return new (C, ID) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
2107 0, QualType(), 0, SC_None, 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00002108}
2109
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002110SourceRange ParmVarDecl::getSourceRange() const {
2111 if (!hasInheritedDefaultArg()) {
2112 SourceRange ArgRange = getDefaultArgRange();
2113 if (ArgRange.isValid())
2114 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2115 }
2116
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002117 // DeclaratorDecl considers the range of postfix types as overlapping with the
2118 // declaration name, but this is not the case with parameters in ObjC methods.
2119 if (isa<ObjCMethodDecl>(getDeclContext()))
2120 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2121
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002122 return DeclaratorDecl::getSourceRange();
2123}
2124
Sebastian Redl833ef452010-01-26 22:01:41 +00002125Expr *ParmVarDecl::getDefaultArg() {
2126 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2127 assert(!hasUninstantiatedDefaultArg() &&
2128 "Default argument is not yet instantiated!");
2129
2130 Expr *Arg = getInit();
John McCall5d413782010-12-06 08:20:24 +00002131 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002132 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002133
Sebastian Redl833ef452010-01-26 22:01:41 +00002134 return Arg;
2135}
2136
Sebastian Redl833ef452010-01-26 22:01:41 +00002137SourceRange ParmVarDecl::getDefaultArgRange() const {
2138 if (const Expr *E = getInit())
2139 return E->getSourceRange();
2140
2141 if (hasUninstantiatedDefaultArg())
2142 return getUninstantiatedDefaultArg()->getSourceRange();
2143
2144 return SourceRange();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002145}
2146
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00002147bool ParmVarDecl::isParameterPack() const {
2148 return isa<PackExpansionType>(getType());
2149}
2150
Ted Kremenek540017e2011-10-06 05:00:56 +00002151void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2152 getASTContext().setParameterIndex(this, parameterIndex);
2153 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2154}
2155
2156unsigned ParmVarDecl::getParameterIndexLarge() const {
2157 return getASTContext().getParameterIndex(this);
2158}
2159
Nuno Lopes394ec982008-12-17 23:39:55 +00002160//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002161// FunctionDecl Implementation
2162//===----------------------------------------------------------------------===//
2163
Benjamin Kramer9170e912013-02-22 15:46:01 +00002164void FunctionDecl::getNameForDiagnostic(
2165 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2166 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002167 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2168 if (TemplateArgs)
Benjamin Kramer9170e912013-02-22 15:46:01 +00002169 TemplateSpecializationType::PrintTemplateArgumentList(
2170 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002171}
2172
Ted Kremenek186a0742010-04-29 16:49:01 +00002173bool FunctionDecl::isVariadic() const {
2174 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
2175 return FT->isVariadic();
2176 return false;
2177}
2178
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002179bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002180 for (auto I : redecls()) {
Francois Pichet1c229c02011-04-22 22:18:13 +00002181 if (I->Body || I->IsLateTemplateParsed) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002182 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002183 return true;
2184 }
2185 }
2186
2187 return false;
2188}
2189
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002190bool FunctionDecl::hasTrivialBody() const
2191{
2192 Stmt *S = getBody();
2193 if (!S) {
2194 // Since we don't have a body for this function, we don't know if it's
2195 // trivial or not.
2196 return false;
2197 }
2198
2199 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2200 return true;
2201 return false;
2202}
2203
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002204bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002205 for (auto I : redecls()) {
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002206 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
2207 I->hasAttr<AliasAttr>()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002208 Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002209 return true;
2210 }
2211 }
2212
2213 return false;
2214}
2215
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002216Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002217 if (!hasBody(Definition))
2218 return 0;
2219
2220 if (Definition->Body)
2221 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002222
2223 return 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002224}
2225
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002226void FunctionDecl::setBody(Stmt *B) {
2227 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002228 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002229 EndRangeLoc = B->getLocEnd();
2230}
2231
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002232void FunctionDecl::setPure(bool P) {
2233 IsPure = P;
2234 if (P)
2235 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2236 Parent->markedVirtualFunctionPure();
2237}
2238
Richard Smith8d0dc312013-07-21 23:12:18 +00002239template<std::size_t Len>
2240static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2241 IdentifierInfo *II = ND->getIdentifier();
2242 return II && II->isStr(Str);
2243}
2244
Douglas Gregor16618f22009-09-12 00:17:51 +00002245bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002246 const TranslationUnitDecl *tunit =
2247 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2248 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002249 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002250 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002251}
2252
David Majnemerc729b0b2013-09-16 22:44:20 +00002253bool FunctionDecl::isMSVCRTEntryPoint() const {
2254 const TranslationUnitDecl *TUnit =
2255 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2256 if (!TUnit)
2257 return false;
2258
2259 // Even though we aren't really targeting MSVCRT if we are freestanding,
2260 // semantic analysis for these functions remains the same.
2261
2262 // MSVCRT entry points only exist on MSVCRT targets.
2263 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2264 return false;
2265
2266 // Nameless functions like constructors cannot be entry points.
2267 if (!getIdentifier())
2268 return false;
2269
2270 return llvm::StringSwitch<bool>(getName())
2271 .Cases("main", // an ANSI console app
2272 "wmain", // a Unicode console App
2273 "WinMain", // an ANSI GUI app
2274 "wWinMain", // a Unicode GUI app
2275 "DllMain", // a DLL
2276 true)
2277 .Default(false);
2278}
2279
John McCall53ffd372011-05-15 17:49:20 +00002280bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2281 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2282 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2283 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2284 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2285 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2286
Richard Smithf6004412014-01-19 23:25:37 +00002287 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2288 return false;
John McCall53ffd372011-05-15 17:49:20 +00002289
2290 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002291 if (proto->getNumParams() != 2 || proto->isVariadic())
2292 return false;
John McCall53ffd372011-05-15 17:49:20 +00002293
2294 ASTContext &Context =
2295 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2296 ->getASTContext();
2297
2298 // The result type and first argument type are constant across all
2299 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002300 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002301}
2302
Richard Smith8d0dc312013-07-21 23:12:18 +00002303static bool isNamespaceStd(const DeclContext *DC) {
2304 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC->getRedeclContext());
2305 return ND && isNamed(ND, "std") &&
2306 ND->getParent()->getRedeclContext()->isTranslationUnit();
2307}
2308
2309bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2310 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2311 return false;
2312 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2313 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2314 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2315 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2316 return false;
2317
2318 if (isa<CXXRecordDecl>(getDeclContext()))
2319 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002320
2321 // This can only fail for an invalid 'operator new' declaration.
2322 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2323 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002324
2325 const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002326 if (FPT->getNumParams() > 2 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002327 return false;
2328
2329 // If this is a single-parameter function, it must be a replaceable global
2330 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002331 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002332 return true;
2333
2334 // Otherwise, we're looking for a second parameter whose type is
Richard Smith1cdec012013-09-29 04:40:38 +00002335 // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
Alp Toker9cacbab2014-01-20 20:26:09 +00002336 QualType Ty = FPT->getParamType(1);
Richard Smith1cdec012013-09-29 04:40:38 +00002337 ASTContext &Ctx = getASTContext();
Richard Smithb47c36f2013-11-05 09:12:18 +00002338 if (Ctx.getLangOpts().SizedDeallocation &&
2339 Ctx.hasSameType(Ty, Ctx.getSizeType()))
Richard Smith1cdec012013-09-29 04:40:38 +00002340 return true;
Richard Smith8d0dc312013-07-21 23:12:18 +00002341 if (!Ty->isReferenceType())
2342 return false;
2343 Ty = Ty->getPointeeType();
2344 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2345 return false;
2346 // FIXME: Recognise nothrow_t in an inline namespace inside std?
2347 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2348 return RD && isNamed(RD, "nothrow_t") && isNamespaceStd(RD->getDeclContext());
2349}
2350
Richard Smithb47c36f2013-11-05 09:12:18 +00002351FunctionDecl *
2352FunctionDecl::getCorrespondingUnsizedGlobalDeallocationFunction() const {
2353 ASTContext &Ctx = getASTContext();
2354 if (!Ctx.getLangOpts().SizedDeallocation)
2355 return 0;
2356
2357 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2358 return 0;
2359 if (getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2360 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2361 return 0;
2362 if (isa<CXXRecordDecl>(getDeclContext()))
2363 return 0;
Richard Smithf6004412014-01-19 23:25:37 +00002364
2365 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2366 return 0;
Richard Smithb47c36f2013-11-05 09:12:18 +00002367
2368 if (getNumParams() != 2 || isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00002369 !Ctx.hasSameType(getType()->castAs<FunctionProtoType>()->getParamType(1),
Richard Smithb47c36f2013-11-05 09:12:18 +00002370 Ctx.getSizeType()))
2371 return 0;
2372
2373 // This is a sized deallocation function. Find the corresponding unsized
2374 // deallocation function.
2375 lookup_const_result R = getDeclContext()->lookup(getDeclName());
2376 for (lookup_const_result::iterator RI = R.begin(), RE = R.end(); RI != RE;
2377 ++RI)
2378 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*RI))
2379 if (FD->getNumParams() == 1 && !FD->isVariadic())
2380 return FD;
2381 return 0;
2382}
2383
Rafael Espindolaf4187652013-02-14 01:18:37 +00002384LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Rafael Espindolaf4187652013-02-14 01:18:37 +00002385 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002386}
2387
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002388bool FunctionDecl::isExternC() const {
2389 return isExternCTemplate(*this);
2390}
2391
Rafael Espindola593537a2013-05-05 20:15:21 +00002392bool FunctionDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002393 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002394}
2395
2396bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002397 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002398}
2399
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002400bool FunctionDecl::isGlobal() const {
2401 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2402 return Method->isStatic();
2403
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002404 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002405 return false;
2406
Mike Stump11289f42009-09-09 15:08:12 +00002407 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002408 DC->isNamespace();
2409 DC = DC->getParent()) {
2410 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2411 if (!Namespace->getDeclName())
2412 return false;
2413 break;
2414 }
2415 }
2416
2417 return true;
2418}
2419
Richard Smith10876ef2013-01-17 01:30:42 +00002420bool FunctionDecl::isNoReturn() const {
2421 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
Richard Smithdebc59d2013-01-30 05:45:05 +00002422 hasAttr<C11NoReturnAttr>() ||
Richard Smith10876ef2013-01-17 01:30:42 +00002423 getType()->getAs<FunctionType>()->getNoReturnAttr();
2424}
2425
Sebastian Redl833ef452010-01-26 22:01:41 +00002426void
2427FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002428 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002429
2430 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2431 FunctionTemplateDecl *PrevFunTmpl
2432 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
2433 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00002434 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002435 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002436
Axel Naumannfbc7b982011-11-08 18:21:06 +00002437 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002438 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002439}
2440
2441const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002442 return getFirstDecl();
Sebastian Redl833ef452010-01-26 22:01:41 +00002443}
2444
Rafael Espindola8db352d2013-10-17 15:37:26 +00002445FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002446
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002447/// \brief Returns a value indicating whether this function
2448/// corresponds to a builtin function.
2449///
2450/// The function corresponds to a built-in function if it is
2451/// declared at translation scope or within an extern "C" block and
2452/// its name matches with the name of a builtin. The returned value
2453/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002454/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002455/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002456unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002457 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002458 return 0;
2459
2460 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002461 if (!BuiltinID)
2462 return 0;
2463
2464 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00002465 if (Context.getLangOpts().CPlusPlus) {
2466 const LinkageSpecDecl *LinkageDecl = dyn_cast<LinkageSpecDecl>(
2467 getFirstDecl()->getDeclContext());
2468 // In C++, the first declaration of a builtin is always inside an implicit
2469 // extern "C".
2470 // FIXME: A recognised library function may not be directly in an extern "C"
2471 // declaration, for instance "extern "C" { namespace std { decl } }".
2472 if (!LinkageDecl || LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
2473 return 0;
2474 }
2475
2476 // If the function is marked "overloadable", it has a different mangled name
2477 // and is not the C library function.
Aaron Ballman9ead1242013-12-19 02:39:40 +00002478 if (hasAttr<OverloadableAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00002479 return 0;
2480
Douglas Gregore711f702009-02-14 18:57:46 +00002481 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2482 return BuiltinID;
2483
2484 // This function has the name of a known C library
2485 // function. Determine whether it actually refers to the C library
2486 // function or whether it just has the same name.
2487
Douglas Gregora908e7f2009-02-17 03:23:10 +00002488 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002489 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002490 return 0;
2491
Warren Hunt445d83e2013-11-01 23:46:51 +00002492 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002493}
2494
2495
Chris Lattner47c0d002009-04-25 06:03:53 +00002496/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002497/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002498/// after it has been created.
2499unsigned FunctionDecl::getNumParams() const {
Reid Kleckner0503a872013-12-05 01:23:43 +00002500 const FunctionProtoType *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002501 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002502}
2503
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002504void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002505 ArrayRef<ParmVarDecl *> NewParamInfo) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002506 assert(ParamInfo == 0 && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002507 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002508
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002509 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002510 if (!NewParamInfo.empty()) {
2511 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2512 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002513 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002514}
Chris Lattner41943152007-01-25 04:52:46 +00002515
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002516void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
James Molloy6f8780b2012-02-29 10:24:19 +00002517 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2518
2519 if (!NewDecls.empty()) {
2520 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2521 std::copy(NewDecls.begin(), NewDecls.end(), A);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002522 DeclsInPrototypeScope = ArrayRef<NamedDecl *>(A, NewDecls.size());
James Molloy6f8780b2012-02-29 10:24:19 +00002523 }
2524}
2525
Chris Lattner58258242008-04-10 02:22:51 +00002526/// getMinRequiredArguments - Returns the minimum number of arguments
2527/// needed to call this function. This may be fewer than the number of
2528/// function parameters, if some of the parameters have default
Douglas Gregor7825bf32011-01-06 22:09:01 +00002529/// arguments (in C++) or the last parameter is a parameter pack.
Chris Lattner58258242008-04-10 02:22:51 +00002530unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002531 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002532 return getNumParams();
2533
Douglas Gregor7825bf32011-01-06 22:09:01 +00002534 unsigned NumRequiredArgs = getNumParams();
2535
2536 // If the last parameter is a parameter pack, we don't need an argument for
2537 // it.
2538 if (NumRequiredArgs > 0 &&
2539 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
2540 --NumRequiredArgs;
2541
2542 // If this parameter has a default argument, we don't need an argument for
2543 // it.
2544 while (NumRequiredArgs > 0 &&
2545 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
Chris Lattner58258242008-04-10 02:22:51 +00002546 --NumRequiredArgs;
2547
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002548 // We might have parameter packs before the end. These can't be deduced,
2549 // but they can still handle multiple arguments.
2550 unsigned ArgIdx = NumRequiredArgs;
2551 while (ArgIdx > 0) {
2552 if (getParamDecl(ArgIdx - 1)->isParameterPack())
2553 NumRequiredArgs = ArgIdx;
2554
2555 --ArgIdx;
2556 }
2557
Chris Lattner58258242008-04-10 02:22:51 +00002558 return NumRequiredArgs;
2559}
2560
Eli Friedman1b125c32012-02-07 03:50:18 +00002561static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2562 // Only consider file-scope declarations in this test.
2563 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2564 return false;
2565
2566 // Only consider explicit declarations; the presence of a builtin for a
2567 // libcall shouldn't affect whether a definition is externally visible.
2568 if (Redecl->isImplicit())
2569 return false;
2570
2571 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2572 return true; // Not an inline definition
2573
2574 return false;
2575}
2576
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002577/// \brief For a function declaration in C or C++, determine whether this
2578/// declaration causes the definition to be externally visible.
2579///
Eli Friedman1b125c32012-02-07 03:50:18 +00002580/// Specifically, this determines if adding the current declaration to the set
2581/// of redeclarations of the given functions causes
2582/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002583bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2584 assert(!doesThisDeclarationHaveABody() &&
2585 "Must have a declaration without a body.");
2586
2587 ASTContext &Context = getASTContext();
2588
David Blaikiebbafb8a2012-03-11 07:00:24 +00002589 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002590 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2591 // an externally visible definition.
2592 //
2593 // FIXME: What happens if gnu_inline gets added on after the first
2594 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002595 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002596 return false;
2597
2598 const FunctionDecl *Prev = this;
2599 bool FoundBody = false;
2600 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002601 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002602
2603 if (Prev->Body) {
2604 // If it's not the case that both 'inline' and 'extern' are
2605 // specified on the definition, then it is always externally visible.
2606 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002607 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002608 return false;
2609 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002610 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002611 return false;
2612 }
2613 }
2614 return FoundBody;
2615 }
2616
David Blaikiebbafb8a2012-03-11 07:00:24 +00002617 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002618 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002619
2620 // C99 6.7.4p6:
2621 // [...] If all of the file scope declarations for a function in a
2622 // translation unit include the inline function specifier without extern,
2623 // then the definition in that translation unit is an inline definition.
2624 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002625 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002626 const FunctionDecl *Prev = this;
2627 bool FoundBody = false;
2628 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002629 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002630 if (RedeclForcesDefC99(Prev))
2631 return false;
2632 }
2633 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002634}
2635
Richard Smithf3814ad2013-01-25 00:08:28 +00002636/// \brief For an inline function definition in C, or for a gnu_inline function
2637/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002638///
2639/// Inline function definitions are always available for inlining optimizations.
2640/// However, depending on the language dialect, declaration specifiers, and
2641/// attributes, the definition of an inline function may or may not be
2642/// "externally" visible to other translation units in the program.
2643///
2644/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00002645/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00002646/// inline definition becomes externally visible (C99 6.7.4p6).
2647///
2648/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2649/// definition, we use the GNU semantics for inline, which are nearly the
2650/// opposite of C99 semantics. In particular, "inline" by itself will create
2651/// an externally visible symbol, but "extern inline" will not create an
2652/// externally visible symbol.
2653bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002654 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002655 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00002656 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00002657
David Blaikiebbafb8a2012-03-11 07:00:24 +00002658 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002659 // Note: If you change the logic here, please change
2660 // doesDeclarationForceExternallyVisibleDefinition as well.
2661 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00002662 // If it's not the case that both 'inline' and 'extern' are
2663 // specified on the definition, then this inline definition is
2664 // externally visible.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002665 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00002666 return true;
2667
2668 // If any declaration is 'inline' but not 'extern', then this definition
2669 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00002670 for (auto Redecl : redecls()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00002671 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002672 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00002673 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00002674 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00002675
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002676 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002677 }
Eli Friedman1b125c32012-02-07 03:50:18 +00002678
Richard Smithf3814ad2013-01-25 00:08:28 +00002679 // The rest of this function is C-only.
2680 assert(!Context.getLangOpts().CPlusPlus &&
2681 "should not use C inline rules in C++");
2682
Douglas Gregor299d76e2009-09-13 07:46:26 +00002683 // C99 6.7.4p6:
2684 // [...] If all of the file scope declarations for a function in a
2685 // translation unit include the inline function specifier without extern,
2686 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00002687 for (auto Redecl : redecls()) {
2688 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00002689 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002690 }
2691
2692 // C99 6.7.4p6:
2693 // An inline definition does not provide an external definition for the
2694 // function, and does not forbid an external definition in another
2695 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002696 return false;
2697}
2698
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002699/// getOverloadedOperator - Which C++ overloaded operator this
2700/// function represents, if any.
2701OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00002702 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2703 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002704 else
2705 return OO_None;
2706}
2707
Alexis Huntc88db062010-01-13 09:01:02 +00002708/// getLiteralIdentifier - The literal suffix identifier this function
2709/// represents, if any.
2710const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2711 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2712 return getDeclName().getCXXLiteralIdentifier();
2713 else
2714 return 0;
2715}
2716
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002717FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2718 if (TemplateOrSpecialization.isNull())
2719 return TK_NonTemplate;
2720 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2721 return TK_FunctionTemplate;
2722 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2723 return TK_MemberSpecialization;
2724 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2725 return TK_FunctionTemplateSpecialization;
2726 if (TemplateOrSpecialization.is
2727 <DependentFunctionTemplateSpecializationInfo*>())
2728 return TK_DependentFunctionTemplateSpecialization;
2729
David Blaikie83d382b2011-09-23 05:06:16 +00002730 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002731}
2732
Douglas Gregord801b062009-10-07 23:56:10 +00002733FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002734 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00002735 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2736
2737 return 0;
2738}
2739
2740void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002741FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2742 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00002743 TemplateSpecializationKind TSK) {
2744 assert(TemplateOrSpecialization.isNull() &&
2745 "Member function is already a specialization");
2746 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002747 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00002748 TemplateOrSpecialization = Info;
2749}
2750
Douglas Gregorafca3b42009-10-27 20:53:28 +00002751bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00002752 // If the function is invalid, it can't be implicitly instantiated.
2753 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00002754 return false;
2755
2756 switch (getTemplateSpecializationKind()) {
2757 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00002758 case TSK_ExplicitInstantiationDefinition:
2759 return false;
2760
2761 case TSK_ImplicitInstantiation:
2762 return true;
2763
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002764 // It is possible to instantiate TSK_ExplicitSpecialization kind
2765 // if the FunctionDecl has a class scope specialization pattern.
2766 case TSK_ExplicitSpecialization:
2767 return getClassScopeSpecializationPattern() != 0;
2768
Douglas Gregorafca3b42009-10-27 20:53:28 +00002769 case TSK_ExplicitInstantiationDeclaration:
2770 // Handled below.
2771 break;
2772 }
2773
2774 // Find the actual template from which we will instantiate.
2775 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002776 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00002777 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002778 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00002779
2780 // C++0x [temp.explicit]p9:
2781 // Except for inline functions, other explicit instantiation declarations
2782 // have the effect of suppressing the implicit instantiation of the entity
2783 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002784 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00002785 return true;
2786
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002787 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00002788}
2789
2790bool FunctionDecl::isTemplateInstantiation() const {
2791 switch (getTemplateSpecializationKind()) {
2792 case TSK_Undeclared:
2793 case TSK_ExplicitSpecialization:
2794 return false;
2795 case TSK_ImplicitInstantiation:
2796 case TSK_ExplicitInstantiationDeclaration:
2797 case TSK_ExplicitInstantiationDefinition:
2798 return true;
2799 }
2800 llvm_unreachable("All TSK values handled.");
2801}
Douglas Gregorafca3b42009-10-27 20:53:28 +00002802
2803FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002804 // Handle class scope explicit specialization special case.
2805 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2806 return getClassScopeSpecializationPattern();
2807
Douglas Gregorafca3b42009-10-27 20:53:28 +00002808 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2809 while (Primary->getInstantiatedFromMemberTemplate()) {
2810 // If we have hit a point where the user provided a specialization of
2811 // this template, we're done looking.
2812 if (Primary->isMemberSpecialization())
2813 break;
2814
2815 Primary = Primary->getInstantiatedFromMemberTemplate();
2816 }
2817
2818 return Primary->getTemplatedDecl();
2819 }
2820
2821 return getInstantiatedFromMemberFunction();
2822}
2823
Douglas Gregor70d83e22009-06-29 17:30:29 +00002824FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00002825 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002826 = TemplateOrSpecialization
2827 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00002828 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00002829 }
2830 return 0;
2831}
2832
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002833FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2834 return getASTContext().getClassScopeSpecializationPattern(this);
2835}
2836
Douglas Gregor70d83e22009-06-29 17:30:29 +00002837const TemplateArgumentList *
2838FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00002839 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00002840 = TemplateOrSpecialization
2841 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00002842 return Info->TemplateArguments;
2843 }
2844 return 0;
2845}
2846
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00002847const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002848FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2849 if (FunctionTemplateSpecializationInfo *Info
2850 = TemplateOrSpecialization
2851 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2852 return Info->TemplateArgumentsAsWritten;
2853 }
2854 return 0;
2855}
2856
Mike Stump11289f42009-09-09 15:08:12 +00002857void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002858FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2859 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002860 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002861 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002862 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00002863 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2864 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002865 assert(TSK != TSK_Undeclared &&
2866 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00002867 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002868 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002869 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00002870 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2871 TemplateArgs,
2872 TemplateArgsAsWritten,
2873 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002874 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00002875 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002876}
2877
John McCallb9c78482010-04-08 09:05:18 +00002878void
2879FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2880 const UnresolvedSetImpl &Templates,
2881 const TemplateArgumentListInfo &TemplateArgs) {
2882 assert(TemplateOrSpecialization.isNull());
2883 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2884 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall900d9802010-04-13 22:18:28 +00002885 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallb9c78482010-04-08 09:05:18 +00002886 void *Buffer = Context.Allocate(Size);
2887 DependentFunctionTemplateSpecializationInfo *Info =
2888 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2889 TemplateArgs);
2890 TemplateOrSpecialization = Info;
2891}
2892
2893DependentFunctionTemplateSpecializationInfo::
2894DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2895 const TemplateArgumentListInfo &TArgs)
2896 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2897
2898 d.NumTemplates = Ts.size();
2899 d.NumArgs = TArgs.size();
2900
2901 FunctionTemplateDecl **TsArray =
2902 const_cast<FunctionTemplateDecl**>(getTemplates());
2903 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2904 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2905
2906 TemplateArgumentLoc *ArgsArray =
2907 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2908 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2909 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2910}
2911
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002912TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00002913 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002914 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00002915 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00002916 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00002917 if (FTSInfo)
2918 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00002919
Douglas Gregord801b062009-10-07 23:56:10 +00002920 MemberSpecializationInfo *MSInfo
2921 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2922 if (MSInfo)
2923 return MSInfo->getTemplateSpecializationKind();
2924
2925 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002926}
2927
Mike Stump11289f42009-09-09 15:08:12 +00002928void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002929FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2930 SourceLocation PointOfInstantiation) {
2931 if (FunctionTemplateSpecializationInfo *FTSInfo
2932 = TemplateOrSpecialization.dyn_cast<
2933 FunctionTemplateSpecializationInfo*>()) {
2934 FTSInfo->setTemplateSpecializationKind(TSK);
2935 if (TSK != TSK_ExplicitSpecialization &&
2936 PointOfInstantiation.isValid() &&
2937 FTSInfo->getPointOfInstantiation().isInvalid())
2938 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2939 } else if (MemberSpecializationInfo *MSInfo
2940 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2941 MSInfo->setTemplateSpecializationKind(TSK);
2942 if (TSK != TSK_ExplicitSpecialization &&
2943 PointOfInstantiation.isValid() &&
2944 MSInfo->getPointOfInstantiation().isInvalid())
2945 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2946 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002947 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002948}
2949
2950SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00002951 if (FunctionTemplateSpecializationInfo *FTSInfo
2952 = TemplateOrSpecialization.dyn_cast<
2953 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002954 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00002955 else if (MemberSpecializationInfo *MSInfo
2956 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002957 return MSInfo->getPointOfInstantiation();
2958
2959 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00002960}
2961
Douglas Gregor6411b922009-09-11 20:15:17 +00002962bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002963 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00002964 return true;
2965
2966 // If this function was instantiated from a member function of a
2967 // class template, check whether that member function was defined out-of-line.
2968 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2969 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002970 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002971 return Definition->isOutOfLine();
2972 }
2973
2974 // If this function was instantiated from a function template,
2975 // check whether that function template was defined out-of-line.
2976 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2977 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002978 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002979 return Definition->isOutOfLine();
2980 }
2981
2982 return false;
2983}
2984
Abramo Bagnaraea947882011-03-08 16:41:52 +00002985SourceRange FunctionDecl::getSourceRange() const {
2986 return SourceRange(getOuterLocStart(), EndRangeLoc);
2987}
2988
Anna Zaks28db7ce2012-01-18 02:45:01 +00002989unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00002990 IdentifierInfo *FnInfo = getIdentifier();
2991
2992 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00002993 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002994
2995 // Builtin handling.
2996 switch (getBuiltinID()) {
2997 case Builtin::BI__builtin_memset:
2998 case Builtin::BI__builtin___memset_chk:
2999 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003000 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003001
3002 case Builtin::BI__builtin_memcpy:
3003 case Builtin::BI__builtin___memcpy_chk:
3004 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003005 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003006
3007 case Builtin::BI__builtin_memmove:
3008 case Builtin::BI__builtin___memmove_chk:
3009 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003010 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003011
3012 case Builtin::BIstrlcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003013 return Builtin::BIstrlcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003014 case Builtin::BIstrlcat:
Anna Zaks22122702012-01-17 00:37:07 +00003015 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003016
3017 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003018 case Builtin::BImemcmp:
3019 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003020
3021 case Builtin::BI__builtin_strncpy:
3022 case Builtin::BI__builtin___strncpy_chk:
3023 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003024 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003025
3026 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003027 case Builtin::BIstrncmp:
3028 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003029
3030 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003031 case Builtin::BIstrncasecmp:
3032 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003033
3034 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003035 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003036 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003037 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003038
3039 case Builtin::BI__builtin_strndup:
3040 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003041 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003042
Anna Zaks314cd092012-02-01 19:08:57 +00003043 case Builtin::BI__builtin_strlen:
3044 case Builtin::BIstrlen:
3045 return Builtin::BIstrlen;
3046
Anna Zaks201d4892012-01-13 21:52:01 +00003047 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003048 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003049 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003050 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003051 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003052 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003053 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003054 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003055 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003056 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003057 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003058 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003059 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003060 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003061 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003062 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003063 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003064 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003065 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003066 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003067 else if (FnInfo->isStr("strlen"))
3068 return Builtin::BIstrlen;
Anna Zaks201d4892012-01-13 21:52:01 +00003069 }
3070 break;
3071 }
Anna Zaks22122702012-01-17 00:37:07 +00003072 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003073}
3074
Chris Lattner59a25942008-03-31 00:36:02 +00003075//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003076// FieldDecl Implementation
3077//===----------------------------------------------------------------------===//
3078
Jay Foad39c79802011-01-12 09:06:06 +00003079FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003080 SourceLocation StartLoc, SourceLocation IdLoc,
3081 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003082 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003083 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003084 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3085 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003086}
3087
Douglas Gregor72172e92012-01-05 21:55:30 +00003088FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003089 return new (C, ID) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
3090 0, QualType(), 0, 0, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00003091}
3092
Sebastian Redl833ef452010-01-26 22:01:41 +00003093bool FieldDecl::isAnonymousStructOrUnion() const {
3094 if (!isImplicit() || getDeclName())
3095 return false;
3096
3097 if (const RecordType *Record = getType()->getAs<RecordType>())
3098 return Record->getDecl()->isAnonymousStructOrUnion();
3099
3100 return false;
3101}
3102
Richard Smithcaf33902011-10-10 18:28:20 +00003103unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3104 assert(isBitField() && "not a bitfield");
3105 Expr *BitWidth = InitializerOrBitWidth.getPointer();
3106 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3107}
3108
John McCall4e819612011-01-20 07:57:12 +00003109unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00003110 const FieldDecl *Canonical = getCanonicalDecl();
3111 if (Canonical != this)
3112 return Canonical->getFieldIndex();
3113
John McCall4e819612011-01-20 07:57:12 +00003114 if (CachedFieldIndex) return CachedFieldIndex - 1;
3115
Richard Smithd62306a2011-11-10 06:34:14 +00003116 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00003117 const RecordDecl *RD = getParent();
Richard Smithd62306a2011-11-10 06:34:14 +00003118
3119 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
Eli Friedman2782dac2013-06-26 20:50:34 +00003120 I != E; ++I, ++Index)
Richard Smith0b87e072013-10-07 08:02:11 +00003121 I->getCanonicalDecl()->CachedFieldIndex = Index + 1;
John McCall4e819612011-01-20 07:57:12 +00003122
Richard Smithd62306a2011-11-10 06:34:14 +00003123 assert(CachedFieldIndex && "failed to find field in parent");
3124 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00003125}
3126
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003127SourceRange FieldDecl::getSourceRange() const {
Abramo Bagnaraff371ac2011-08-05 08:02:55 +00003128 if (const Expr *E = InitializerOrBitWidth.getPointer())
3129 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00003130 return DeclaratorDecl::getSourceRange();
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003131}
3132
Abramo Bagnarab1cdde72012-07-02 20:35:48 +00003133void FieldDecl::setBitWidth(Expr *Width) {
3134 assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
3135 "bit width or initializer already set");
3136 InitializerOrBitWidth.setPointer(Width);
3137}
3138
Richard Smith938f40b2011-06-11 17:19:42 +00003139void FieldDecl::setInClassInitializer(Expr *Init) {
Richard Smith2b013182012-06-10 03:12:00 +00003140 assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
Richard Smith938f40b2011-06-11 17:19:42 +00003141 "bit width or initializer already set");
3142 InitializerOrBitWidth.setPointer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003143}
3144
Sebastian Redl833ef452010-01-26 22:01:41 +00003145//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003146// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00003147//===----------------------------------------------------------------------===//
3148
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003149SourceLocation TagDecl::getOuterLocStart() const {
3150 return getTemplateOrInnerLocStart(this);
3151}
3152
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003153SourceRange TagDecl::getSourceRange() const {
3154 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003155 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003156}
3157
Rafael Espindola8db352d2013-10-17 15:37:26 +00003158TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00003159
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00003160void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer50ce8352013-09-17 23:57:10 +00003161 NamedDeclOrQualifier = TDD;
Douglas Gregora72a4e32010-05-19 18:39:18 +00003162 if (TypeForDecl)
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003163 assert(TypeForDecl->isLinkageValid());
3164 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00003165}
3166
Douglas Gregordee1be82009-01-17 00:42:38 +00003167void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003168 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00003169
David Blaikie095deba2012-11-14 01:52:05 +00003170 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
John McCall67da35c2010-02-04 22:26:26 +00003171 struct CXXRecordDecl::DefinitionData *Data =
3172 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00003173 for (auto I : redecls())
3174 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00003175 }
Douglas Gregordee1be82009-01-17 00:42:38 +00003176}
3177
3178void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00003179 assert((!isa<CXXRecordDecl>(this) ||
3180 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3181 "definition completed but not started");
3182
John McCallf937c022011-10-07 06:10:15 +00003183 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003184 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00003185
3186 if (ASTMutationListener *L = getASTMutationListener())
3187 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00003188}
3189
John McCallf937c022011-10-07 06:10:15 +00003190TagDecl *TagDecl::getDefinition() const {
3191 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003192 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003193
3194 // If it's possible for us to have an out-of-date definition, check now.
3195 if (MayHaveOutOfDateDef) {
3196 if (IdentifierInfo *II = getIdentifier()) {
3197 if (II->isOutOfDate()) {
3198 updateOutOfDate(*II);
3199 }
3200 }
3201 }
3202
Andrew Trickba266ee2010-10-19 21:54:32 +00003203 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
3204 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003205
Aaron Ballman86c93902014-03-06 23:45:36 +00003206 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00003207 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00003208 return R;
Mike Stump11289f42009-09-09 15:08:12 +00003209
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003210 return 0;
Ted Kremenek21475702008-09-05 17:16:31 +00003211}
3212
Douglas Gregor14454802011-02-25 02:25:35 +00003213void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3214 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00003215 // Make sure the extended qualifier info is allocated.
3216 if (!hasExtInfo())
David Majnemer50ce8352013-09-17 23:57:10 +00003217 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00003218 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00003219 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003220 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00003221 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00003222 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00003223 if (getExtInfo()->NumTemplParamLists == 0) {
3224 getASTContext().Deallocate(getExtInfo());
David Majnemer50ce8352013-09-17 23:57:10 +00003225 NamedDeclOrQualifier = (TypedefNameDecl*) 0;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003226 }
3227 else
3228 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00003229 }
3230 }
3231}
3232
Abramo Bagnara60804e12011-03-18 15:16:37 +00003233void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
3234 unsigned NumTPLists,
3235 TemplateParameterList **TPLists) {
3236 assert(NumTPLists > 0);
3237 // Make sure the extended decl info is allocated.
3238 if (!hasExtInfo())
3239 // Allocate external info struct.
David Majnemer50ce8352013-09-17 23:57:10 +00003240 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003241 // Set the template parameter lists info.
3242 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
3243}
3244
Ted Kremenek21475702008-09-05 17:16:31 +00003245//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003246// EnumDecl Implementation
3247//===----------------------------------------------------------------------===//
3248
David Blaikie68e081d2011-12-20 02:48:34 +00003249void EnumDecl::anchor() { }
3250
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003251EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3252 SourceLocation StartLoc, SourceLocation IdLoc,
3253 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00003254 EnumDecl *PrevDecl, bool IsScoped,
3255 bool IsScopedUsingClassTag, bool IsFixed) {
Richard Smithf7981722013-11-22 09:01:48 +00003256 EnumDecl *Enum = new (C, DC) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
3257 IsScoped, IsScopedUsingClassTag,
3258 IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003259 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00003260 C.getTypeDeclType(Enum, PrevDecl);
3261 return Enum;
3262}
3263
Douglas Gregor72172e92012-01-05 21:55:30 +00003264EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003265 EnumDecl *Enum = new (C, ID) EnumDecl(0, SourceLocation(), SourceLocation(),
3266 0, 0, false, false, false);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003267 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3268 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003269}
3270
Alp Tokerb9fa5122014-01-06 11:31:18 +00003271SourceRange EnumDecl::getIntegerTypeRange() const {
3272 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3273 return TI->getTypeLoc().getSourceRange();
3274 return SourceRange();
3275}
3276
Douglas Gregord5058122010-02-11 01:19:42 +00003277void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00003278 QualType NewPromotionType,
3279 unsigned NumPositiveBits,
3280 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00003281 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00003282 if (!IntegerType)
3283 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00003284 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00003285 setNumPositiveBits(NumPositiveBits);
3286 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00003287 TagDecl::completeDefinition();
3288}
3289
Richard Smith7d137e32012-03-23 03:33:32 +00003290TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3291 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3292 return MSI->getTemplateSpecializationKind();
3293
3294 return TSK_Undeclared;
3295}
3296
3297void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3298 SourceLocation PointOfInstantiation) {
3299 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3300 assert(MSI && "Not an instantiated member enumeration?");
3301 MSI->setTemplateSpecializationKind(TSK);
3302 if (TSK != TSK_ExplicitSpecialization &&
3303 PointOfInstantiation.isValid() &&
3304 MSI->getPointOfInstantiation().isInvalid())
3305 MSI->setPointOfInstantiation(PointOfInstantiation);
3306}
3307
Richard Smith4b38ded2012-03-14 23:13:10 +00003308EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3309 if (SpecializationInfo)
3310 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3311
3312 return 0;
3313}
3314
3315void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3316 TemplateSpecializationKind TSK) {
3317 assert(!SpecializationInfo && "Member enum is already a specialization");
3318 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3319}
3320
Sebastian Redl833ef452010-01-26 22:01:41 +00003321//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003322// RecordDecl Implementation
3323//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003324
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003325RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
3326 SourceLocation StartLoc, SourceLocation IdLoc,
3327 IdentifierInfo *Id, RecordDecl *PrevDecl)
3328 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003329 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003330 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003331 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00003332 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003333 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00003334 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003335}
3336
Jay Foad39c79802011-01-12 09:06:06 +00003337RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003338 SourceLocation StartLoc, SourceLocation IdLoc,
3339 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smithf7981722013-11-22 09:01:48 +00003340 RecordDecl* R = new (C, DC) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
3341 PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003342 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3343
Ted Kremenek21475702008-09-05 17:16:31 +00003344 C.getTypeDeclType(R, PrevDecl);
3345 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003346}
3347
Douglas Gregor72172e92012-01-05 21:55:30 +00003348RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003349 RecordDecl *R = new (C, ID) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
3350 SourceLocation(), 0, 0);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003351 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3352 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003353}
3354
Douglas Gregordfcad112009-03-25 15:59:44 +00003355bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003356 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003357 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3358}
3359
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003360RecordDecl::field_iterator RecordDecl::field_begin() const {
3361 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3362 LoadFieldsFromExternalStorage();
3363
3364 return field_iterator(decl_iterator(FirstDecl));
3365}
3366
Douglas Gregorb11aad82011-02-19 18:51:44 +00003367/// completeDefinition - Notes that the definition of this type is now
3368/// complete.
3369void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003370 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003371 TagDecl::completeDefinition();
3372}
3373
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003374/// isMsStruct - Get whether or not this record uses ms_struct layout.
3375/// This which can be turned on with an attribute, pragma, or the
3376/// -mms-bitfields command-line option.
3377bool RecordDecl::isMsStruct(const ASTContext &C) const {
3378 return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3379}
3380
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003381static bool isFieldOrIndirectField(Decl::Kind K) {
3382 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3383}
3384
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003385void RecordDecl::LoadFieldsFromExternalStorage() const {
3386 ExternalASTSource *Source = getASTContext().getExternalSource();
3387 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3388
3389 // Notify that we have a RecordDecl doing some initialization.
3390 ExternalASTSource::Deserializing TheFields(Source);
3391
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003392 SmallVector<Decl*, 64> Decls;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003393 LoadedFieldsFromExternalStorage = true;
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003394 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3395 Decls)) {
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003396 case ELR_Success:
3397 break;
3398
3399 case ELR_AlreadyLoaded:
3400 case ELR_Failure:
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003401 return;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003402 }
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003403
3404#ifndef NDEBUG
3405 // Check that all decls we got were FieldDecls.
3406 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003407 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003408#endif
3409
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003410 if (Decls.empty())
3411 return;
3412
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003413 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003414 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003415}
3416
Steve Naroff415d3d52008-10-08 17:01:13 +00003417//===----------------------------------------------------------------------===//
3418// BlockDecl Implementation
3419//===----------------------------------------------------------------------===//
3420
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003421void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Steve Naroffc4b30e52009-03-13 16:56:44 +00003422 assert(ParamInfo == 0 && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00003423
Steve Naroffc4b30e52009-03-13 16:56:44 +00003424 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003425 if (!NewParamInfo.empty()) {
3426 NumParams = NewParamInfo.size();
3427 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3428 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003429 }
3430}
3431
John McCall351762c2011-02-07 10:33:21 +00003432void BlockDecl::setCaptures(ASTContext &Context,
3433 const Capture *begin,
3434 const Capture *end,
3435 bool capturesCXXThis) {
John McCallc63de662011-02-02 13:00:07 +00003436 CapturesCXXThis = capturesCXXThis;
3437
3438 if (begin == end) {
John McCall351762c2011-02-07 10:33:21 +00003439 NumCaptures = 0;
3440 Captures = 0;
John McCallc63de662011-02-02 13:00:07 +00003441 return;
3442 }
3443
John McCall351762c2011-02-07 10:33:21 +00003444 NumCaptures = end - begin;
3445
3446 // Avoid new Capture[] because we don't want to provide a default
3447 // constructor.
3448 size_t allocationSize = NumCaptures * sizeof(Capture);
3449 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3450 memcpy(buffer, begin, allocationSize);
3451 Captures = static_cast<Capture*>(buffer);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003452}
Sebastian Redl833ef452010-01-26 22:01:41 +00003453
John McCallce45f882011-06-15 22:51:16 +00003454bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00003455 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00003456 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00003457 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00003458 return true;
3459
3460 return false;
3461}
3462
Douglas Gregor70226da2010-12-21 16:27:07 +00003463SourceRange BlockDecl::getSourceRange() const {
3464 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3465}
Sebastian Redl833ef452010-01-26 22:01:41 +00003466
3467//===----------------------------------------------------------------------===//
3468// Other Decl Allocation/Deallocation Method Implementations
3469//===----------------------------------------------------------------------===//
3470
David Blaikie68e081d2011-12-20 02:48:34 +00003471void TranslationUnitDecl::anchor() { }
3472
Sebastian Redl833ef452010-01-26 22:01:41 +00003473TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Richard Smithf7981722013-11-22 09:01:48 +00003474 return new (C, (DeclContext*)0) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00003475}
3476
David Blaikie68e081d2011-12-20 02:48:34 +00003477void LabelDecl::anchor() { }
3478
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003479LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003480 SourceLocation IdentL, IdentifierInfo *II) {
Richard Smithf7981722013-11-22 09:01:48 +00003481 return new (C, DC) LabelDecl(DC, IdentL, II, 0, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003482}
3483
3484LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3485 SourceLocation IdentL, IdentifierInfo *II,
3486 SourceLocation GnuLabelL) {
3487 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Richard Smithf7981722013-11-22 09:01:48 +00003488 return new (C, DC) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003489}
3490
Douglas Gregor72172e92012-01-05 21:55:30 +00003491LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003492 return new (C, ID) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00003493}
3494
David Blaikie68e081d2011-12-20 02:48:34 +00003495void ValueDecl::anchor() { }
3496
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003497bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00003498 for (const auto *I : attrs())
3499 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003500 return true;
3501
3502 return isWeakImported();
3503}
3504
David Blaikie68e081d2011-12-20 02:48:34 +00003505void ImplicitParamDecl::anchor() { }
3506
Sebastian Redl833ef452010-01-26 22:01:41 +00003507ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003508 SourceLocation IdLoc,
3509 IdentifierInfo *Id,
3510 QualType Type) {
Richard Smithf7981722013-11-22 09:01:48 +00003511 return new (C, DC) ImplicitParamDecl(DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00003512}
3513
Richard Smithf7981722013-11-22 09:01:48 +00003514ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00003515 unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003516 return new (C, ID) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
Douglas Gregor72172e92012-01-05 21:55:30 +00003517}
3518
Sebastian Redl833ef452010-01-26 22:01:41 +00003519FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003520 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003521 const DeclarationNameInfo &NameInfo,
3522 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003523 StorageClass SC,
Richard Smithf7981722013-11-22 09:01:48 +00003524 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00003525 bool hasWrittenPrototype,
3526 bool isConstexprSpecified) {
Richard Smithf7981722013-11-22 09:01:48 +00003527 FunctionDecl *New =
3528 new (C, DC) FunctionDecl(Function, DC, StartLoc, NameInfo, T, TInfo, SC,
3529 isInlineSpecified, isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00003530 New->HasWrittenPrototype = hasWrittenPrototype;
3531 return New;
3532}
3533
Douglas Gregor72172e92012-01-05 21:55:30 +00003534FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003535 return new (C, ID) FunctionDecl(Function, 0, SourceLocation(),
3536 DeclarationNameInfo(), QualType(), 0,
3537 SC_None, false, false);
Douglas Gregor72172e92012-01-05 21:55:30 +00003538}
3539
Sebastian Redl833ef452010-01-26 22:01:41 +00003540BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00003541 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00003542}
3543
Douglas Gregor72172e92012-01-05 21:55:30 +00003544BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003545 return new (C, ID) BlockDecl(0, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00003546}
3547
Ben Langmuir37943a72013-05-03 19:00:33 +00003548CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
3549 unsigned NumParams) {
Richard Smithf7981722013-11-22 09:01:48 +00003550 return new (C, DC, NumParams * sizeof(ImplicitParamDecl *))
3551 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003552}
3553
Ben Langmuirce914fc2013-05-03 19:20:19 +00003554CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00003555 unsigned NumParams) {
3556 return new (C, ID, NumParams * sizeof(ImplicitParamDecl *))
3557 CapturedDecl(0, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00003558}
3559
Sebastian Redl833ef452010-01-26 22:01:41 +00003560EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3561 SourceLocation L,
3562 IdentifierInfo *Id, QualType T,
3563 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00003564 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00003565}
3566
Douglas Gregor72172e92012-01-05 21:55:30 +00003567EnumConstantDecl *
3568EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003569 return new (C, ID) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
3570 llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00003571}
3572
David Blaikie68e081d2011-12-20 02:48:34 +00003573void IndirectFieldDecl::anchor() { }
3574
Benjamin Kramer39593702010-11-21 14:11:41 +00003575IndirectFieldDecl *
3576IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3577 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3578 unsigned CHS) {
Richard Smithf7981722013-11-22 09:01:48 +00003579 return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003580}
3581
Douglas Gregor72172e92012-01-05 21:55:30 +00003582IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3583 unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003584 return new (C, ID) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
3585 QualType(), 0, 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00003586}
3587
Douglas Gregorbe996932010-09-01 20:41:53 +00003588SourceRange EnumConstantDecl::getSourceRange() const {
3589 SourceLocation End = getLocation();
3590 if (Init)
3591 End = Init->getLocEnd();
3592 return SourceRange(getLocation(), End);
3593}
3594
David Blaikie68e081d2011-12-20 02:48:34 +00003595void TypeDecl::anchor() { }
3596
Sebastian Redl833ef452010-01-26 22:01:41 +00003597TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003598 SourceLocation StartLoc, SourceLocation IdLoc,
3599 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smithf7981722013-11-22 09:01:48 +00003600 return new (C, DC) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00003601}
3602
David Blaikie68e081d2011-12-20 02:48:34 +00003603void TypedefNameDecl::anchor() { }
3604
Douglas Gregor72172e92012-01-05 21:55:30 +00003605TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003606 return new (C, ID) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00003607}
3608
Richard Smithdda56e42011-04-15 14:24:37 +00003609TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3610 SourceLocation StartLoc,
3611 SourceLocation IdLoc, IdentifierInfo *Id,
3612 TypeSourceInfo *TInfo) {
Richard Smithf7981722013-11-22 09:01:48 +00003613 return new (C, DC) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00003614}
3615
Douglas Gregor72172e92012-01-05 21:55:30 +00003616TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003617 return new (C, ID) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00003618}
3619
Abramo Bagnaraea947882011-03-08 16:41:52 +00003620SourceRange TypedefDecl::getSourceRange() const {
3621 SourceLocation RangeEnd = getLocation();
3622 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3623 if (typeIsPostfix(TInfo->getType()))
3624 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3625 }
3626 return SourceRange(getLocStart(), RangeEnd);
3627}
3628
Richard Smithdda56e42011-04-15 14:24:37 +00003629SourceRange TypeAliasDecl::getSourceRange() const {
3630 SourceLocation RangeEnd = getLocStart();
3631 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3632 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3633 return SourceRange(getLocStart(), RangeEnd);
3634}
3635
David Blaikie68e081d2011-12-20 02:48:34 +00003636void FileScopeAsmDecl::anchor() { }
3637
Sebastian Redl833ef452010-01-26 22:01:41 +00003638FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00003639 StringLiteral *Str,
3640 SourceLocation AsmLoc,
3641 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00003642 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00003643}
Douglas Gregorba345522011-12-02 23:23:56 +00003644
Richard Smithf7981722013-11-22 09:01:48 +00003645FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00003646 unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003647 return new (C, ID) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00003648}
3649
Michael Han84324352013-02-22 17:15:32 +00003650void EmptyDecl::anchor() {}
3651
3652EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00003653 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00003654}
3655
3656EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003657 return new (C, ID) EmptyDecl(0, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00003658}
3659
Douglas Gregorba345522011-12-02 23:23:56 +00003660//===----------------------------------------------------------------------===//
3661// ImportDecl Implementation
3662//===----------------------------------------------------------------------===//
3663
3664/// \brief Retrieve the number of module identifiers needed to name the given
3665/// module.
3666static unsigned getNumModuleIdentifiers(Module *Mod) {
3667 unsigned Result = 1;
3668 while (Mod->Parent) {
3669 Mod = Mod->Parent;
3670 ++Result;
3671 }
3672 return Result;
3673}
3674
Douglas Gregor22d09742012-01-03 18:04:46 +00003675ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003676 Module *Imported,
3677 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00003678 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003679 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003680{
3681 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3682 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3683 memcpy(StoredLocs, IdentifierLocs.data(),
3684 IdentifierLocs.size() * sizeof(SourceLocation));
3685}
3686
Douglas Gregor22d09742012-01-03 18:04:46 +00003687ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003688 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00003689 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003690 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003691{
3692 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3693}
3694
Richard Smithf7981722013-11-22 09:01:48 +00003695ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003696 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00003697 ArrayRef<SourceLocation> IdentifierLocs) {
Richard Smithf7981722013-11-22 09:01:48 +00003698 return new (C, DC, IdentifierLocs.size() * sizeof(SourceLocation))
3699 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00003700}
3701
Richard Smithf7981722013-11-22 09:01:48 +00003702ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003703 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00003704 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00003705 SourceLocation EndLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00003706 ImportDecl *Import =
3707 new (C, DC, sizeof(SourceLocation)) ImportDecl(DC, StartLoc,
3708 Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00003709 Import->setImplicit();
3710 return Import;
3711}
3712
Douglas Gregor72172e92012-01-05 21:55:30 +00003713ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3714 unsigned NumLocations) {
Richard Smithf7981722013-11-22 09:01:48 +00003715 return new (C, ID, NumLocations * sizeof(SourceLocation))
3716 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00003717}
3718
3719ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3720 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003721 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00003722
3723 const SourceLocation *StoredLocs
3724 = reinterpret_cast<const SourceLocation *>(this + 1);
3725 return ArrayRef<SourceLocation>(StoredLocs,
3726 getNumModuleIdentifiers(getImportedModule()));
3727}
3728
3729SourceRange ImportDecl::getSourceRange() const {
3730 if (!ImportedAndComplete.getInt())
3731 return SourceRange(getLocation(),
3732 *reinterpret_cast<const SourceLocation *>(this + 1));
3733
3734 return SourceRange(getLocation(), getIdentifierLocs().back());
3735}