blob: 489a65d2023643f95d36459d5394d65d482fda47 [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"
John McCall5f46c482013-02-21 23:42:58 +000032#include "llvm/Support/type_traits.h"
David Blaikie9c70e042011-09-21 18:16:56 +000033#include <algorithm>
34
Chris Lattner6d9a6852006-10-25 05:11:20 +000035using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000036
Chris Lattner88f70d62008-03-15 05:43:15 +000037//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000038// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000039//===----------------------------------------------------------------------===//
40
John McCalldf25c432013-02-16 00:17:33 +000041// Visibility rules aren't rigorously externally specified, but here
42// are the basic principles behind what we implement:
43//
44// 1. An explicit visibility attribute is generally a direct expression
45// of the user's intent and should be honored. Only the innermost
46// visibility attribute applies. If no visibility attribute applies,
47// global visibility settings are considered.
48//
49// 2. There is one caveat to the above: on or in a template pattern,
50// an explicit visibility attribute is just a default rule, and
51// visibility can be decreased by the visibility of template
52// arguments. But this, too, has an exception: an attribute on an
53// explicit specialization or instantiation causes all the visibility
54// restrictions of the template arguments to be ignored.
55//
56// 3. A variable that does not otherwise have explicit visibility can
57// be restricted by the visibility of its type.
58//
59// 4. A visibility restriction is explicit if it comes from an
60// attribute (or something like it), not a global visibility setting.
61// When emitting a reference to an external symbol, visibility
62// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +000063//
64// 5. When computing the visibility of a non-type, including a
65// non-type member of a class, only non-type visibility restrictions
66// are considered: the 'visibility' attribute, global value-visibility
67// settings, and a few special cases like __private_extern.
68//
69// 6. When computing the visibility of a type, including a type member
70// of a class, only type visibility restrictions are considered:
71// the 'type_visibility' attribute and global type-visibility settings.
72// However, a 'visibility' attribute counts as a 'type_visibility'
73// attribute on any declaration that only has the former.
74//
75// The visibility of a "secondary" entity, like a template argument,
76// is computed using the kind of that entity, not the kind of the
77// primary entity for which we are computing visibility. For example,
78// the visibility of a specialization of either of these templates:
79// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
80// template <class T, bool (&compare)(T, X)> class matcher;
81// is restricted according to the type visibility of the argument 'T',
82// the type visibility of 'bool(&)(T,X)', and the value visibility of
83// the argument function 'compare'. That 'has_match' is a value
84// and 'matcher' is a type only matters when looking for attributes
85// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +000086
John McCall5f46c482013-02-21 23:42:58 +000087const unsigned IgnoreExplicitVisibilityBit = 2;
88
John McCalldf25c432013-02-16 00:17:33 +000089/// Kinds of LV computation. The linkage side of the computation is
90/// always the same, but different things can change how visibility is
91/// computed.
92enum LVComputationKind {
John McCall5f46c482013-02-21 23:42:58 +000093 /// Do an LV computation for, ultimately, a type.
94 /// Visibility may be restricted by type visibility settings and
95 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +000096 LVForType = NamedDecl::VisibilityForType,
John McCalldf25c432013-02-16 00:17:33 +000097
John McCall5f46c482013-02-21 23:42:58 +000098 /// Do an LV computation for, ultimately, a non-type declaration.
99 /// Visibility may be restricted by value visibility settings and
100 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000101 LVForValue = NamedDecl::VisibilityForValue,
102
John McCall5f46c482013-02-21 23:42:58 +0000103 /// Do an LV computation for, ultimately, a type that already has
104 /// some sort of explicit visibility. Visibility may only be
105 /// restricted by the visibility of template arguments.
106 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
John McCalld041a9b2013-02-20 01:54:26 +0000107
John McCall5f46c482013-02-21 23:42:58 +0000108 /// Do an LV computation for, ultimately, a non-type declaration
109 /// that already has some sort of explicit visibility. Visibility
110 /// may only be restricted by the visibility of template arguments.
111 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit)
John McCalldf25c432013-02-16 00:17:33 +0000112};
113
John McCalld041a9b2013-02-20 01:54:26 +0000114/// Does this computation kind permit us to consider additional
115/// visibility settings from attributes and the like?
116static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000117 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
John McCalld041a9b2013-02-20 01:54:26 +0000118}
119
120/// Given an LVComputationKind, return one of the same type/value sort
121/// that records that it already has explicit visibility.
122static LVComputationKind
123withExplicitVisibilityAlready(LVComputationKind oldKind) {
124 LVComputationKind newKind =
John McCall5f46c482013-02-21 23:42:58 +0000125 static_cast<LVComputationKind>(unsigned(oldKind) |
126 IgnoreExplicitVisibilityBit);
John McCalld041a9b2013-02-20 01:54:26 +0000127 assert(oldKind != LVForType || newKind == LVForExplicitType);
128 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
129 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
130 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
131 return newKind;
132}
133
David Blaikie05785d12013-02-20 22:23:23 +0000134static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
135 LVComputationKind kind) {
John McCalld041a9b2013-02-20 01:54:26 +0000136 assert(!hasExplicitVisibilityAlready(kind) &&
137 "asking for explicit visibility when we shouldn't be");
138 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
139}
140
John McCalldf25c432013-02-16 00:17:33 +0000141typedef NamedDecl::LinkageInfo LinkageInfo;
142
143/// Is the given declaration a "type" or a "value" for the purposes of
144/// visibility computation?
145static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000146 return isa<TypeDecl>(D) ||
147 isa<ClassTemplateDecl>(D) ||
148 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000149}
150
John McCall5f46c482013-02-21 23:42:58 +0000151/// Does the given declaration have member specialization information,
152/// and if so, is it an explicit specialization?
153template <class T> static typename
154llvm::enable_if_c<!llvm::is_base_of<RedeclarableTemplateDecl, T>::value,
155 bool>::type
156isExplicitMemberSpecialization(const T *D) {
157 if (const MemberSpecializationInfo *member =
158 D->getMemberSpecializationInfo()) {
159 return member->isExplicitSpecialization();
160 }
161 return false;
162}
163
164/// For templates, this question is easier: a member template can't be
165/// explicitly instantiated, so there's a single bit indicating whether
166/// or not this is an explicit member specialization.
167static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
168 return D->isMemberSpecialization();
169}
170
John McCalld041a9b2013-02-20 01:54:26 +0000171/// Given a visibility attribute, return the explicit visibility
172/// associated with it.
173template <class T>
174static Visibility getVisibilityFromAttr(const T *attr) {
175 switch (attr->getVisibility()) {
176 case T::Default:
177 return DefaultVisibility;
178 case T::Hidden:
179 return HiddenVisibility;
180 case T::Protected:
181 return ProtectedVisibility;
182 }
183 llvm_unreachable("bad visibility kind");
184}
185
John McCalldf25c432013-02-16 00:17:33 +0000186/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000187static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000188 NamedDecl::ExplicitVisibilityKind kind) {
189 // If we're ultimately computing the visibility of a type, look for
190 // a 'type_visibility' attribute before looking for 'visibility'.
191 if (kind == NamedDecl::VisibilityForType) {
192 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
193 return getVisibilityFromAttr(A);
194 }
195 }
196
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000197 // If this declaration has an explicit visibility attribute, use it.
198 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000199 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000200 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000201
202 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
203 // implies visibility(default).
Douglas Gregore8bbc122011-09-02 00:18:52 +0000204 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000205 for (specific_attr_iterator<AvailabilityAttr>
206 A = D->specific_attr_begin<AvailabilityAttr>(),
207 AEnd = D->specific_attr_end<AvailabilityAttr>();
208 A != AEnd; ++A)
209 if ((*A)->getPlatform()->getName().equals("macosx"))
210 return DefaultVisibility;
211 }
212
David Blaikie7a30dc52013-02-21 01:47:18 +0000213 return None;
John McCall457a04e2010-10-22 21:05:15 +0000214}
215
Rafael Espindola2f869a32012-01-14 00:30:36 +0000216static LinkageInfo getLVForType(QualType T) {
217 std::pair<Linkage,Visibility> P = T->getLinkageAndVisibility();
218 return LinkageInfo(P.first, P.second, T->isVisibilityExplicit());
219}
220
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000221/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000222/// template parameter list. For visibility purposes, template
223/// parameters are part of the signature of a template.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000224static LinkageInfo
John McCalldf25c432013-02-16 00:17:33 +0000225getLVForTemplateParameterList(const TemplateParameterList *params) {
226 LinkageInfo LV;
227 for (TemplateParameterList::const_iterator P = params->begin(),
228 PEnd = params->end();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000229 P != PEnd; ++P) {
John McCalldf25c432013-02-16 00:17:33 +0000230
231 // Template type parameters are the most common and never
232 // contribute to visibility, pack or not.
233 if (isa<TemplateTypeParmDecl>(*P))
234 continue;
235
236 // Non-type template parameters can be restricted by the value type, e.g.
237 // template <enum X> class A { ... };
238 // We have to be careful here, though, because we can be dealing with
239 // dependent types.
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000240 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
John McCalldf25c432013-02-16 00:17:33 +0000241 // Handle the non-pack case first.
242 if (!NTTP->isExpandedParameterPack()) {
243 if (!NTTP->getType()->isDependentType()) {
244 LV.merge(getLVForType(NTTP->getType()));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000245 }
246 continue;
247 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000248
John McCalldf25c432013-02-16 00:17:33 +0000249 // Look at all the types in an expanded pack.
250 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
251 QualType type = NTTP->getExpansionType(i);
252 if (!type->isDependentType())
253 LV.merge(getLVForType(type));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000254 }
John McCalldf25c432013-02-16 00:17:33 +0000255 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000256 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000257
John McCalldf25c432013-02-16 00:17:33 +0000258 // Template template parameters can be restricted by their
259 // template parameters, recursively.
260 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
261
262 // Handle the non-pack case first.
263 if (!TTP->isExpandedParameterPack()) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000264 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters()));
John McCalldf25c432013-02-16 00:17:33 +0000265 continue;
266 }
267
268 // Look at all expansions in an expanded pack.
269 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
270 i != n; ++i) {
271 LV.merge(getLVForTemplateParameterList(
272 TTP->getExpansionTemplateParameters(i)));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000273 }
274 }
275
John McCall457a04e2010-10-22 21:05:15 +0000276 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000277}
278
Rafael Espindola19de5612013-01-12 06:42:30 +0000279/// getLVForDecl - Get the linkage and visibility for the given declaration.
John McCalldf25c432013-02-16 00:17:33 +0000280static LinkageInfo getLVForDecl(const NamedDecl *D,
281 LVComputationKind computation);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000282
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000283/// \brief Get the most restrictive linkage for the types and
284/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000285///
286/// Note that we don't take an LVComputationKind because we always
287/// want to honor the visibility of template arguments in the same way.
288static LinkageInfo
289getLVForTemplateArgumentList(ArrayRef<TemplateArgument> args) {
290 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000291
John McCalldf25c432013-02-16 00:17:33 +0000292 for (unsigned i = 0, e = args.size(); i != e; ++i) {
293 const TemplateArgument &arg = args[i];
294 switch (arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000295 case TemplateArgument::Null:
296 case TemplateArgument::Integral:
297 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000298 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000299
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000300 case TemplateArgument::Type:
John McCalldf25c432013-02-16 00:17:33 +0000301 LV.merge(getLVForType(arg.getAsType()));
302 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000303
304 case TemplateArgument::Declaration:
John McCalldf25c432013-02-16 00:17:33 +0000305 if (NamedDecl *ND = dyn_cast<NamedDecl>(arg.getAsDecl())) {
306 assert(!usesTypeVisibility(ND));
307 LV.merge(getLVForDecl(ND, LVForValue));
308 }
309 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +0000310
311 case TemplateArgument::NullPtr:
John McCalldf25c432013-02-16 00:17:33 +0000312 LV.merge(getLVForType(arg.getNullPtrType()));
313 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000314
315 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000316 case TemplateArgument::TemplateExpansion:
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000317 if (TemplateDecl *Template
John McCalldf25c432013-02-16 00:17:33 +0000318 = arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
319 LV.merge(getLVForDecl(Template, LVForValue));
320 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000321
322 case TemplateArgument::Pack:
John McCalldf25c432013-02-16 00:17:33 +0000323 LV.merge(getLVForTemplateArgumentList(arg.getPackAsArray()));
324 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000325 }
John McCalldf25c432013-02-16 00:17:33 +0000326 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000327 }
328
John McCall457a04e2010-10-22 21:05:15 +0000329 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000330}
331
Rafael Espindola2f869a32012-01-14 00:30:36 +0000332static LinkageInfo
John McCalldf25c432013-02-16 00:17:33 +0000333getLVForTemplateArgumentList(const TemplateArgumentList &TArgs) {
334 return getLVForTemplateArgumentList(TArgs.asArray());
John McCall8823c652010-08-13 08:35:10 +0000335}
336
John McCall5f46c482013-02-21 23:42:58 +0000337static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
338 const FunctionTemplateSpecializationInfo *specInfo) {
339 // Include visibility from the template parameters and arguments
340 // only if this is not an explicit instantiation or specialization
341 // with direct explicit visibility. (Implicit instantiations won't
342 // have a direct attribute.)
343 if (!specInfo->isExplicitInstantiationOrSpecialization())
344 return true;
345
346 return !fn->hasAttr<VisibilityAttr>();
347}
348
John McCalldf25c432013-02-16 00:17:33 +0000349/// Merge in template-related linkage and visibility for the given
350/// function template specialization.
351///
352/// We don't need a computation kind here because we can assume
353/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000354///
355/// \return the computation to use for the parent
356static void
357mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
358 const FunctionTemplateSpecializationInfo *specInfo) {
359 bool considerVisibility =
360 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000361
362 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000363 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000364 LinkageInfo tempLV =
365 getLVForTemplateParameterList(temp->getTemplateParameters());
366 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
367
368 // Merge information from the template arguments.
369 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
370 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
371 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000372}
373
John McCall5f46c482013-02-21 23:42:58 +0000374/// Does the given declaration have a direct visibility attribute
375/// that would match the given rules?
376static bool hasDirectVisibilityAttribute(const NamedDecl *D,
377 LVComputationKind computation) {
378 switch (computation) {
379 case LVForType:
380 case LVForExplicitType:
381 if (D->hasAttr<TypeVisibilityAttr>())
382 return true;
383 // fallthrough
384 case LVForValue:
385 case LVForExplicitValue:
386 if (D->hasAttr<VisibilityAttr>())
387 return true;
388 return false;
389 }
390 llvm_unreachable("bad visibility computation kind");
391}
392
John McCalld041a9b2013-02-20 01:54:26 +0000393/// Should we consider visibility associated with the template
394/// arguments and parameters of the given class template specialization?
395static bool shouldConsiderTemplateVisibility(
396 const ClassTemplateSpecializationDecl *spec,
397 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000398 // Include visibility from the template parameters and arguments
399 // only if this is not an explicit instantiation or specialization
400 // with direct explicit visibility (and note that implicit
401 // instantiations won't have a direct attribute).
402 //
403 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000404 // for an explicit specialization when computing the visibility of a
405 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000406 //
407 // This is a bit complex; let's unpack it.
408 //
409 // An explicit class specialization is an independent, top-level
410 // declaration. As such, if it or any of its members has an
411 // explicit visibility attribute, that must directly express the
412 // user's intent, and we should honor it. The same logic applies to
413 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000414
415 // Fast path: if this is not an explicit instantiation or
416 // specialization, we always want to consider template-related
417 // visibility restrictions.
418 if (!spec->isExplicitInstantiationOrSpecialization())
419 return true;
420
421 // This is the 'member thereof' check.
422 if (spec->isExplicitSpecialization() &&
423 hasExplicitVisibilityAlready(computation))
424 return false;
425
John McCall5f46c482013-02-21 23:42:58 +0000426 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000427}
428
429/// Merge in template-related linkage and visibility for the given
430/// class template specialization.
431static void mergeTemplateLV(LinkageInfo &LV,
432 const ClassTemplateSpecializationDecl *spec,
433 LVComputationKind computation) {
434 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000435
436 // Merge information from the template parameters, but ignore
437 // visibility if we're only considering template arguments.
438
John McCalld041a9b2013-02-20 01:54:26 +0000439 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000440 LinkageInfo tempLV =
441 getLVForTemplateParameterList(temp->getTemplateParameters());
442 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000443 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000444
445 // Merge information from the template arguments. We ignore
446 // template-argument visibility if we've got an explicit
447 // instantiation with a visibility attribute.
448 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
449 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
450 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000451}
452
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000453static bool useInlineVisibilityHidden(const NamedDecl *D) {
454 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000455 const LangOptions &Opts = D->getASTContext().getLangOpts();
456 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000457 return false;
458
459 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
460 if (!FD)
461 return false;
462
463 TemplateSpecializationKind TSK = TSK_Undeclared;
464 if (FunctionTemplateSpecializationInfo *spec
465 = FD->getTemplateSpecializationInfo()) {
466 TSK = spec->getTemplateSpecializationKind();
467 } else if (MemberSpecializationInfo *MSI =
468 FD->getMemberSpecializationInfo()) {
469 TSK = MSI->getTemplateSpecializationKind();
470 }
471
472 const FunctionDecl *Def = 0;
473 // InlineVisibilityHidden only applies to definitions, and
474 // isInlined() only gives meaningful answers on definitions
475 // anyway.
476 return TSK != TSK_ExplicitInstantiationDeclaration &&
477 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000478 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000479}
480
Benjamin Kramer3e350262013-02-15 12:30:38 +0000481template <typename T> static bool isInExternCContext(T *D) {
Rafael Espindolaf4187652013-02-14 01:18:37 +0000482 const T *First = D->getFirstDeclaration();
483 return First->getDeclContext()->isExternCContext();
484}
485
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000486static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
John McCalldf25c432013-02-16 00:17:33 +0000487 LVComputationKind computation) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000488 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000489 "Not a name having namespace scope");
490 ASTContext &Context = D->getASTContext();
491
492 // C++ [basic.link]p3:
493 // A name having namespace scope (3.3.6) has internal linkage if it
494 // is the name of
495 // - an object, reference, function or function template that is
496 // explicitly declared static; or,
497 // (This bullet corresponds to C99 6.2.2p3.)
498 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
499 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000500 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000501 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000502
Richard Smithdc0ef452012-10-19 06:37:48 +0000503 // - a non-volatile object or reference that is explicitly declared const
504 // or constexpr and neither explicitly declared extern nor previously
505 // declared to have external linkage; or (there is no equivalent in C99)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000506 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000507 Var->getType().isConstQualified() &&
508 !Var->getType().isVolatileQualified() &&
John McCall8e7d6562010-08-26 03:08:43 +0000509 Var->getStorageClass() != SC_Extern &&
510 Var->getStorageClass() != SC_PrivateExtern) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000511 bool FoundExtern = false;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000512 for (const VarDecl *PrevVar = Var->getPreviousDecl();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000513 PrevVar && !FoundExtern;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000514 PrevVar = PrevVar->getPreviousDecl())
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000515 if (isExternalLinkage(PrevVar->getLinkage()))
Douglas Gregorf73b2822009-11-25 22:24:25 +0000516 FoundExtern = true;
517
518 if (!FoundExtern)
John McCallc273f242010-10-30 11:50:40 +0000519 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000520 }
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000521 if (Var->getStorageClass() == SC_None) {
Douglas Gregorec9fd132012-01-14 16:38:05 +0000522 const VarDecl *PrevVar = Var->getPreviousDecl();
523 for (; PrevVar; PrevVar = PrevVar->getPreviousDecl())
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000524 if (PrevVar->getStorageClass() == SC_PrivateExtern)
525 break;
Eli Friedmana7137bc2012-10-26 23:05:34 +0000526 if (PrevVar)
527 return PrevVar->getLinkageAndVisibility();
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000528 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000529 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000530 // C++ [temp]p4:
531 // A non-member function template can have internal linkage; any
532 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000533 const FunctionDecl *Function = 0;
534 if (const FunctionTemplateDecl *FunTmpl
535 = dyn_cast<FunctionTemplateDecl>(D))
536 Function = FunTmpl->getTemplatedDecl();
537 else
538 Function = cast<FunctionDecl>(D);
539
540 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000541 if (Function->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000542 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000543 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
544 // - a data member of an anonymous union.
545 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
John McCallc273f242010-10-30 11:50:40 +0000546 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000547 }
548
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000549 if (D->isInAnonymousNamespace()) {
550 const VarDecl *Var = dyn_cast<VarDecl>(D);
551 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
Rafael Espindolaf4187652013-02-14 01:18:37 +0000552 if ((!Var || !isInExternCContext(Var)) &&
553 (!Func || !isInExternCContext(Func)))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000554 return LinkageInfo::uniqueExternal();
555 }
John McCallb7139c42010-10-28 04:18:25 +0000556
John McCall457a04e2010-10-22 21:05:15 +0000557 // Set up the defaults.
558
559 // C99 6.2.2p5:
560 // If the declaration of an identifier for an object has file
561 // scope and no storage-class specifier, its linkage is
562 // external.
John McCallc273f242010-10-30 11:50:40 +0000563 LinkageInfo LV;
564
John McCalld041a9b2013-02-20 01:54:26 +0000565 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000566 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000567 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000568 } else {
569 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000570 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000571 for (const DeclContext *DC = D->getDeclContext();
572 !isa<TranslationUnitDecl>(DC);
573 DC = DC->getParent()) {
574 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
575 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000576 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000577 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000578 break;
579 }
580 }
581 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000582
John McCalldf25c432013-02-16 00:17:33 +0000583 // Add in global settings if the above didn't give us direct visibility.
584 if (!LV.visibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000585 // Use global type/value visibility as appropriate.
586 Visibility globalVisibility;
587 if (computation == LVForValue) {
588 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
589 } else {
590 assert(computation == LVForType);
591 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
592 }
593 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000594
595 // If we're paying attention to global visibility, apply
596 // -finline-visibility-hidden if this is an inline method.
597 if (useInlineVisibilityHidden(D))
598 LV.mergeVisibility(HiddenVisibility, true);
599 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000600 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000601
Douglas Gregorf73b2822009-11-25 22:24:25 +0000602 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000603
Douglas Gregorf73b2822009-11-25 22:24:25 +0000604 // A name having namespace scope has external linkage if it is the
605 // name of
606 //
607 // - an object or reference, unless it has internal linkage; or
608 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000609 // GCC applies the following optimization to variables and static
610 // data members, but not to functions:
611 //
John McCall457a04e2010-10-22 21:05:15 +0000612 // Modify the variable's LV by the LV of its type unless this is
613 // C or extern "C". This follows from [basic.link]p9:
614 // A type without linkage shall not be used as the type of a
615 // variable or function with external linkage unless
616 // - the entity has C language linkage, or
617 // - the entity is declared within an unnamed namespace, or
618 // - the entity is not used or is defined in the same
619 // translation unit.
620 // and [basic.link]p10:
621 // ...the types specified by all declarations referring to a
622 // given variable or function shall be identical...
623 // C does not have an equivalent rule.
624 //
John McCall5fe84122010-10-26 04:59:26 +0000625 // Ignore this if we've got an explicit attribute; the user
626 // probably knows what they're doing.
627 //
John McCall457a04e2010-10-22 21:05:15 +0000628 // Note that we don't want to make the variable non-external
629 // because of this, but unique-external linkage suits us.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000630 if (Context.getLangOpts().CPlusPlus &&
Eli Friedman839192f2012-01-15 01:23:58 +0000631 !Var->getDeclContext()->isExternCContext()) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000632 LinkageInfo TypeLV = getLVForType(Var->getType());
633 if (TypeLV.linkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000634 return LinkageInfo::uniqueExternal();
John McCalldf25c432013-02-16 00:17:33 +0000635 if (!LV.visibilityExplicit())
636 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000637 }
638
John McCall23032652010-11-02 18:38:13 +0000639 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000640 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000641
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000642 // Note that Sema::MergeVarDecl already takes care of implementing
643 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
644 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000645
Douglas Gregorf73b2822009-11-25 22:24:25 +0000646 // - a function, unless it has internal linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000647 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000648 // In theory, we can modify the function's LV by the LV of its
649 // type unless it has C linkage (see comment above about variables
650 // for justification). In practice, GCC doesn't do this, so it's
651 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000652
John McCall23032652010-11-02 18:38:13 +0000653 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000654 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000655
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000656 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
657 // merging storage classes and visibility attributes, so we don't have to
658 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000659
John McCallf768aa72011-02-10 06:50:24 +0000660 // In C++, then if the type of the function uses a type with
661 // unique-external linkage, it's not legally usable from outside
662 // this translation unit. However, we should use the C linkage
663 // rules instead for extern "C" declarations.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000664 if (Context.getLangOpts().CPlusPlus &&
Eli Friedman839192f2012-01-15 01:23:58 +0000665 !Function->getDeclContext()->isExternCContext() &&
John McCallf768aa72011-02-10 06:50:24 +0000666 Function->getType()->getLinkage() == UniqueExternalLinkage)
667 return LinkageInfo::uniqueExternal();
668
John McCall5f46c482013-02-21 23:42:58 +0000669 // Consider LV from the template and the template arguments.
670 // We're at file scope, so we do not need to worry about nested
671 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000672 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000673 = Function->getTemplateSpecializationInfo()) {
John McCalldf25c432013-02-16 00:17:33 +0000674 mergeTemplateLV(LV, Function, specInfo);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000675 }
676
Douglas Gregorf73b2822009-11-25 22:24:25 +0000677 // - a named class (Clause 9), or an unnamed class defined in a
678 // typedef declaration in which the class has the typedef name
679 // for linkage purposes (7.1.3); or
680 // - a named enumeration (7.2), or an unnamed enumeration
681 // defined in a typedef declaration in which the enumeration
682 // has the typedef name for linkage purposes (7.1.3); or
John McCall457a04e2010-10-22 21:05:15 +0000683 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
684 // Unnamed tags have no linkage.
Richard Smithdda56e42011-04-15 14:24:37 +0000685 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
John McCallc273f242010-10-30 11:50:40 +0000686 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000687
John McCall457a04e2010-10-22 21:05:15 +0000688 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000689 // linkage of the template and template arguments. We're at file
690 // scope, so we do not need to worry about nested specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000691 if (const ClassTemplateSpecializationDecl *spec
John McCall457a04e2010-10-22 21:05:15 +0000692 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000693 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000694 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000695
696 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000697 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000698 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000699 computation);
John McCallc273f242010-10-30 11:50:40 +0000700 if (!isExternalLinkage(EnumLV.linkage()))
701 return LinkageInfo::none();
702 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000703
704 // - a template, unless it is a function template that has
705 // internal linkage (Clause 14);
John McCall8bc6d5b2011-03-04 10:39:25 +0000706 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000707 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000708 LinkageInfo tempLV =
709 getLVForTemplateParameterList(temp->getTemplateParameters());
710 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
711
Douglas Gregorf73b2822009-11-25 22:24:25 +0000712 // - a namespace (7.3), unless it is declared within an unnamed
713 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000714 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
715 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000716
John McCall457a04e2010-10-22 21:05:15 +0000717 // By extension, we assign external linkage to Objective-C
718 // interfaces.
719 } else if (isa<ObjCInterfaceDecl>(D)) {
720 // fallout
721
722 // Everything not covered here has no linkage.
723 } else {
John McCallc273f242010-10-30 11:50:40 +0000724 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000725 }
726
727 // If we ended up with non-external linkage, visibility should
728 // always be default.
John McCallc273f242010-10-30 11:50:40 +0000729 if (LV.linkage() != ExternalLinkage)
730 return LinkageInfo(LV.linkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000731
John McCall457a04e2010-10-22 21:05:15 +0000732 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000733}
734
John McCalldf25c432013-02-16 00:17:33 +0000735static LinkageInfo getLVForClassMember(const NamedDecl *D,
736 LVComputationKind computation) {
John McCall457a04e2010-10-22 21:05:15 +0000737 // Only certain class members have linkage. Note that fields don't
738 // really have linkage, but it's convenient to say they do for the
739 // purposes of calculating linkage of pointer-to-data-member
740 // template arguments.
John McCall8823c652010-08-13 08:35:10 +0000741 if (!(isa<CXXMethodDecl>(D) ||
742 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000743 isa<FieldDecl>(D) ||
David Blaikie095deba2012-11-14 01:52:05 +0000744 isa<TagDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000745 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000746
John McCall07072662010-11-02 01:45:15 +0000747 LinkageInfo LV;
748
John McCall07072662010-11-02 01:45:15 +0000749 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000750 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000751 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000752 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000753 // If we're paying attention to global visibility, apply
754 // -finline-visibility-hidden if this is an inline method.
755 //
756 // Note that we do this before merging information about
757 // the class visibility.
758 if (!LV.visibilityExplicit() && useInlineVisibilityHidden(D))
759 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000760 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000761
762 // If this class member has an explicit visibility attribute, the only
763 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000764 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000765 LVComputationKind classComputation = computation;
766 if (LV.visibilityExplicit())
767 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000768
John McCall5f46c482013-02-21 23:42:58 +0000769 LinkageInfo classLV =
770 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
771 if (!isExternalLinkage(classLV.linkage()))
John McCallc273f242010-10-30 11:50:40 +0000772 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000773
774 // If the class already has unique-external linkage, we can't improve.
John McCall5f46c482013-02-21 23:42:58 +0000775 if (classLV.linkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000776 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000777
John McCall5f46c482013-02-21 23:42:58 +0000778 // Otherwise, don't merge in classLV yet, because in certain cases
779 // we need to completely ignore the visibility from it.
780
781 // Specifically, if this decl exists and has an explicit attribute.
782 const NamedDecl *explicitSpecSuppressor = 0;
783
John McCall8823c652010-08-13 08:35:10 +0000784 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000785 // If the type of the function uses a type with unique-external
786 // linkage, it's not legally usable from outside this translation unit.
787 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
788 return LinkageInfo::uniqueExternal();
789
John McCall457a04e2010-10-22 21:05:15 +0000790 // If this is a method template specialization, use the linkage for
791 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000792 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000793 = MD->getTemplateSpecializationInfo()) {
John McCalldf25c432013-02-16 00:17:33 +0000794 mergeTemplateLV(LV, MD, spec);
John McCall5f46c482013-02-21 23:42:58 +0000795 if (spec->isExplicitSpecialization()) {
796 explicitSpecSuppressor = MD;
797 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
798 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
799 }
800 } else if (isExplicitMemberSpecialization(MD)) {
801 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000802 }
John McCall457a04e2010-10-22 21:05:15 +0000803
John McCall37bb6c92010-10-29 22:22:43 +0000804 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCallb8c604a2011-06-27 23:06:04 +0000805 if (const ClassTemplateSpecializationDecl *spec
John McCall37bb6c92010-10-29 22:22:43 +0000806 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000807 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000808 if (spec->isExplicitSpecialization()) {
809 explicitSpecSuppressor = spec;
810 } else {
811 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
812 if (isExplicitMemberSpecialization(temp)) {
813 explicitSpecSuppressor = temp->getTemplatedDecl();
814 }
815 }
816 } else if (isExplicitMemberSpecialization(RD)) {
817 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000818 }
819
John McCall37bb6c92010-10-29 22:22:43 +0000820 // Static data members.
821 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCall36cd5cc2010-10-30 09:18:49 +0000822 // Modify the variable's linkage by its type, but ignore the
823 // type's visibility unless it's a definition.
John McCalldf25c432013-02-16 00:17:33 +0000824 LinkageInfo typeLV = getLVForType(VD->getType());
John McCall5f46c482013-02-21 23:42:58 +0000825 LV.mergeMaybeWithVisibility(typeLV,
826 !LV.visibilityExplicit() && !classLV.visibilityExplicit());
827
828 if (isExplicitMemberSpecialization(VD)) {
829 explicitSpecSuppressor = VD;
830 }
John McCalldf25c432013-02-16 00:17:33 +0000831
832 // Template members.
833 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
834 bool considerVisibility =
John McCalld041a9b2013-02-20 01:54:26 +0000835 (!LV.visibilityExplicit() &&
John McCall5f46c482013-02-21 23:42:58 +0000836 !classLV.visibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000837 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000838 LinkageInfo tempLV =
839 getLVForTemplateParameterList(temp->getTemplateParameters());
840 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +0000841
842 if (const RedeclarableTemplateDecl *redeclTemp =
843 dyn_cast<RedeclarableTemplateDecl>(temp)) {
844 if (isExplicitMemberSpecialization(redeclTemp)) {
845 explicitSpecSuppressor = temp->getTemplatedDecl();
846 }
847 }
John McCall37bb6c92010-10-29 22:22:43 +0000848 }
849
John McCall5f46c482013-02-21 23:42:58 +0000850 // We should never be looking for an attribute directly on a template.
851 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
852
853 // If this member is an explicit member specialization, and it has
854 // an explicit attribute, ignore visibility from the parent.
855 bool considerClassVisibility = true;
856 if (explicitSpecSuppressor &&
857 LV.visibilityExplicit() && // optimization: hasDVA() is true only if this
858 classLV.visibility() != DefaultVisibility &&
859 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
860 considerClassVisibility = false;
861 }
862
863 // Finally, merge in information from the class.
864 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +0000865 return LV;
John McCall8823c652010-08-13 08:35:10 +0000866}
867
John McCalld396b972011-02-08 19:01:05 +0000868static void clearLinkageForClass(const CXXRecordDecl *record) {
869 for (CXXRecordDecl::decl_iterator
870 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
871 Decl *child = *i;
872 if (isa<NamedDecl>(child))
Rafael Espindola19de5612013-01-12 06:42:30 +0000873 cast<NamedDecl>(child)->ClearLinkageCache();
John McCalld396b972011-02-08 19:01:05 +0000874 }
875}
876
David Blaikie68e081d2011-12-20 02:48:34 +0000877void NamedDecl::anchor() { }
878
Rafael Espindola19de5612013-01-12 06:42:30 +0000879void NamedDecl::ClearLinkageCache() {
John McCalld396b972011-02-08 19:01:05 +0000880 // Note that we can't skip clearing the linkage of children just
881 // because the parent doesn't have cached linkage: we don't cache
882 // when computing linkage for parent contexts.
883
Rafael Espindola19de5612013-01-12 06:42:30 +0000884 HasCachedLinkage = 0;
John McCalld396b972011-02-08 19:01:05 +0000885
886 // If we're changing the linkage of a class, we need to reset the
887 // linkage of child declarations, too.
888 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
889 clearLinkageForClass(record);
890
Dmitri Gribenkofb04e1b2013-02-03 16:10:26 +0000891 if (ClassTemplateDecl *temp = dyn_cast<ClassTemplateDecl>(this)) {
John McCalld396b972011-02-08 19:01:05 +0000892 // Clear linkage for the template pattern.
893 CXXRecordDecl *record = temp->getTemplatedDecl();
Rafael Espindola19de5612013-01-12 06:42:30 +0000894 record->HasCachedLinkage = 0;
John McCalld396b972011-02-08 19:01:05 +0000895 clearLinkageForClass(record);
896
John McCall83779672011-02-19 02:53:41 +0000897 // We need to clear linkage for specializations, too.
898 for (ClassTemplateDecl::spec_iterator
899 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
Rafael Espindola19de5612013-01-12 06:42:30 +0000900 i->ClearLinkageCache();
John McCalld396b972011-02-08 19:01:05 +0000901 }
John McCall83779672011-02-19 02:53:41 +0000902
903 // Clear cached linkage for function template decls, too.
Dmitri Gribenkofb04e1b2013-02-03 16:10:26 +0000904 if (FunctionTemplateDecl *temp = dyn_cast<FunctionTemplateDecl>(this)) {
Rafael Espindola19de5612013-01-12 06:42:30 +0000905 temp->getTemplatedDecl()->ClearLinkageCache();
John McCall83779672011-02-19 02:53:41 +0000906 for (FunctionTemplateDecl::spec_iterator
907 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
Rafael Espindola19de5612013-01-12 06:42:30 +0000908 i->ClearLinkageCache();
John McCall8f9a4292011-03-22 06:58:49 +0000909 }
John McCall83779672011-02-19 02:53:41 +0000910
John McCalld396b972011-02-08 19:01:05 +0000911}
912
Douglas Gregorbf62d642010-12-06 18:36:25 +0000913Linkage NamedDecl::getLinkage() const {
Richard Smith88581592013-02-12 05:48:23 +0000914 if (HasCachedLinkage)
Rafael Espindola19de5612013-01-12 06:42:30 +0000915 return Linkage(CachedLinkage);
Rafael Espindola19de5612013-01-12 06:42:30 +0000916
John McCalld041a9b2013-02-20 01:54:26 +0000917 // We don't care about visibility here, so ask for the cheapest
918 // possible visibility analysis.
919 CachedLinkage = getLVForDecl(this, LVForExplicitValue).linkage();
Rafael Espindola19de5612013-01-12 06:42:30 +0000920 HasCachedLinkage = 1;
921
922#ifndef NDEBUG
923 verifyLinkage();
924#endif
925
926 return Linkage(CachedLinkage);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000927}
928
John McCallc273f242010-10-30 11:50:40 +0000929LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCalldf25c432013-02-16 00:17:33 +0000930 LVComputationKind computation =
931 (usesTypeVisibility(this) ? LVForType : LVForValue);
932 LinkageInfo LI = getLVForDecl(this, computation);
Rafael Espindola19de5612013-01-12 06:42:30 +0000933 if (HasCachedLinkage) {
934 assert(Linkage(CachedLinkage) == LI.linkage());
935 return LI;
Rafael Espindola54606d52012-12-25 07:31:49 +0000936 }
Rafael Espindola19de5612013-01-12 06:42:30 +0000937 HasCachedLinkage = 1;
938 CachedLinkage = LI.linkage();
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000939
940#ifndef NDEBUG
Rafael Espindola19de5612013-01-12 06:42:30 +0000941 verifyLinkage();
942#endif
943
944 return LI;
945}
946
947void NamedDecl::verifyLinkage() const {
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000948 // In C (because of gnu inline) and in c++ with microsoft extensions an
949 // static can follow an extern, so we can have two decls with different
950 // linkages.
951 const LangOptions &Opts = getASTContext().getLangOpts();
952 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
Rafael Espindola19de5612013-01-12 06:42:30 +0000953 return;
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000954
955 // We have just computed the linkage for this decl. By induction we know
956 // that all other computed linkages match, check that the one we just computed
957 // also does.
958 NamedDecl *D = NULL;
959 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
960 NamedDecl *T = cast<NamedDecl>(*I);
961 if (T == this)
962 continue;
Rafael Espindola19de5612013-01-12 06:42:30 +0000963 if (T->HasCachedLinkage != 0) {
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000964 D = T;
965 break;
966 }
967 }
968 assert(!D || D->CachedLinkage == CachedLinkage);
John McCall033caa52010-10-29 00:29:13 +0000969}
Ted Kremenek926d8602010-04-20 23:15:35 +0000970
David Blaikie05785d12013-02-20 22:23:23 +0000971Optional<Visibility>
John McCalld041a9b2013-02-20 01:54:26 +0000972NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000973 // Use the most recent declaration of a variable.
Rafael Espindola96e68242012-05-16 02:10:38 +0000974 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
David Blaikie05785d12013-02-20 22:23:23 +0000975 if (Optional<Visibility> V = getVisibilityOf(Var, kind))
Rafael Espindola96e68242012-05-16 02:10:38 +0000976 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000977
Rafael Espindola96e68242012-05-16 02:10:38 +0000978 if (Var->isStaticDataMember()) {
979 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
980 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +0000981 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +0000982 }
983
David Blaikie7a30dc52013-02-21 01:47:18 +0000984 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +0000985 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000986 // Use the most recent declaration of a function, and also handle
987 // function template specializations.
988 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
David Blaikie05785d12013-02-20 22:23:23 +0000989 if (Optional<Visibility> V = getVisibilityOf(fn, kind))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000990 return V;
991
992 // 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
1008 // Otherwise, just check the declaration itself first.
David Blaikie05785d12013-02-20 22:23:23 +00001009 if (Optional<Visibility> V = getVisibilityOf(this, kind))
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001010 return V;
1011
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001012 // The visibility of a template is stored in the templated decl.
1013 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(this))
John McCalld041a9b2013-02-20 01:54:26 +00001014 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001015
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001016 // If there wasn't explicit visibility there, and this is a
1017 // specialization of a class template, check for visibility
1018 // on the pattern.
1019 if (const ClassTemplateSpecializationDecl *spec
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001020 = dyn_cast<ClassTemplateSpecializationDecl>(this))
John McCalld041a9b2013-02-20 01:54:26 +00001021 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1022 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001023
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001024 // If this is a member class of a specialization of a class template
1025 // and the corresponding decl has explicit visibility, use that.
1026 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(this)) {
1027 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1028 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001029 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001030 }
1031
David Blaikie7a30dc52013-02-21 01:47:18 +00001032 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001033}
1034
John McCalldf25c432013-02-16 00:17:33 +00001035static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1036 LVComputationKind computation) {
1037 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1038 if (Function->isInAnonymousNamespace() &&
1039 !Function->getDeclContext()->isExternCContext())
1040 return LinkageInfo::uniqueExternal();
1041
1042 // This is a "void f();" which got merged with a file static.
1043 if (Function->getStorageClass() == SC_Static)
1044 return LinkageInfo::internal();
1045
1046 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001047 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001048 if (Optional<Visibility> Vis =
1049 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001050 LV.mergeVisibility(*Vis, true);
1051 }
1052
1053 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1054 // merging storage classes and visibility attributes, so we don't have to
1055 // look at previous decls in here.
1056
1057 return LV;
1058 }
1059
1060 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1061 if (Var->getStorageClassAsWritten() == SC_Extern ||
1062 Var->getStorageClassAsWritten() == SC_PrivateExtern) {
1063 if (Var->isInAnonymousNamespace() &&
1064 !Var->getDeclContext()->isExternCContext())
1065 return LinkageInfo::uniqueExternal();
1066
1067 // This is an "extern int foo;" which got merged with a file static.
1068 if (Var->getStorageClass() == SC_Static)
1069 return LinkageInfo::internal();
1070
1071 LinkageInfo LV;
1072 if (Var->getStorageClass() == SC_PrivateExtern)
1073 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001074 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001075 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001076 LV.mergeVisibility(*Vis, true);
1077 }
1078
1079 // Note that Sema::MergeVarDecl already takes care of implementing
1080 // C99 6.2.2p4 and propagating the visibility attribute, so we don't
1081 // have to do it here.
1082 return LV;
1083 }
1084 }
1085
1086 return LinkageInfo::none();
1087}
1088
1089static LinkageInfo getLVForDecl(const NamedDecl *D,
1090 LVComputationKind computation) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001091 // Objective-C: treat all Objective-C declarations as having external
1092 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001093 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001094 default:
1095 break;
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001096 case Decl::ParmVar:
1097 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001098 case Decl::TemplateTemplateParm: // count these as external
1099 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001100 case Decl::ObjCAtDefsField:
1101 case Decl::ObjCCategory:
1102 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001103 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001104 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001105 case Decl::ObjCMethod:
1106 case Decl::ObjCProperty:
1107 case Decl::ObjCPropertyImpl:
1108 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +00001109 return LinkageInfo::external();
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001110
1111 case Decl::CXXRecord: {
1112 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1113 if (Record->isLambda()) {
1114 if (!Record->getLambdaManglingNumber()) {
1115 // This lambda has no mangling number, so it's internal.
1116 return LinkageInfo::internal();
1117 }
1118
1119 // This lambda has its linkage/visibility determined by its owner.
1120 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
1121 if (Decl *ContextDecl = Record->getLambdaContextDecl()) {
1122 if (isa<ParmVarDecl>(ContextDecl))
1123 DC = ContextDecl->getDeclContext()->getRedeclContext();
1124 else
John McCalldf25c432013-02-16 00:17:33 +00001125 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001126 }
1127
1128 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
John McCalldf25c432013-02-16 00:17:33 +00001129 return getLVForDecl(ND, computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001130
1131 return LinkageInfo::external();
1132 }
1133
1134 break;
1135 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001136 }
1137
Douglas Gregorf73b2822009-11-25 22:24:25 +00001138 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001139 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCalldf25c432013-02-16 00:17:33 +00001140 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001141
1142 // C++ [basic.link]p5:
1143 // In addition, a member function, static data member, a named
1144 // class or enumeration of class scope, or an unnamed class or
1145 // enumeration defined in a class-scope typedef declaration such
1146 // that the class or enumeration has the typedef name for linkage
1147 // purposes (7.1.3), has external linkage if the name of the class
1148 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001149 if (D->getDeclContext()->isRecord())
John McCalldf25c432013-02-16 00:17:33 +00001150 return getLVForClassMember(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001151
1152 // C++ [basic.link]p6:
1153 // The name of a function declared in block scope and the name of
1154 // an object declared by a block scope extern declaration have
1155 // linkage. If there is a visible declaration of an entity with
1156 // linkage having the same name and type, ignoring entities
1157 // declared outside the innermost enclosing namespace scope, the
1158 // block scope declaration declares that same entity and receives
1159 // the linkage of the previous declaration. If there is more than
1160 // one such matching entity, the program is ill-formed. Otherwise,
1161 // if no matching entity is found, the block scope entity receives
1162 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001163 if (D->getDeclContext()->isFunctionOrMethod())
1164 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001165
1166 // C++ [basic.link]p6:
1167 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001168 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001169}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001170
Douglas Gregor2ada0482009-02-04 17:27:36 +00001171std::string NamedDecl::getQualifiedNameAsString() const {
Douglas Gregor78254c82012-03-27 23:34:16 +00001172 return getQualifiedNameAsString(getASTContext().getPrintingPolicy());
Anders Carlsson2fb08242009-09-08 18:24:21 +00001173}
1174
1175std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001176 const DeclContext *Ctx = getDeclContext();
1177
1178 if (Ctx->isFunctionOrMethod())
1179 return getNameAsString();
1180
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001181 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001182 ContextsTy Contexts;
1183
1184 // Collect contexts.
1185 while (Ctx && isa<NamedDecl>(Ctx)) {
1186 Contexts.push_back(Ctx);
1187 Ctx = Ctx->getParent();
1188 };
1189
1190 std::string QualName;
1191 llvm::raw_string_ostream OS(QualName);
1192
1193 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1194 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00001195 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001196 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Douglas Gregor85673582009-05-18 17:01:57 +00001197 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1198 std::string TemplateArgsStr
1199 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001200 TemplateArgs.data(),
1201 TemplateArgs.size(),
Anders Carlsson2fb08242009-09-08 18:24:21 +00001202 P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001203 OS << Spec->getName() << TemplateArgsStr;
1204 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Sam Weinig07d211e2009-12-24 23:15:03 +00001205 if (ND->isAnonymousNamespace())
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001206 OS << "<anonymous namespace>";
Sam Weinig07d211e2009-12-24 23:15:03 +00001207 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001208 OS << *ND;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001209 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1210 if (!RD->getIdentifier())
1211 OS << "<anonymous " << RD->getKindName() << '>';
1212 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001213 OS << *RD;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001214 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Sam Weinigb999f682009-12-28 03:19:38 +00001215 const FunctionProtoType *FT = 0;
1216 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001217 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001218
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001219 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001220 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001221 unsigned NumParams = FD->getNumParams();
1222 for (unsigned i = 0; i < NumParams; ++i) {
1223 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001224 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001225 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001226 }
1227
1228 if (FT->isVariadic()) {
1229 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001230 OS << ", ";
1231 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001232 }
1233 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001234 OS << ')';
1235 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001236 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001237 }
1238 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001239 }
1240
John McCalla2a3f7d2010-03-16 21:48:18 +00001241 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001242 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001243 else
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001244 OS << "<anonymous>";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001245
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001246 return OS.str();
Douglas Gregor2ada0482009-02-04 17:27:36 +00001247}
1248
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001249bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001250 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1251
Douglas Gregor889ceb72009-02-03 19:21:40 +00001252 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1253 // We want to keep it, unless it nominates same namespace.
1254 if (getKind() == Decl::UsingDirective) {
Douglas Gregor12441b32011-02-25 16:33:46 +00001255 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1256 ->getOriginalNamespace() ==
1257 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1258 ->getOriginalNamespace();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001259 }
Mike Stump11289f42009-09-09 15:08:12 +00001260
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001261 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1262 // For function declarations, we keep track of redeclarations.
Douglas Gregorec9fd132012-01-14 16:38:05 +00001263 return FD->getPreviousDecl() == OldD;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001264
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001265 // For function templates, the underlying function declarations are linked.
1266 if (const FunctionTemplateDecl *FunctionTemplate
1267 = dyn_cast<FunctionTemplateDecl>(this))
1268 if (const FunctionTemplateDecl *OldFunctionTemplate
1269 = dyn_cast<FunctionTemplateDecl>(OldD))
1270 return FunctionTemplate->getTemplatedDecl()
1271 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001272
Steve Naroffc4173fa2009-02-22 19:35:57 +00001273 // For method declarations, we keep track of redeclarations.
1274 if (isa<ObjCMethodDecl>(this))
1275 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001276
John McCall9f3059a2009-10-09 21:13:30 +00001277 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1278 return true;
1279
John McCall3f746822009-11-17 05:59:44 +00001280 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1281 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1282 cast<UsingShadowDecl>(OldD)->getTargetDecl();
1283
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001284 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1285 ASTContext &Context = getASTContext();
1286 return Context.getCanonicalNestedNameSpecifier(
1287 cast<UsingDecl>(this)->getQualifier()) ==
1288 Context.getCanonicalNestedNameSpecifier(
1289 cast<UsingDecl>(OldD)->getQualifier());
1290 }
Argyrios Kyrtzidis4b520072010-11-04 08:48:52 +00001291
Douglas Gregorb59643b2012-01-03 23:26:26 +00001292 // A typedef of an Objective-C class type can replace an Objective-C class
1293 // declaration or definition, and vice versa.
1294 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1295 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1296 return true;
1297
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001298 // For non-function declarations, if the declarations are of the
1299 // same kind then this must be a redeclaration, or semantic analysis
1300 // would not have given us the new declaration.
1301 return this->getKind() == OldD->getKind();
1302}
1303
Douglas Gregoreddf4332009-02-24 20:03:32 +00001304bool NamedDecl::hasLinkage() const {
Douglas Gregorf73b2822009-11-25 22:24:25 +00001305 return getLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001306}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001307
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001308NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001309 NamedDecl *ND = this;
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001310 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1311 ND = UD->getTargetDecl();
1312
1313 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1314 return AD->getClassInterface();
1315
1316 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001317}
1318
John McCalla8ae2222010-04-06 21:38:20 +00001319bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001320 if (!isCXXClassMember())
1321 return false;
1322
John McCalla8ae2222010-04-06 21:38:20 +00001323 const NamedDecl *D = this;
1324 if (isa<UsingShadowDecl>(D))
1325 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1326
Francois Pichet783dd6e2010-11-21 06:08:52 +00001327 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001328 return true;
1329 if (isa<CXXMethodDecl>(D))
1330 return cast<CXXMethodDecl>(D)->isInstance();
1331 if (isa<FunctionTemplateDecl>(D))
1332 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
1333 ->getTemplatedDecl())->isInstance();
1334 return false;
1335}
1336
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001337//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001338// DeclaratorDecl Implementation
1339//===----------------------------------------------------------------------===//
1340
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001341template <typename DeclT>
1342static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1343 if (decl->getNumTemplateParameterLists() > 0)
1344 return decl->getTemplateParameterList(0)->getTemplateLoc();
1345 else
1346 return decl->getInnerLocStart();
1347}
1348
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001349SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001350 TypeSourceInfo *TSI = getTypeSourceInfo();
1351 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001352 return SourceLocation();
1353}
1354
Douglas Gregor14454802011-02-25 02:25:35 +00001355void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1356 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001357 // Make sure the extended decl info is allocated.
1358 if (!hasExtInfo()) {
1359 // Save (non-extended) type source info pointer.
1360 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1361 // Allocate external info struct.
1362 DeclInfo = new (getASTContext()) ExtInfo;
1363 // Restore savedTInfo into (extended) decl info.
1364 getExtInfo()->TInfo = savedTInfo;
1365 }
1366 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001367 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001368 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001369 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001370 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001371 if (getExtInfo()->NumTemplParamLists == 0) {
1372 // Save type source info pointer.
1373 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1374 // Deallocate the extended decl info.
1375 getASTContext().Deallocate(getExtInfo());
1376 // Restore savedTInfo into (non-extended) decl info.
1377 DeclInfo = savedTInfo;
1378 }
1379 else
1380 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001381 }
1382 }
1383}
1384
Abramo Bagnara60804e12011-03-18 15:16:37 +00001385void
1386DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1387 unsigned NumTPLists,
1388 TemplateParameterList **TPLists) {
1389 assert(NumTPLists > 0);
1390 // Make sure the extended decl info is allocated.
1391 if (!hasExtInfo()) {
1392 // Save (non-extended) type source info pointer.
1393 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1394 // Allocate external info struct.
1395 DeclInfo = new (getASTContext()) ExtInfo;
1396 // Restore savedTInfo into (extended) decl info.
1397 getExtInfo()->TInfo = savedTInfo;
1398 }
1399 // Set the template parameter lists info.
1400 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1401}
1402
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001403SourceLocation DeclaratorDecl::getOuterLocStart() const {
1404 return getTemplateOrInnerLocStart(this);
1405}
1406
Abramo Bagnaraea947882011-03-08 16:41:52 +00001407namespace {
1408
1409// Helper function: returns true if QT is or contains a type
1410// having a postfix component.
1411bool typeIsPostfix(clang::QualType QT) {
1412 while (true) {
1413 const Type* T = QT.getTypePtr();
1414 switch (T->getTypeClass()) {
1415 default:
1416 return false;
1417 case Type::Pointer:
1418 QT = cast<PointerType>(T)->getPointeeType();
1419 break;
1420 case Type::BlockPointer:
1421 QT = cast<BlockPointerType>(T)->getPointeeType();
1422 break;
1423 case Type::MemberPointer:
1424 QT = cast<MemberPointerType>(T)->getPointeeType();
1425 break;
1426 case Type::LValueReference:
1427 case Type::RValueReference:
1428 QT = cast<ReferenceType>(T)->getPointeeType();
1429 break;
1430 case Type::PackExpansion:
1431 QT = cast<PackExpansionType>(T)->getPattern();
1432 break;
1433 case Type::Paren:
1434 case Type::ConstantArray:
1435 case Type::DependentSizedArray:
1436 case Type::IncompleteArray:
1437 case Type::VariableArray:
1438 case Type::FunctionProto:
1439 case Type::FunctionNoProto:
1440 return true;
1441 }
1442 }
1443}
1444
1445} // namespace
1446
1447SourceRange DeclaratorDecl::getSourceRange() const {
1448 SourceLocation RangeEnd = getLocation();
1449 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1450 if (typeIsPostfix(TInfo->getType()))
1451 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1452 }
1453 return SourceRange(getOuterLocStart(), RangeEnd);
1454}
1455
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001456void
Douglas Gregor20527e22010-06-15 17:44:38 +00001457QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1458 unsigned NumTPLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001459 TemplateParameterList **TPLists) {
1460 assert((NumTPLists == 0 || TPLists != 0) &&
1461 "Empty array of template parameters with positive size!");
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001462
1463 // Free previous template parameters (if any).
1464 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001465 Context.Deallocate(TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001466 TemplParamLists = 0;
1467 NumTemplParamLists = 0;
1468 }
1469 // Set info on matched template parameter lists (if any).
1470 if (NumTPLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001471 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001472 NumTemplParamLists = NumTPLists;
1473 for (unsigned i = NumTPLists; i-- > 0; )
1474 TemplParamLists[i] = TPLists[i];
1475 }
1476}
1477
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001478//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001479// VarDecl Implementation
1480//===----------------------------------------------------------------------===//
1481
Sebastian Redl833ef452010-01-26 22:01:41 +00001482const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1483 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001484 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001485 case SC_Auto: return "auto";
1486 case SC_Extern: return "extern";
1487 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1488 case SC_PrivateExtern: return "__private_extern__";
1489 case SC_Register: return "register";
1490 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001491 }
1492
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001493 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001494}
1495
Abramo Bagnaradff19302011-03-08 08:55:46 +00001496VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1497 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001498 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001499 StorageClass S, StorageClass SCAsWritten) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001500 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
Nuno Lopes394ec982008-12-17 23:39:55 +00001501}
1502
Douglas Gregor72172e92012-01-05 21:55:30 +00001503VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1504 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
1505 return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1506 QualType(), 0, SC_None, SC_None);
1507}
1508
Douglas Gregorbf62d642010-12-06 18:36:25 +00001509void VarDecl::setStorageClass(StorageClass SC) {
1510 assert(isLegalForVariable(SC));
1511 if (getStorageClass() != SC)
Rafael Espindola19de5612013-01-12 06:42:30 +00001512 ClearLinkageCache();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001513
John McCallbeaa11c2011-05-01 02:13:58 +00001514 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001515}
1516
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001517SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001518 if (const Expr *Init = getInit()) {
1519 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001520 // If Init is implicit, ignore its source range and fallback on
1521 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1522 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001523 return SourceRange(getOuterLocStart(), InitEnd);
1524 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001525 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001526}
1527
Rafael Espindola88510672013-01-04 21:18:45 +00001528template<typename T>
Rafael Espindolaf4187652013-02-14 01:18:37 +00001529static LanguageLinkage getLanguageLinkageTemplate(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001530 // C++ [dcl.link]p1: All function types, function names with external linkage,
1531 // and variable names with external linkage have a language linkage.
1532 if (!isExternalLinkage(D.getLinkage()))
1533 return NoLanguageLinkage;
1534
1535 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001536 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001537 ASTContext &Context = D.getASTContext();
1538 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001539 return CLanguageLinkage;
1540
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001541 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1542 // language linkage of the names of class members and the function type of
1543 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001544 const DeclContext *DC = D.getDeclContext();
1545 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001546 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001547
1548 // If the first decl is in an extern "C" context, any other redeclaration
1549 // will have C language linkage. If the first one is not in an extern "C"
1550 // context, we would have reported an error for any other decl being in one.
Rafael Espindola88510672013-01-04 21:18:45 +00001551 const T *First = D.getFirstDeclaration();
Rafael Espindolaf4187652013-02-14 01:18:37 +00001552 if (First->getDeclContext()->isExternCContext())
1553 return CLanguageLinkage;
1554 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001555}
1556
Rafael Espindolaf4187652013-02-14 01:18:37 +00001557LanguageLinkage VarDecl::getLanguageLinkage() const {
1558 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001559}
1560
Sebastian Redl833ef452010-01-26 22:01:41 +00001561VarDecl *VarDecl::getCanonicalDecl() {
1562 return getFirstDeclaration();
1563}
1564
Daniel Dunbar9d355812012-03-09 01:51:51 +00001565VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1566 ASTContext &C) const
1567{
Sebastian Redl35351a92010-01-31 22:27:38 +00001568 // C++ [basic.def]p2:
1569 // A declaration is a definition unless [...] it contains the 'extern'
1570 // specifier or a linkage-specification and neither an initializer [...],
1571 // it declares a static data member in a class declaration [...].
1572 // C++ [temp.expl.spec]p15:
1573 // An explicit specialization of a static data member of a template is a
1574 // definition if the declaration includes an initializer; otherwise, it is
1575 // a declaration.
1576 if (isStaticDataMember()) {
1577 if (isOutOfLine() && (hasInit() ||
1578 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1579 return Definition;
1580 else
1581 return DeclarationOnly;
1582 }
1583 // C99 6.7p5:
1584 // A definition of an identifier is a declaration for that identifier that
1585 // [...] causes storage to be reserved for that object.
1586 // Note: that applies for all non-file-scope objects.
1587 // C99 6.9.2p1:
1588 // If the declaration of an identifier for an object has file scope and an
1589 // initializer, the declaration is an external definition for the identifier
1590 if (hasInit())
1591 return Definition;
1592 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1593 if (hasExternalStorage())
1594 return DeclarationOnly;
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001595
John McCall8e7d6562010-08-26 03:08:43 +00001596 if (getStorageClassAsWritten() == SC_Extern ||
1597 getStorageClassAsWritten() == SC_PrivateExtern) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00001598 for (const VarDecl *PrevVar = getPreviousDecl();
1599 PrevVar; PrevVar = PrevVar->getPreviousDecl()) {
Rafael Espindola7581f322012-12-17 22:23:47 +00001600 if (PrevVar->getLinkage() == InternalLinkage)
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001601 return DeclarationOnly;
1602 }
1603 }
Sebastian Redl35351a92010-01-31 22:27:38 +00001604 // C99 6.9.2p2:
1605 // A declaration of an object that has file scope without an initializer,
1606 // and without a storage class specifier or the scs 'static', constitutes
1607 // a tentative definition.
1608 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001609 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00001610 return TentativeDefinition;
1611
1612 // What's left is (in C, block-scope) declarations without initializers or
1613 // external storage. These are definitions.
1614 return Definition;
1615}
1616
Sebastian Redl35351a92010-01-31 22:27:38 +00001617VarDecl *VarDecl::getActingDefinition() {
1618 DefinitionKind Kind = isThisDeclarationADefinition();
1619 if (Kind != TentativeDefinition)
1620 return 0;
1621
Chris Lattner48eb14d2010-06-14 18:31:46 +00001622 VarDecl *LastTentative = 0;
Sebastian Redl35351a92010-01-31 22:27:38 +00001623 VarDecl *First = getFirstDeclaration();
1624 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1625 I != E; ++I) {
1626 Kind = (*I)->isThisDeclarationADefinition();
1627 if (Kind == Definition)
1628 return 0;
1629 else if (Kind == TentativeDefinition)
1630 LastTentative = *I;
1631 }
1632 return LastTentative;
1633}
1634
1635bool VarDecl::isTentativeDefinitionNow() const {
1636 DefinitionKind Kind = isThisDeclarationADefinition();
1637 if (Kind != TentativeDefinition)
1638 return false;
1639
1640 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1641 if ((*I)->isThisDeclarationADefinition() == Definition)
1642 return false;
1643 }
Sebastian Redl5ca79842010-02-01 20:16:42 +00001644 return true;
Sebastian Redl35351a92010-01-31 22:27:38 +00001645}
1646
Daniel Dunbar9d355812012-03-09 01:51:51 +00001647VarDecl *VarDecl::getDefinition(ASTContext &C) {
Sebastian Redlccdb5ff2010-02-02 17:55:12 +00001648 VarDecl *First = getFirstDeclaration();
1649 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1650 I != E; ++I) {
Daniel Dunbar9d355812012-03-09 01:51:51 +00001651 if ((*I)->isThisDeclarationADefinition(C) == Definition)
Sebastian Redl5ca79842010-02-01 20:16:42 +00001652 return *I;
1653 }
1654 return 0;
1655}
1656
Daniel Dunbar9d355812012-03-09 01:51:51 +00001657VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00001658 DefinitionKind Kind = DeclarationOnly;
1659
1660 const VarDecl *First = getFirstDeclaration();
1661 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001662 I != E; ++I) {
Daniel Dunbar9d355812012-03-09 01:51:51 +00001663 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001664 if (Kind == Definition)
1665 break;
1666 }
John McCall37bb6c92010-10-29 22:22:43 +00001667
1668 return Kind;
1669}
1670
Sebastian Redl5ca79842010-02-01 20:16:42 +00001671const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Sebastian Redl833ef452010-01-26 22:01:41 +00001672 redecl_iterator I = redecls_begin(), E = redecls_end();
1673 while (I != E && !I->getInit())
1674 ++I;
1675
1676 if (I != E) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001677 D = *I;
Sebastian Redl833ef452010-01-26 22:01:41 +00001678 return I->getInit();
1679 }
1680 return 0;
1681}
1682
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001683bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00001684 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001685 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001686
1687 if (!isStaticDataMember())
1688 return false;
1689
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001690 // If this static data member was instantiated from a static data member of
1691 // a class template, check whether that static data member was defined
1692 // out-of-line.
1693 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1694 return VD->isOutOfLine();
1695
1696 return false;
1697}
1698
Douglas Gregor1d957a32009-10-27 18:42:08 +00001699VarDecl *VarDecl::getOutOfLineDefinition() {
1700 if (!isStaticDataMember())
1701 return 0;
1702
1703 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1704 RD != RDEnd; ++RD) {
1705 if (RD->getLexicalDeclContext()->isFileContext())
1706 return *RD;
1707 }
1708
1709 return 0;
1710}
1711
Douglas Gregord5058122010-02-11 01:19:42 +00001712void VarDecl::setInit(Expr *I) {
Sebastian Redl833ef452010-01-26 22:01:41 +00001713 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1714 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00001715 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00001716 }
1717
1718 Init = I;
1719}
1720
Daniel Dunbar9d355812012-03-09 01:51:51 +00001721bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001722 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00001723
Richard Smith35ecb362012-03-02 04:14:40 +00001724 if (!Lang.CPlusPlus)
1725 return false;
1726
1727 // In C++11, any variable of reference type can be used in a constant
1728 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001729 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00001730 return true;
1731
1732 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00001733 // not require the variable to be non-volatile, but we consider this to be a
1734 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00001735 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00001736 return false;
1737
1738 // In C++, const, non-volatile variables of integral or enumeration types
1739 // can be used in constant expressions.
1740 if (getType()->isIntegralOrEnumerationType())
1741 return true;
1742
Richard Smith35ecb362012-03-02 04:14:40 +00001743 // Additionally, in C++11, non-volatile constexpr variables can be used in
1744 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001745 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00001746}
1747
Richard Smithd0b4dd62011-12-19 06:19:21 +00001748/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1749/// form, which contains extra information on the evaluated value of the
1750/// initializer.
1751EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1752 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1753 if (!Eval) {
1754 Stmt *S = Init.get<Stmt *>();
1755 Eval = new (getASTContext()) EvaluatedStmt;
1756 Eval->Value = S;
1757 Init = Eval;
1758 }
1759 return Eval;
1760}
1761
Richard Smithdafff942012-01-14 04:30:29 +00001762APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001763 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00001764 return evaluateValue(Notes);
1765}
1766
1767APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001768 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001769 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1770
1771 // We only produce notes indicating why an initializer is non-constant the
1772 // first time it is evaluated. FIXME: The notes won't always be emitted the
1773 // first time we try evaluation, so might not be produced at all.
1774 if (Eval->WasEvaluated)
Richard Smithdafff942012-01-14 04:30:29 +00001775 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001776
1777 const Expr *Init = cast<Expr>(Eval->Value);
1778 assert(!Init->isValueDependent());
1779
1780 if (Eval->IsEvaluating) {
1781 // FIXME: Produce a diagnostic for self-initialization.
1782 Eval->CheckedICE = true;
1783 Eval->IsICE = false;
Richard Smithdafff942012-01-14 04:30:29 +00001784 return 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001785 }
1786
1787 Eval->IsEvaluating = true;
1788
1789 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1790 this, Notes);
1791
1792 // Ensure the result is an uninitialized APValue if evaluation fails.
1793 if (!Result)
1794 Eval->Evaluated = APValue();
1795
1796 Eval->IsEvaluating = false;
1797 Eval->WasEvaluated = true;
1798
1799 // In C++11, we have determined whether the initializer was a constant
1800 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001801 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001802 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00001803 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00001804 }
1805
Richard Smithdafff942012-01-14 04:30:29 +00001806 return Result ? &Eval->Evaluated : 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001807}
1808
1809bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00001810 // Initializers of weak variables are never ICEs.
1811 if (isWeak())
1812 return false;
1813
Richard Smithd0b4dd62011-12-19 06:19:21 +00001814 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1815 if (Eval->CheckedICE)
1816 // We have already checked whether this subexpression is an
1817 // integral constant expression.
1818 return Eval->IsICE;
1819
1820 const Expr *Init = cast<Expr>(Eval->Value);
1821 assert(!Init->isValueDependent());
1822
1823 // In C++11, evaluate the initializer to check whether it's a constant
1824 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001825 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001826 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001827 evaluateValue(Notes);
1828 return Eval->IsICE;
1829 }
1830
1831 // It's an ICE whether or not the definition we found is
1832 // out-of-line. See DR 721 and the discussion in Clang PR
1833 // 6206 for details.
1834
1835 if (Eval->CheckingICE)
1836 return false;
1837 Eval->CheckingICE = true;
1838
1839 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1840 Eval->CheckingICE = false;
1841 Eval->CheckedICE = true;
1842 return Eval->IsICE;
1843}
1844
Douglas Gregorfe314812011-06-21 17:03:29 +00001845bool VarDecl::extendsLifetimeOfTemporary() const {
Douglas Gregord410c082011-06-21 18:20:46 +00001846 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
Douglas Gregorfe314812011-06-21 17:03:29 +00001847
1848 const Expr *E = getInit();
1849 if (!E)
1850 return false;
1851
1852 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1853 E = Cleanups->getSubExpr();
1854
1855 return isa<MaterializeTemporaryExpr>(E);
1856}
1857
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001858VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001859 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001860 return cast<VarDecl>(MSI->getInstantiatedFrom());
1861
1862 return 0;
1863}
1864
Douglas Gregor3c74d412009-10-14 20:14:33 +00001865TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001866 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001867 return MSI->getTemplateSpecializationKind();
1868
1869 return TSK_Undeclared;
1870}
1871
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001872MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001873 return getASTContext().getInstantiatedFromStaticDataMember(this);
1874}
1875
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001876void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1877 SourceLocation PointOfInstantiation) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001878 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00001879 assert(MSI && "Not an instantiated static data member?");
1880 MSI->setTemplateSpecializationKind(TSK);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001881 if (TSK != TSK_ExplicitSpecialization &&
1882 PointOfInstantiation.isValid() &&
1883 MSI->getPointOfInstantiation().isInvalid())
1884 MSI->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001885}
1886
Sebastian Redl833ef452010-01-26 22:01:41 +00001887//===----------------------------------------------------------------------===//
1888// ParmVarDecl Implementation
1889//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00001890
Sebastian Redl833ef452010-01-26 22:01:41 +00001891ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001892 SourceLocation StartLoc,
1893 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00001894 QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001895 StorageClass S, StorageClass SCAsWritten,
1896 Expr *DefArg) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001897 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001898 S, SCAsWritten, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00001899}
1900
Douglas Gregor72172e92012-01-05 21:55:30 +00001901ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1902 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
1903 return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
1904 0, QualType(), 0, SC_None, SC_None, 0);
1905}
1906
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00001907SourceRange ParmVarDecl::getSourceRange() const {
1908 if (!hasInheritedDefaultArg()) {
1909 SourceRange ArgRange = getDefaultArgRange();
1910 if (ArgRange.isValid())
1911 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1912 }
1913
1914 return DeclaratorDecl::getSourceRange();
1915}
1916
Sebastian Redl833ef452010-01-26 22:01:41 +00001917Expr *ParmVarDecl::getDefaultArg() {
1918 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1919 assert(!hasUninstantiatedDefaultArg() &&
1920 "Default argument is not yet instantiated!");
1921
1922 Expr *Arg = getInit();
John McCall5d413782010-12-06 08:20:24 +00001923 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00001924 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00001925
Sebastian Redl833ef452010-01-26 22:01:41 +00001926 return Arg;
1927}
1928
Sebastian Redl833ef452010-01-26 22:01:41 +00001929SourceRange ParmVarDecl::getDefaultArgRange() const {
1930 if (const Expr *E = getInit())
1931 return E->getSourceRange();
1932
1933 if (hasUninstantiatedDefaultArg())
1934 return getUninstantiatedDefaultArg()->getSourceRange();
1935
1936 return SourceRange();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00001937}
1938
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00001939bool ParmVarDecl::isParameterPack() const {
1940 return isa<PackExpansionType>(getType());
1941}
1942
Ted Kremenek540017e2011-10-06 05:00:56 +00001943void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1944 getASTContext().setParameterIndex(this, parameterIndex);
1945 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1946}
1947
1948unsigned ParmVarDecl::getParameterIndexLarge() const {
1949 return getASTContext().getParameterIndex(this);
1950}
1951
Nuno Lopes394ec982008-12-17 23:39:55 +00001952//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00001953// FunctionDecl Implementation
1954//===----------------------------------------------------------------------===//
1955
Douglas Gregorb11aad82011-02-19 18:51:44 +00001956void FunctionDecl::getNameForDiagnostic(std::string &S,
1957 const PrintingPolicy &Policy,
1958 bool Qualified) const {
1959 NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
1960 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1961 if (TemplateArgs)
1962 S += TemplateSpecializationType::PrintTemplateArgumentList(
1963 TemplateArgs->data(),
1964 TemplateArgs->size(),
1965 Policy);
1966
1967}
1968
Ted Kremenek186a0742010-04-29 16:49:01 +00001969bool FunctionDecl::isVariadic() const {
1970 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1971 return FT->isVariadic();
1972 return false;
1973}
1974
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001975bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1976 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Francois Pichet1c229c02011-04-22 22:18:13 +00001977 if (I->Body || I->IsLateTemplateParsed) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001978 Definition = *I;
1979 return true;
1980 }
1981 }
1982
1983 return false;
1984}
1985
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001986bool FunctionDecl::hasTrivialBody() const
1987{
1988 Stmt *S = getBody();
1989 if (!S) {
1990 // Since we don't have a body for this function, we don't know if it's
1991 // trivial or not.
1992 return false;
1993 }
1994
1995 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
1996 return true;
1997 return false;
1998}
1999
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002000bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
2001 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00002002 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002003 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
2004 return true;
2005 }
2006 }
2007
2008 return false;
2009}
2010
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002011Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Argyrios Kyrtzidis1506d9b2009-07-14 03:20:21 +00002012 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
2013 if (I->Body) {
2014 Definition = *I;
2015 return I->Body.get(getASTContext().getExternalSource());
Francois Pichet1c229c02011-04-22 22:18:13 +00002016 } else if (I->IsLateTemplateParsed) {
2017 Definition = *I;
2018 return 0;
Douglas Gregor89f238c2008-04-21 02:02:58 +00002019 }
2020 }
2021
2022 return 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002023}
2024
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002025void FunctionDecl::setBody(Stmt *B) {
2026 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002027 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002028 EndRangeLoc = B->getLocEnd();
2029}
2030
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002031void FunctionDecl::setPure(bool P) {
2032 IsPure = P;
2033 if (P)
2034 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2035 Parent->markedVirtualFunctionPure();
2036}
2037
Douglas Gregor16618f22009-09-12 00:17:51 +00002038bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002039 const TranslationUnitDecl *tunit =
2040 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2041 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002042 !tunit->getASTContext().getLangOpts().Freestanding &&
John McCall53ffd372011-05-15 17:49:20 +00002043 getIdentifier() &&
2044 getIdentifier()->isStr("main");
2045}
2046
2047bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2048 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2049 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2050 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2051 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2052 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2053
2054 if (isa<CXXRecordDecl>(getDeclContext())) return false;
2055 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
2056
2057 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
2058 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
2059
2060 ASTContext &Context =
2061 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2062 ->getASTContext();
2063
2064 // The result type and first argument type are constant across all
2065 // these operators. The second argument must be exactly void*.
2066 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002067}
2068
Rafael Espindolaf4187652013-02-14 01:18:37 +00002069LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Rafael Espindola6239e052013-01-12 15:27:44 +00002070 // Users expect to be able to write
2071 // extern "C" void *__builtin_alloca (size_t);
2072 // so consider builtins as having C language linkage.
Rafael Espindolac48f7342013-01-12 15:27:43 +00002073 if (getBuiltinID())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002074 return CLanguageLinkage;
Rafael Espindolac48f7342013-01-12 15:27:43 +00002075
Rafael Espindolaf4187652013-02-14 01:18:37 +00002076 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002077}
2078
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002079bool FunctionDecl::isGlobal() const {
2080 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2081 return Method->isStatic();
2082
John McCall8e7d6562010-08-26 03:08:43 +00002083 if (getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002084 return false;
2085
Mike Stump11289f42009-09-09 15:08:12 +00002086 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002087 DC->isNamespace();
2088 DC = DC->getParent()) {
2089 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2090 if (!Namespace->getDeclName())
2091 return false;
2092 break;
2093 }
2094 }
2095
2096 return true;
2097}
2098
Richard Smith10876ef2013-01-17 01:30:42 +00002099bool FunctionDecl::isNoReturn() const {
2100 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
Richard Smithdebc59d2013-01-30 05:45:05 +00002101 hasAttr<C11NoReturnAttr>() ||
Richard Smith10876ef2013-01-17 01:30:42 +00002102 getType()->getAs<FunctionType>()->getNoReturnAttr();
2103}
2104
Sebastian Redl833ef452010-01-26 22:01:41 +00002105void
2106FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2107 redeclarable_base::setPreviousDeclaration(PrevDecl);
2108
2109 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2110 FunctionTemplateDecl *PrevFunTmpl
2111 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
2112 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2113 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
2114 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002115
Axel Naumannfbc7b982011-11-08 18:21:06 +00002116 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002117 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002118}
2119
2120const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
2121 return getFirstDeclaration();
2122}
2123
2124FunctionDecl *FunctionDecl::getCanonicalDecl() {
2125 return getFirstDeclaration();
2126}
2127
Douglas Gregorbf62d642010-12-06 18:36:25 +00002128void FunctionDecl::setStorageClass(StorageClass SC) {
2129 assert(isLegalForFunction(SC));
2130 if (getStorageClass() != SC)
Rafael Espindola19de5612013-01-12 06:42:30 +00002131 ClearLinkageCache();
Douglas Gregorbf62d642010-12-06 18:36:25 +00002132
2133 SClass = SC;
2134}
2135
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002136/// \brief Returns a value indicating whether this function
2137/// corresponds to a builtin function.
2138///
2139/// The function corresponds to a built-in function if it is
2140/// declared at translation scope or within an extern "C" block and
2141/// its name matches with the name of a builtin. The returned value
2142/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002143/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002144/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002145unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002146 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002147 return 0;
2148
2149 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002150 if (!BuiltinID)
2151 return 0;
2152
2153 ASTContext &Context = getASTContext();
Douglas Gregore711f702009-02-14 18:57:46 +00002154 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2155 return BuiltinID;
2156
2157 // This function has the name of a known C library
2158 // function. Determine whether it actually refers to the C library
2159 // function or whether it just has the same name.
2160
Douglas Gregora908e7f2009-02-17 03:23:10 +00002161 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002162 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002163 return 0;
2164
Douglas Gregore711f702009-02-14 18:57:46 +00002165 // If this function is at translation-unit scope and we're not in
2166 // C++, it refers to the C library function.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002167 if (!Context.getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +00002168 getDeclContext()->isTranslationUnit())
2169 return BuiltinID;
2170
2171 // If the function is in an extern "C" linkage specification and is
2172 // not marked "overloadable", it's the real function.
2173 if (isa<LinkageSpecDecl>(getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002174 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
Douglas Gregore711f702009-02-14 18:57:46 +00002175 == LinkageSpecDecl::lang_c &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002176 !getAttr<OverloadableAttr>())
Douglas Gregore711f702009-02-14 18:57:46 +00002177 return BuiltinID;
2178
2179 // Not a builtin
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002180 return 0;
2181}
2182
2183
Chris Lattner47c0d002009-04-25 06:03:53 +00002184/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002185/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002186/// after it has been created.
2187unsigned FunctionDecl::getNumParams() const {
Eli Friedman5c27c4c2012-08-30 22:22:09 +00002188 const FunctionType *FT = getType()->castAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002189 if (isa<FunctionNoProtoType>(FT))
Chris Lattner88f70d62008-03-15 05:43:15 +00002190 return 0;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002191 return cast<FunctionProtoType>(FT)->getNumArgs();
Mike Stump11289f42009-09-09 15:08:12 +00002192
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002193}
2194
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002195void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002196 ArrayRef<ParmVarDecl *> NewParamInfo) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002197 assert(ParamInfo == 0 && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002198 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002199
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002200 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002201 if (!NewParamInfo.empty()) {
2202 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2203 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002204 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002205}
Chris Lattner41943152007-01-25 04:52:46 +00002206
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002207void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
James Molloy6f8780b2012-02-29 10:24:19 +00002208 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2209
2210 if (!NewDecls.empty()) {
2211 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2212 std::copy(NewDecls.begin(), NewDecls.end(), A);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002213 DeclsInPrototypeScope = ArrayRef<NamedDecl *>(A, NewDecls.size());
James Molloy6f8780b2012-02-29 10:24:19 +00002214 }
2215}
2216
Chris Lattner58258242008-04-10 02:22:51 +00002217/// getMinRequiredArguments - Returns the minimum number of arguments
2218/// needed to call this function. This may be fewer than the number of
2219/// function parameters, if some of the parameters have default
Douglas Gregor7825bf32011-01-06 22:09:01 +00002220/// arguments (in C++) or the last parameter is a parameter pack.
Chris Lattner58258242008-04-10 02:22:51 +00002221unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002222 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002223 return getNumParams();
2224
Douglas Gregor7825bf32011-01-06 22:09:01 +00002225 unsigned NumRequiredArgs = getNumParams();
2226
2227 // If the last parameter is a parameter pack, we don't need an argument for
2228 // it.
2229 if (NumRequiredArgs > 0 &&
2230 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
2231 --NumRequiredArgs;
2232
2233 // If this parameter has a default argument, we don't need an argument for
2234 // it.
2235 while (NumRequiredArgs > 0 &&
2236 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
Chris Lattner58258242008-04-10 02:22:51 +00002237 --NumRequiredArgs;
2238
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002239 // We might have parameter packs before the end. These can't be deduced,
2240 // but they can still handle multiple arguments.
2241 unsigned ArgIdx = NumRequiredArgs;
2242 while (ArgIdx > 0) {
2243 if (getParamDecl(ArgIdx - 1)->isParameterPack())
2244 NumRequiredArgs = ArgIdx;
2245
2246 --ArgIdx;
2247 }
2248
Chris Lattner58258242008-04-10 02:22:51 +00002249 return NumRequiredArgs;
2250}
2251
Eli Friedman1b125c32012-02-07 03:50:18 +00002252static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2253 // Only consider file-scope declarations in this test.
2254 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2255 return false;
2256
2257 // Only consider explicit declarations; the presence of a builtin for a
2258 // libcall shouldn't affect whether a definition is externally visible.
2259 if (Redecl->isImplicit())
2260 return false;
2261
2262 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2263 return true; // Not an inline definition
2264
2265 return false;
2266}
2267
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002268/// \brief For a function declaration in C or C++, determine whether this
2269/// declaration causes the definition to be externally visible.
2270///
Eli Friedman1b125c32012-02-07 03:50:18 +00002271/// Specifically, this determines if adding the current declaration to the set
2272/// of redeclarations of the given functions causes
2273/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002274bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2275 assert(!doesThisDeclarationHaveABody() &&
2276 "Must have a declaration without a body.");
2277
2278 ASTContext &Context = getASTContext();
2279
David Blaikiebbafb8a2012-03-11 07:00:24 +00002280 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002281 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2282 // an externally visible definition.
2283 //
2284 // FIXME: What happens if gnu_inline gets added on after the first
2285 // declaration?
2286 if (!isInlineSpecified() || getStorageClassAsWritten() == SC_Extern)
2287 return false;
2288
2289 const FunctionDecl *Prev = this;
2290 bool FoundBody = false;
2291 while ((Prev = Prev->getPreviousDecl())) {
2292 FoundBody |= Prev->Body;
2293
2294 if (Prev->Body) {
2295 // If it's not the case that both 'inline' and 'extern' are
2296 // specified on the definition, then it is always externally visible.
2297 if (!Prev->isInlineSpecified() ||
2298 Prev->getStorageClassAsWritten() != SC_Extern)
2299 return false;
2300 } else if (Prev->isInlineSpecified() &&
2301 Prev->getStorageClassAsWritten() != SC_Extern) {
2302 return false;
2303 }
2304 }
2305 return FoundBody;
2306 }
2307
David Blaikiebbafb8a2012-03-11 07:00:24 +00002308 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002309 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002310
2311 // C99 6.7.4p6:
2312 // [...] If all of the file scope declarations for a function in a
2313 // translation unit include the inline function specifier without extern,
2314 // then the definition in that translation unit is an inline definition.
2315 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002316 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002317 const FunctionDecl *Prev = this;
2318 bool FoundBody = false;
2319 while ((Prev = Prev->getPreviousDecl())) {
2320 FoundBody |= Prev->Body;
2321 if (RedeclForcesDefC99(Prev))
2322 return false;
2323 }
2324 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002325}
2326
Richard Smithf3814ad2013-01-25 00:08:28 +00002327/// \brief For an inline function definition in C, or for a gnu_inline function
2328/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002329///
2330/// Inline function definitions are always available for inlining optimizations.
2331/// However, depending on the language dialect, declaration specifiers, and
2332/// attributes, the definition of an inline function may or may not be
2333/// "externally" visible to other translation units in the program.
2334///
2335/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00002336/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00002337/// inline definition becomes externally visible (C99 6.7.4p6).
2338///
2339/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2340/// definition, we use the GNU semantics for inline, which are nearly the
2341/// opposite of C99 semantics. In particular, "inline" by itself will create
2342/// an externally visible symbol, but "extern inline" will not create an
2343/// externally visible symbol.
2344bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002345 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002346 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00002347 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00002348
David Blaikiebbafb8a2012-03-11 07:00:24 +00002349 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002350 // Note: If you change the logic here, please change
2351 // doesDeclarationForceExternallyVisibleDefinition as well.
2352 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00002353 // If it's not the case that both 'inline' and 'extern' are
2354 // specified on the definition, then this inline definition is
2355 // externally visible.
2356 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
2357 return true;
2358
2359 // If any declaration is 'inline' but not 'extern', then this definition
2360 // is externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002361 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2362 Redecl != RedeclEnd;
2363 ++Redecl) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00002364 if (Redecl->isInlineSpecified() &&
2365 Redecl->getStorageClassAsWritten() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00002366 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00002367 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00002368
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002369 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002370 }
Eli Friedman1b125c32012-02-07 03:50:18 +00002371
Richard Smithf3814ad2013-01-25 00:08:28 +00002372 // The rest of this function is C-only.
2373 assert(!Context.getLangOpts().CPlusPlus &&
2374 "should not use C inline rules in C++");
2375
Douglas Gregor299d76e2009-09-13 07:46:26 +00002376 // C99 6.7.4p6:
2377 // [...] If all of the file scope declarations for a function in a
2378 // translation unit include the inline function specifier without extern,
2379 // then the definition in that translation unit is an inline definition.
2380 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2381 Redecl != RedeclEnd;
2382 ++Redecl) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002383 if (RedeclForcesDefC99(*Redecl))
2384 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002385 }
2386
2387 // C99 6.7.4p6:
2388 // An inline definition does not provide an external definition for the
2389 // function, and does not forbid an external definition in another
2390 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002391 return false;
2392}
2393
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002394/// getOverloadedOperator - Which C++ overloaded operator this
2395/// function represents, if any.
2396OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00002397 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2398 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002399 else
2400 return OO_None;
2401}
2402
Alexis Huntc88db062010-01-13 09:01:02 +00002403/// getLiteralIdentifier - The literal suffix identifier this function
2404/// represents, if any.
2405const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2406 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2407 return getDeclName().getCXXLiteralIdentifier();
2408 else
2409 return 0;
2410}
2411
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002412FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2413 if (TemplateOrSpecialization.isNull())
2414 return TK_NonTemplate;
2415 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2416 return TK_FunctionTemplate;
2417 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2418 return TK_MemberSpecialization;
2419 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2420 return TK_FunctionTemplateSpecialization;
2421 if (TemplateOrSpecialization.is
2422 <DependentFunctionTemplateSpecializationInfo*>())
2423 return TK_DependentFunctionTemplateSpecialization;
2424
David Blaikie83d382b2011-09-23 05:06:16 +00002425 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002426}
2427
Douglas Gregord801b062009-10-07 23:56:10 +00002428FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002429 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00002430 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2431
2432 return 0;
2433}
2434
2435void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002436FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2437 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00002438 TemplateSpecializationKind TSK) {
2439 assert(TemplateOrSpecialization.isNull() &&
2440 "Member function is already a specialization");
2441 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002442 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00002443 TemplateOrSpecialization = Info;
2444}
2445
Douglas Gregorafca3b42009-10-27 20:53:28 +00002446bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00002447 // If the function is invalid, it can't be implicitly instantiated.
2448 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00002449 return false;
2450
2451 switch (getTemplateSpecializationKind()) {
2452 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00002453 case TSK_ExplicitInstantiationDefinition:
2454 return false;
2455
2456 case TSK_ImplicitInstantiation:
2457 return true;
2458
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002459 // It is possible to instantiate TSK_ExplicitSpecialization kind
2460 // if the FunctionDecl has a class scope specialization pattern.
2461 case TSK_ExplicitSpecialization:
2462 return getClassScopeSpecializationPattern() != 0;
2463
Douglas Gregorafca3b42009-10-27 20:53:28 +00002464 case TSK_ExplicitInstantiationDeclaration:
2465 // Handled below.
2466 break;
2467 }
2468
2469 // Find the actual template from which we will instantiate.
2470 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002471 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00002472 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002473 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00002474
2475 // C++0x [temp.explicit]p9:
2476 // Except for inline functions, other explicit instantiation declarations
2477 // have the effect of suppressing the implicit instantiation of the entity
2478 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002479 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00002480 return true;
2481
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002482 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00002483}
2484
2485bool FunctionDecl::isTemplateInstantiation() const {
2486 switch (getTemplateSpecializationKind()) {
2487 case TSK_Undeclared:
2488 case TSK_ExplicitSpecialization:
2489 return false;
2490 case TSK_ImplicitInstantiation:
2491 case TSK_ExplicitInstantiationDeclaration:
2492 case TSK_ExplicitInstantiationDefinition:
2493 return true;
2494 }
2495 llvm_unreachable("All TSK values handled.");
2496}
Douglas Gregorafca3b42009-10-27 20:53:28 +00002497
2498FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002499 // Handle class scope explicit specialization special case.
2500 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2501 return getClassScopeSpecializationPattern();
2502
Douglas Gregorafca3b42009-10-27 20:53:28 +00002503 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2504 while (Primary->getInstantiatedFromMemberTemplate()) {
2505 // If we have hit a point where the user provided a specialization of
2506 // this template, we're done looking.
2507 if (Primary->isMemberSpecialization())
2508 break;
2509
2510 Primary = Primary->getInstantiatedFromMemberTemplate();
2511 }
2512
2513 return Primary->getTemplatedDecl();
2514 }
2515
2516 return getInstantiatedFromMemberFunction();
2517}
2518
Douglas Gregor70d83e22009-06-29 17:30:29 +00002519FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00002520 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002521 = TemplateOrSpecialization
2522 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00002523 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00002524 }
2525 return 0;
2526}
2527
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002528FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2529 return getASTContext().getClassScopeSpecializationPattern(this);
2530}
2531
Douglas Gregor70d83e22009-06-29 17:30:29 +00002532const TemplateArgumentList *
2533FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00002534 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00002535 = TemplateOrSpecialization
2536 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00002537 return Info->TemplateArguments;
2538 }
2539 return 0;
2540}
2541
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00002542const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002543FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2544 if (FunctionTemplateSpecializationInfo *Info
2545 = TemplateOrSpecialization
2546 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2547 return Info->TemplateArgumentsAsWritten;
2548 }
2549 return 0;
2550}
2551
Mike Stump11289f42009-09-09 15:08:12 +00002552void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002553FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2554 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002555 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002556 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002557 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00002558 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2559 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002560 assert(TSK != TSK_Undeclared &&
2561 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00002562 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002563 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002564 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00002565 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2566 TemplateArgs,
2567 TemplateArgsAsWritten,
2568 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002569 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00002570 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002571}
2572
John McCallb9c78482010-04-08 09:05:18 +00002573void
2574FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2575 const UnresolvedSetImpl &Templates,
2576 const TemplateArgumentListInfo &TemplateArgs) {
2577 assert(TemplateOrSpecialization.isNull());
2578 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2579 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall900d9802010-04-13 22:18:28 +00002580 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallb9c78482010-04-08 09:05:18 +00002581 void *Buffer = Context.Allocate(Size);
2582 DependentFunctionTemplateSpecializationInfo *Info =
2583 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2584 TemplateArgs);
2585 TemplateOrSpecialization = Info;
2586}
2587
2588DependentFunctionTemplateSpecializationInfo::
2589DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2590 const TemplateArgumentListInfo &TArgs)
2591 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2592
2593 d.NumTemplates = Ts.size();
2594 d.NumArgs = TArgs.size();
2595
2596 FunctionTemplateDecl **TsArray =
2597 const_cast<FunctionTemplateDecl**>(getTemplates());
2598 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2599 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2600
2601 TemplateArgumentLoc *ArgsArray =
2602 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2603 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2604 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2605}
2606
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002607TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00002608 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002609 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00002610 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00002611 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00002612 if (FTSInfo)
2613 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00002614
Douglas Gregord801b062009-10-07 23:56:10 +00002615 MemberSpecializationInfo *MSInfo
2616 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2617 if (MSInfo)
2618 return MSInfo->getTemplateSpecializationKind();
2619
2620 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002621}
2622
Mike Stump11289f42009-09-09 15:08:12 +00002623void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002624FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2625 SourceLocation PointOfInstantiation) {
2626 if (FunctionTemplateSpecializationInfo *FTSInfo
2627 = TemplateOrSpecialization.dyn_cast<
2628 FunctionTemplateSpecializationInfo*>()) {
2629 FTSInfo->setTemplateSpecializationKind(TSK);
2630 if (TSK != TSK_ExplicitSpecialization &&
2631 PointOfInstantiation.isValid() &&
2632 FTSInfo->getPointOfInstantiation().isInvalid())
2633 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2634 } else if (MemberSpecializationInfo *MSInfo
2635 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2636 MSInfo->setTemplateSpecializationKind(TSK);
2637 if (TSK != TSK_ExplicitSpecialization &&
2638 PointOfInstantiation.isValid() &&
2639 MSInfo->getPointOfInstantiation().isInvalid())
2640 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2641 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002642 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002643}
2644
2645SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00002646 if (FunctionTemplateSpecializationInfo *FTSInfo
2647 = TemplateOrSpecialization.dyn_cast<
2648 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002649 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00002650 else if (MemberSpecializationInfo *MSInfo
2651 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002652 return MSInfo->getPointOfInstantiation();
2653
2654 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00002655}
2656
Douglas Gregor6411b922009-09-11 20:15:17 +00002657bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002658 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00002659 return true;
2660
2661 // If this function was instantiated from a member function of a
2662 // class template, check whether that member function was defined out-of-line.
2663 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2664 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002665 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002666 return Definition->isOutOfLine();
2667 }
2668
2669 // If this function was instantiated from a function template,
2670 // check whether that function template was defined out-of-line.
2671 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2672 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002673 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002674 return Definition->isOutOfLine();
2675 }
2676
2677 return false;
2678}
2679
Abramo Bagnaraea947882011-03-08 16:41:52 +00002680SourceRange FunctionDecl::getSourceRange() const {
2681 return SourceRange(getOuterLocStart(), EndRangeLoc);
2682}
2683
Anna Zaks28db7ce2012-01-18 02:45:01 +00002684unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00002685 IdentifierInfo *FnInfo = getIdentifier();
2686
2687 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00002688 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002689
2690 // Builtin handling.
2691 switch (getBuiltinID()) {
2692 case Builtin::BI__builtin_memset:
2693 case Builtin::BI__builtin___memset_chk:
2694 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00002695 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00002696
2697 case Builtin::BI__builtin_memcpy:
2698 case Builtin::BI__builtin___memcpy_chk:
2699 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00002700 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002701
2702 case Builtin::BI__builtin_memmove:
2703 case Builtin::BI__builtin___memmove_chk:
2704 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00002705 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00002706
2707 case Builtin::BIstrlcpy:
Anna Zaks22122702012-01-17 00:37:07 +00002708 return Builtin::BIstrlcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002709 case Builtin::BIstrlcat:
Anna Zaks22122702012-01-17 00:37:07 +00002710 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00002711
2712 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00002713 case Builtin::BImemcmp:
2714 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002715
2716 case Builtin::BI__builtin_strncpy:
2717 case Builtin::BI__builtin___strncpy_chk:
2718 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00002719 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002720
2721 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00002722 case Builtin::BIstrncmp:
2723 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002724
2725 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00002726 case Builtin::BIstrncasecmp:
2727 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002728
2729 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00002730 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00002731 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00002732 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00002733
2734 case Builtin::BI__builtin_strndup:
2735 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00002736 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00002737
Anna Zaks314cd092012-02-01 19:08:57 +00002738 case Builtin::BI__builtin_strlen:
2739 case Builtin::BIstrlen:
2740 return Builtin::BIstrlen;
2741
Anna Zaks201d4892012-01-13 21:52:01 +00002742 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00002743 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00002744 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00002745 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00002746 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00002747 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002748 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00002749 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00002750 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002751 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002752 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00002753 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002754 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002755 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002756 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002757 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002758 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00002759 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00002760 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00002761 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00002762 else if (FnInfo->isStr("strlen"))
2763 return Builtin::BIstrlen;
Anna Zaks201d4892012-01-13 21:52:01 +00002764 }
2765 break;
2766 }
Anna Zaks22122702012-01-17 00:37:07 +00002767 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002768}
2769
Chris Lattner59a25942008-03-31 00:36:02 +00002770//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002771// FieldDecl Implementation
2772//===----------------------------------------------------------------------===//
2773
Jay Foad39c79802011-01-12 09:06:06 +00002774FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002775 SourceLocation StartLoc, SourceLocation IdLoc,
2776 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00002777 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00002778 InClassInitStyle InitStyle) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002779 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +00002780 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00002781}
2782
Douglas Gregor72172e92012-01-05 21:55:30 +00002783FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2784 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
2785 return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
Richard Smith2b013182012-06-10 03:12:00 +00002786 0, QualType(), 0, 0, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00002787}
2788
Sebastian Redl833ef452010-01-26 22:01:41 +00002789bool FieldDecl::isAnonymousStructOrUnion() const {
2790 if (!isImplicit() || getDeclName())
2791 return false;
2792
2793 if (const RecordType *Record = getType()->getAs<RecordType>())
2794 return Record->getDecl()->isAnonymousStructOrUnion();
2795
2796 return false;
2797}
2798
Richard Smithcaf33902011-10-10 18:28:20 +00002799unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2800 assert(isBitField() && "not a bitfield");
2801 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2802 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2803}
2804
John McCall4e819612011-01-20 07:57:12 +00002805unsigned FieldDecl::getFieldIndex() const {
2806 if (CachedFieldIndex) return CachedFieldIndex - 1;
2807
Richard Smithd62306a2011-11-10 06:34:14 +00002808 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002809 const RecordDecl *RD = getParent();
2810 const FieldDecl *LastFD = 0;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00002811 bool IsMsStruct = RD->isMsStruct(getASTContext());
Richard Smithd62306a2011-11-10 06:34:14 +00002812
2813 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2814 I != E; ++I, ++Index) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00002815 I->CachedFieldIndex = Index + 1;
John McCall4e819612011-01-20 07:57:12 +00002816
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002817 if (IsMsStruct) {
2818 // Zero-length bitfields following non-bitfield members are ignored.
David Blaikie40ed2972012-06-06 20:45:41 +00002819 if (getASTContext().ZeroBitfieldFollowsNonBitfield(*I, LastFD)) {
Richard Smithd62306a2011-11-10 06:34:14 +00002820 --Index;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002821 continue;
2822 }
David Blaikie40ed2972012-06-06 20:45:41 +00002823 LastFD = *I;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002824 }
John McCall4e819612011-01-20 07:57:12 +00002825 }
2826
Richard Smithd62306a2011-11-10 06:34:14 +00002827 assert(CachedFieldIndex && "failed to find field in parent");
2828 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00002829}
2830
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002831SourceRange FieldDecl::getSourceRange() const {
Abramo Bagnaraff371ac2011-08-05 08:02:55 +00002832 if (const Expr *E = InitializerOrBitWidth.getPointer())
2833 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00002834 return DeclaratorDecl::getSourceRange();
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002835}
2836
Abramo Bagnarab1cdde72012-07-02 20:35:48 +00002837void FieldDecl::setBitWidth(Expr *Width) {
2838 assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
2839 "bit width or initializer already set");
2840 InitializerOrBitWidth.setPointer(Width);
2841}
2842
Richard Smith938f40b2011-06-11 17:19:42 +00002843void FieldDecl::setInClassInitializer(Expr *Init) {
Richard Smith2b013182012-06-10 03:12:00 +00002844 assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
Richard Smith938f40b2011-06-11 17:19:42 +00002845 "bit width or initializer already set");
2846 InitializerOrBitWidth.setPointer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00002847}
2848
Sebastian Redl833ef452010-01-26 22:01:41 +00002849//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002850// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00002851//===----------------------------------------------------------------------===//
2852
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002853SourceLocation TagDecl::getOuterLocStart() const {
2854 return getTemplateOrInnerLocStart(this);
2855}
2856
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002857SourceRange TagDecl::getSourceRange() const {
2858 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002859 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002860}
2861
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002862TagDecl* TagDecl::getCanonicalDecl() {
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002863 return getFirstDeclaration();
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002864}
2865
Richard Smithdda56e42011-04-15 14:24:37 +00002866void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2867 TypedefNameDeclOrQualifier = TDD;
Douglas Gregora72a4e32010-05-19 18:39:18 +00002868 if (TypeForDecl)
Rafael Espindola19de5612013-01-12 06:42:30 +00002869 const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
2870 ClearLinkageCache();
Douglas Gregora72a4e32010-05-19 18:39:18 +00002871}
2872
Douglas Gregordee1be82009-01-17 00:42:38 +00002873void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002874 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00002875
David Blaikie095deba2012-11-14 01:52:05 +00002876 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
John McCall67da35c2010-02-04 22:26:26 +00002877 struct CXXRecordDecl::DefinitionData *Data =
2878 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
John McCall93cc7322010-03-26 21:56:38 +00002879 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2880 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00002881 }
Douglas Gregordee1be82009-01-17 00:42:38 +00002882}
2883
2884void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00002885 assert((!isa<CXXRecordDecl>(this) ||
2886 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2887 "definition completed but not started");
2888
John McCallf937c022011-10-07 06:10:15 +00002889 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002890 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00002891
2892 if (ASTMutationListener *L = getASTMutationListener())
2893 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00002894}
2895
John McCallf937c022011-10-07 06:10:15 +00002896TagDecl *TagDecl::getDefinition() const {
2897 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002898 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002899
2900 // If it's possible for us to have an out-of-date definition, check now.
2901 if (MayHaveOutOfDateDef) {
2902 if (IdentifierInfo *II = getIdentifier()) {
2903 if (II->isOutOfDate()) {
2904 updateOutOfDate(*II);
2905 }
2906 }
2907 }
2908
Andrew Trickba266ee2010-10-19 21:54:32 +00002909 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2910 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00002911
2912 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002913 R != REnd; ++R)
John McCallf937c022011-10-07 06:10:15 +00002914 if (R->isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002915 return *R;
Mike Stump11289f42009-09-09 15:08:12 +00002916
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002917 return 0;
Ted Kremenek21475702008-09-05 17:16:31 +00002918}
2919
Douglas Gregor14454802011-02-25 02:25:35 +00002920void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2921 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00002922 // Make sure the extended qualifier info is allocated.
2923 if (!hasExtInfo())
Richard Smithdda56e42011-04-15 14:24:37 +00002924 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00002925 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00002926 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002927 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00002928 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00002929 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00002930 if (getExtInfo()->NumTemplParamLists == 0) {
2931 getASTContext().Deallocate(getExtInfo());
Richard Smithdda56e42011-04-15 14:24:37 +00002932 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002933 }
2934 else
2935 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00002936 }
2937 }
2938}
2939
Abramo Bagnara60804e12011-03-18 15:16:37 +00002940void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2941 unsigned NumTPLists,
2942 TemplateParameterList **TPLists) {
2943 assert(NumTPLists > 0);
2944 // Make sure the extended decl info is allocated.
2945 if (!hasExtInfo())
2946 // Allocate external info struct.
Richard Smithdda56e42011-04-15 14:24:37 +00002947 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002948 // Set the template parameter lists info.
2949 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2950}
2951
Ted Kremenek21475702008-09-05 17:16:31 +00002952//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002953// EnumDecl Implementation
2954//===----------------------------------------------------------------------===//
2955
David Blaikie68e081d2011-12-20 02:48:34 +00002956void EnumDecl::anchor() { }
2957
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002958EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2959 SourceLocation StartLoc, SourceLocation IdLoc,
2960 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002961 EnumDecl *PrevDecl, bool IsScoped,
2962 bool IsScopedUsingClassTag, bool IsFixed) {
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002963 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002964 IsScoped, IsScopedUsingClassTag, IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002965 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00002966 C.getTypeDeclType(Enum, PrevDecl);
2967 return Enum;
2968}
2969
Douglas Gregor72172e92012-01-05 21:55:30 +00002970EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2971 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002972 EnumDecl *Enum = new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(),
2973 0, 0, false, false, false);
2974 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
2975 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00002976}
2977
Douglas Gregord5058122010-02-11 01:19:42 +00002978void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00002979 QualType NewPromotionType,
2980 unsigned NumPositiveBits,
2981 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00002982 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00002983 if (!IntegerType)
2984 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00002985 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00002986 setNumPositiveBits(NumPositiveBits);
2987 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00002988 TagDecl::completeDefinition();
2989}
2990
Richard Smith7d137e32012-03-23 03:33:32 +00002991TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
2992 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2993 return MSI->getTemplateSpecializationKind();
2994
2995 return TSK_Undeclared;
2996}
2997
2998void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2999 SourceLocation PointOfInstantiation) {
3000 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3001 assert(MSI && "Not an instantiated member enumeration?");
3002 MSI->setTemplateSpecializationKind(TSK);
3003 if (TSK != TSK_ExplicitSpecialization &&
3004 PointOfInstantiation.isValid() &&
3005 MSI->getPointOfInstantiation().isInvalid())
3006 MSI->setPointOfInstantiation(PointOfInstantiation);
3007}
3008
Richard Smith4b38ded2012-03-14 23:13:10 +00003009EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3010 if (SpecializationInfo)
3011 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3012
3013 return 0;
3014}
3015
3016void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3017 TemplateSpecializationKind TSK) {
3018 assert(!SpecializationInfo && "Member enum is already a specialization");
3019 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3020}
3021
Sebastian Redl833ef452010-01-26 22:01:41 +00003022//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003023// RecordDecl Implementation
3024//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003025
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003026RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
3027 SourceLocation StartLoc, SourceLocation IdLoc,
3028 IdentifierInfo *Id, RecordDecl *PrevDecl)
3029 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003030 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003031 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003032 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00003033 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003034 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00003035 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003036}
3037
Jay Foad39c79802011-01-12 09:06:06 +00003038RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003039 SourceLocation StartLoc, SourceLocation IdLoc,
3040 IdentifierInfo *Id, RecordDecl* PrevDecl) {
3041 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
3042 PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003043 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3044
Ted Kremenek21475702008-09-05 17:16:31 +00003045 C.getTypeDeclType(R, PrevDecl);
3046 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003047}
3048
Douglas Gregor72172e92012-01-05 21:55:30 +00003049RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
3050 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003051 RecordDecl *R = new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
3052 SourceLocation(), 0, 0);
3053 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3054 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003055}
3056
Douglas Gregordfcad112009-03-25 15:59:44 +00003057bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003058 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003059 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3060}
3061
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003062RecordDecl::field_iterator RecordDecl::field_begin() const {
3063 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3064 LoadFieldsFromExternalStorage();
3065
3066 return field_iterator(decl_iterator(FirstDecl));
3067}
3068
Douglas Gregorb11aad82011-02-19 18:51:44 +00003069/// completeDefinition - Notes that the definition of this type is now
3070/// complete.
3071void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003072 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003073 TagDecl::completeDefinition();
3074}
3075
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003076/// isMsStruct - Get whether or not this record uses ms_struct layout.
3077/// This which can be turned on with an attribute, pragma, or the
3078/// -mms-bitfields command-line option.
3079bool RecordDecl::isMsStruct(const ASTContext &C) const {
3080 return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3081}
3082
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003083static bool isFieldOrIndirectField(Decl::Kind K) {
3084 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3085}
3086
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003087void RecordDecl::LoadFieldsFromExternalStorage() const {
3088 ExternalASTSource *Source = getASTContext().getExternalSource();
3089 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3090
3091 // Notify that we have a RecordDecl doing some initialization.
3092 ExternalASTSource::Deserializing TheFields(Source);
3093
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003094 SmallVector<Decl*, 64> Decls;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003095 LoadedFieldsFromExternalStorage = true;
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003096 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3097 Decls)) {
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003098 case ELR_Success:
3099 break;
3100
3101 case ELR_AlreadyLoaded:
3102 case ELR_Failure:
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003103 return;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003104 }
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003105
3106#ifndef NDEBUG
3107 // Check that all decls we got were FieldDecls.
3108 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003109 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003110#endif
3111
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003112 if (Decls.empty())
3113 return;
3114
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003115 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
3116 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003117}
3118
Steve Naroff415d3d52008-10-08 17:01:13 +00003119//===----------------------------------------------------------------------===//
3120// BlockDecl Implementation
3121//===----------------------------------------------------------------------===//
3122
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003123void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Steve Naroffc4b30e52009-03-13 16:56:44 +00003124 assert(ParamInfo == 0 && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00003125
Steve Naroffc4b30e52009-03-13 16:56:44 +00003126 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003127 if (!NewParamInfo.empty()) {
3128 NumParams = NewParamInfo.size();
3129 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3130 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003131 }
3132}
3133
John McCall351762c2011-02-07 10:33:21 +00003134void BlockDecl::setCaptures(ASTContext &Context,
3135 const Capture *begin,
3136 const Capture *end,
3137 bool capturesCXXThis) {
John McCallc63de662011-02-02 13:00:07 +00003138 CapturesCXXThis = capturesCXXThis;
3139
3140 if (begin == end) {
John McCall351762c2011-02-07 10:33:21 +00003141 NumCaptures = 0;
3142 Captures = 0;
John McCallc63de662011-02-02 13:00:07 +00003143 return;
3144 }
3145
John McCall351762c2011-02-07 10:33:21 +00003146 NumCaptures = end - begin;
3147
3148 // Avoid new Capture[] because we don't want to provide a default
3149 // constructor.
3150 size_t allocationSize = NumCaptures * sizeof(Capture);
3151 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3152 memcpy(buffer, begin, allocationSize);
3153 Captures = static_cast<Capture*>(buffer);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003154}
Sebastian Redl833ef452010-01-26 22:01:41 +00003155
John McCallce45f882011-06-15 22:51:16 +00003156bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3157 for (capture_const_iterator
3158 i = capture_begin(), e = capture_end(); i != e; ++i)
3159 // Only auto vars can be captured, so no redeclaration worries.
3160 if (i->getVariable() == variable)
3161 return true;
3162
3163 return false;
3164}
3165
Douglas Gregor70226da2010-12-21 16:27:07 +00003166SourceRange BlockDecl::getSourceRange() const {
3167 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3168}
Sebastian Redl833ef452010-01-26 22:01:41 +00003169
3170//===----------------------------------------------------------------------===//
3171// Other Decl Allocation/Deallocation Method Implementations
3172//===----------------------------------------------------------------------===//
3173
David Blaikie68e081d2011-12-20 02:48:34 +00003174void TranslationUnitDecl::anchor() { }
3175
Sebastian Redl833ef452010-01-26 22:01:41 +00003176TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
3177 return new (C) TranslationUnitDecl(C);
3178}
3179
David Blaikie68e081d2011-12-20 02:48:34 +00003180void LabelDecl::anchor() { }
3181
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003182LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003183 SourceLocation IdentL, IdentifierInfo *II) {
3184 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
3185}
3186
3187LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3188 SourceLocation IdentL, IdentifierInfo *II,
3189 SourceLocation GnuLabelL) {
3190 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
3191 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003192}
3193
Douglas Gregor72172e92012-01-05 21:55:30 +00003194LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3195 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
3196 return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00003197}
3198
David Blaikie68e081d2011-12-20 02:48:34 +00003199void ValueDecl::anchor() { }
3200
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003201bool ValueDecl::isWeak() const {
3202 for (attr_iterator I = attr_begin(), E = attr_end(); I != E; ++I)
3203 if (isa<WeakAttr>(*I) || isa<WeakRefAttr>(*I))
3204 return true;
3205
3206 return isWeakImported();
3207}
3208
David Blaikie68e081d2011-12-20 02:48:34 +00003209void ImplicitParamDecl::anchor() { }
3210
Sebastian Redl833ef452010-01-26 22:01:41 +00003211ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003212 SourceLocation IdLoc,
3213 IdentifierInfo *Id,
3214 QualType Type) {
3215 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00003216}
3217
Douglas Gregor72172e92012-01-05 21:55:30 +00003218ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
3219 unsigned ID) {
3220 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
3221 return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
3222}
3223
Sebastian Redl833ef452010-01-26 22:01:41 +00003224FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003225 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003226 const DeclarationNameInfo &NameInfo,
3227 QualType T, TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003228 StorageClass SC, StorageClass SCAsWritten,
Douglas Gregorff76cb92010-12-09 16:59:22 +00003229 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00003230 bool hasWrittenPrototype,
3231 bool isConstexprSpecified) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003232 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
3233 T, TInfo, SC, SCAsWritten,
Richard Smitha77a0a62011-08-15 21:04:07 +00003234 isInlineSpecified,
3235 isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00003236 New->HasWrittenPrototype = hasWrittenPrototype;
3237 return New;
3238}
3239
Douglas Gregor72172e92012-01-05 21:55:30 +00003240FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3241 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
3242 return new (Mem) FunctionDecl(Function, 0, SourceLocation(),
3243 DeclarationNameInfo(), QualType(), 0,
3244 SC_None, SC_None, false, false);
3245}
3246
Sebastian Redl833ef452010-01-26 22:01:41 +00003247BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3248 return new (C) BlockDecl(DC, L);
3249}
3250
Douglas Gregor72172e92012-01-05 21:55:30 +00003251BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3252 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
3253 return new (Mem) BlockDecl(0, SourceLocation());
3254}
3255
Sebastian Redl833ef452010-01-26 22:01:41 +00003256EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3257 SourceLocation L,
3258 IdentifierInfo *Id, QualType T,
3259 Expr *E, const llvm::APSInt &V) {
3260 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
3261}
3262
Douglas Gregor72172e92012-01-05 21:55:30 +00003263EnumConstantDecl *
3264EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3265 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
3266 return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
3267 llvm::APSInt());
3268}
3269
David Blaikie68e081d2011-12-20 02:48:34 +00003270void IndirectFieldDecl::anchor() { }
3271
Benjamin Kramer39593702010-11-21 14:11:41 +00003272IndirectFieldDecl *
3273IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3274 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3275 unsigned CHS) {
Francois Pichet783dd6e2010-11-21 06:08:52 +00003276 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
3277}
3278
Douglas Gregor72172e92012-01-05 21:55:30 +00003279IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3280 unsigned ID) {
3281 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
3282 return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
3283 QualType(), 0, 0);
3284}
3285
Douglas Gregorbe996932010-09-01 20:41:53 +00003286SourceRange EnumConstantDecl::getSourceRange() const {
3287 SourceLocation End = getLocation();
3288 if (Init)
3289 End = Init->getLocEnd();
3290 return SourceRange(getLocation(), End);
3291}
3292
David Blaikie68e081d2011-12-20 02:48:34 +00003293void TypeDecl::anchor() { }
3294
Sebastian Redl833ef452010-01-26 22:01:41 +00003295TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003296 SourceLocation StartLoc, SourceLocation IdLoc,
3297 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
3298 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00003299}
3300
David Blaikie68e081d2011-12-20 02:48:34 +00003301void TypedefNameDecl::anchor() { }
3302
Douglas Gregor72172e92012-01-05 21:55:30 +00003303TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3304 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
3305 return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3306}
3307
Richard Smithdda56e42011-04-15 14:24:37 +00003308TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3309 SourceLocation StartLoc,
3310 SourceLocation IdLoc, IdentifierInfo *Id,
3311 TypeSourceInfo *TInfo) {
3312 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
3313}
3314
Douglas Gregor72172e92012-01-05 21:55:30 +00003315TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3316 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
3317 return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3318}
3319
Abramo Bagnaraea947882011-03-08 16:41:52 +00003320SourceRange TypedefDecl::getSourceRange() const {
3321 SourceLocation RangeEnd = getLocation();
3322 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3323 if (typeIsPostfix(TInfo->getType()))
3324 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3325 }
3326 return SourceRange(getLocStart(), RangeEnd);
3327}
3328
Richard Smithdda56e42011-04-15 14:24:37 +00003329SourceRange TypeAliasDecl::getSourceRange() const {
3330 SourceLocation RangeEnd = getLocStart();
3331 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3332 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3333 return SourceRange(getLocStart(), RangeEnd);
3334}
3335
David Blaikie68e081d2011-12-20 02:48:34 +00003336void FileScopeAsmDecl::anchor() { }
3337
Sebastian Redl833ef452010-01-26 22:01:41 +00003338FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00003339 StringLiteral *Str,
3340 SourceLocation AsmLoc,
3341 SourceLocation RParenLoc) {
3342 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00003343}
Douglas Gregorba345522011-12-02 23:23:56 +00003344
Douglas Gregor72172e92012-01-05 21:55:30 +00003345FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
3346 unsigned ID) {
3347 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
3348 return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
3349}
3350
Douglas Gregorba345522011-12-02 23:23:56 +00003351//===----------------------------------------------------------------------===//
3352// ImportDecl Implementation
3353//===----------------------------------------------------------------------===//
3354
3355/// \brief Retrieve the number of module identifiers needed to name the given
3356/// module.
3357static unsigned getNumModuleIdentifiers(Module *Mod) {
3358 unsigned Result = 1;
3359 while (Mod->Parent) {
3360 Mod = Mod->Parent;
3361 ++Result;
3362 }
3363 return Result;
3364}
3365
Douglas Gregor22d09742012-01-03 18:04:46 +00003366ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003367 Module *Imported,
3368 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00003369 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003370 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003371{
3372 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3373 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3374 memcpy(StoredLocs, IdentifierLocs.data(),
3375 IdentifierLocs.size() * sizeof(SourceLocation));
3376}
3377
Douglas Gregor22d09742012-01-03 18:04:46 +00003378ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003379 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00003380 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003381 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003382{
3383 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3384}
3385
3386ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003387 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00003388 ArrayRef<SourceLocation> IdentifierLocs) {
3389 void *Mem = C.Allocate(sizeof(ImportDecl) +
3390 IdentifierLocs.size() * sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00003391 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00003392}
3393
3394ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003395 SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003396 Module *Imported,
3397 SourceLocation EndLoc) {
3398 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00003399 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00003400 Import->setImplicit();
3401 return Import;
3402}
3403
Douglas Gregor72172e92012-01-05 21:55:30 +00003404ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3405 unsigned NumLocations) {
3406 void *Mem = AllocateDeserializedDecl(C, ID,
3407 (sizeof(ImportDecl) +
3408 NumLocations * sizeof(SourceLocation)));
Douglas Gregorba345522011-12-02 23:23:56 +00003409 return new (Mem) ImportDecl(EmptyShell());
3410}
3411
3412ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3413 if (!ImportedAndComplete.getInt())
3414 return ArrayRef<SourceLocation>();
3415
3416 const SourceLocation *StoredLocs
3417 = reinterpret_cast<const SourceLocation *>(this + 1);
3418 return ArrayRef<SourceLocation>(StoredLocs,
3419 getNumModuleIdentifiers(getImportedModule()));
3420}
3421
3422SourceRange ImportDecl::getSourceRange() const {
3423 if (!ImportedAndComplete.getInt())
3424 return SourceRange(getLocation(),
3425 *reinterpret_cast<const SourceLocation *>(this + 1));
3426
3427 return SourceRange(getLocation(), getIdentifierLocs().back());
3428}