blob: 9505d299ab1debfc7990d2bcd1a465b141f38069 [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 +0000141/// Is the given declaration a "type" or a "value" for the purposes of
142/// visibility computation?
143static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000144 return isa<TypeDecl>(D) ||
145 isa<ClassTemplateDecl>(D) ||
146 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000147}
148
John McCall5f46c482013-02-21 23:42:58 +0000149/// Does the given declaration have member specialization information,
150/// and if so, is it an explicit specialization?
151template <class T> static typename
152llvm::enable_if_c<!llvm::is_base_of<RedeclarableTemplateDecl, T>::value,
153 bool>::type
154isExplicitMemberSpecialization(const T *D) {
155 if (const MemberSpecializationInfo *member =
156 D->getMemberSpecializationInfo()) {
157 return member->isExplicitSpecialization();
158 }
159 return false;
160}
161
162/// For templates, this question is easier: a member template can't be
163/// explicitly instantiated, so there's a single bit indicating whether
164/// or not this is an explicit member specialization.
165static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
166 return D->isMemberSpecialization();
167}
168
John McCalld041a9b2013-02-20 01:54:26 +0000169/// Given a visibility attribute, return the explicit visibility
170/// associated with it.
171template <class T>
172static Visibility getVisibilityFromAttr(const T *attr) {
173 switch (attr->getVisibility()) {
174 case T::Default:
175 return DefaultVisibility;
176 case T::Hidden:
177 return HiddenVisibility;
178 case T::Protected:
179 return ProtectedVisibility;
180 }
181 llvm_unreachable("bad visibility kind");
182}
183
John McCalldf25c432013-02-16 00:17:33 +0000184/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000185static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000186 NamedDecl::ExplicitVisibilityKind kind) {
187 // If we're ultimately computing the visibility of a type, look for
188 // a 'type_visibility' attribute before looking for 'visibility'.
189 if (kind == NamedDecl::VisibilityForType) {
190 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
191 return getVisibilityFromAttr(A);
192 }
193 }
194
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000195 // If this declaration has an explicit visibility attribute, use it.
196 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000197 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000198 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000199
200 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
201 // implies visibility(default).
Douglas Gregore8bbc122011-09-02 00:18:52 +0000202 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000203 for (specific_attr_iterator<AvailabilityAttr>
204 A = D->specific_attr_begin<AvailabilityAttr>(),
205 AEnd = D->specific_attr_end<AvailabilityAttr>();
206 A != AEnd; ++A)
207 if ((*A)->getPlatform()->getName().equals("macosx"))
208 return DefaultVisibility;
209 }
210
David Blaikie7a30dc52013-02-21 01:47:18 +0000211 return None;
John McCall457a04e2010-10-22 21:05:15 +0000212}
213
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000214/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000215/// template parameter list. For visibility purposes, template
216/// parameters are part of the signature of a template.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000217static LinkageInfo
John McCalldf25c432013-02-16 00:17:33 +0000218getLVForTemplateParameterList(const TemplateParameterList *params) {
219 LinkageInfo LV;
220 for (TemplateParameterList::const_iterator P = params->begin(),
221 PEnd = params->end();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000222 P != PEnd; ++P) {
John McCalldf25c432013-02-16 00:17:33 +0000223
224 // Template type parameters are the most common and never
225 // contribute to visibility, pack or not.
226 if (isa<TemplateTypeParmDecl>(*P))
227 continue;
228
229 // Non-type template parameters can be restricted by the value type, e.g.
230 // template <enum X> class A { ... };
231 // We have to be careful here, though, because we can be dealing with
232 // dependent types.
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000233 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
John McCalldf25c432013-02-16 00:17:33 +0000234 // Handle the non-pack case first.
235 if (!NTTP->isExpandedParameterPack()) {
236 if (!NTTP->getType()->isDependentType()) {
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000237 LV.merge(NTTP->getType()->getLinkageAndVisibility());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000238 }
239 continue;
240 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000241
John McCalldf25c432013-02-16 00:17:33 +0000242 // Look at all the types in an expanded pack.
243 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
244 QualType type = NTTP->getExpansionType(i);
245 if (!type->isDependentType())
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000246 LV.merge(type->getLinkageAndVisibility());
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000247 }
John McCalldf25c432013-02-16 00:17:33 +0000248 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000249 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000250
John McCalldf25c432013-02-16 00:17:33 +0000251 // Template template parameters can be restricted by their
252 // template parameters, recursively.
253 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
254
255 // Handle the non-pack case first.
256 if (!TTP->isExpandedParameterPack()) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000257 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters()));
John McCalldf25c432013-02-16 00:17:33 +0000258 continue;
259 }
260
261 // Look at all expansions in an expanded pack.
262 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
263 i != n; ++i) {
264 LV.merge(getLVForTemplateParameterList(
265 TTP->getExpansionTemplateParameters(i)));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000266 }
267 }
268
John McCall457a04e2010-10-22 21:05:15 +0000269 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000270}
271
Rafael Espindola19de5612013-01-12 06:42:30 +0000272/// getLVForDecl - Get the linkage and visibility for the given declaration.
John McCalldf25c432013-02-16 00:17:33 +0000273static LinkageInfo getLVForDecl(const NamedDecl *D,
274 LVComputationKind computation);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000275
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000276/// \brief Get the most restrictive linkage for the types and
277/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000278///
279/// Note that we don't take an LVComputationKind because we always
280/// want to honor the visibility of template arguments in the same way.
281static LinkageInfo
282getLVForTemplateArgumentList(ArrayRef<TemplateArgument> args) {
283 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000284
John McCalldf25c432013-02-16 00:17:33 +0000285 for (unsigned i = 0, e = args.size(); i != e; ++i) {
286 const TemplateArgument &arg = args[i];
287 switch (arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000288 case TemplateArgument::Null:
289 case TemplateArgument::Integral:
290 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000291 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000292
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000293 case TemplateArgument::Type:
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000294 LV.merge(arg.getAsType()->getLinkageAndVisibility());
John McCalldf25c432013-02-16 00:17:33 +0000295 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000296
297 case TemplateArgument::Declaration:
John McCalldf25c432013-02-16 00:17:33 +0000298 if (NamedDecl *ND = dyn_cast<NamedDecl>(arg.getAsDecl())) {
299 assert(!usesTypeVisibility(ND));
300 LV.merge(getLVForDecl(ND, LVForValue));
301 }
302 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +0000303
304 case TemplateArgument::NullPtr:
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000305 LV.merge(arg.getNullPtrType()->getLinkageAndVisibility());
John McCalldf25c432013-02-16 00:17:33 +0000306 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000307
308 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000309 case TemplateArgument::TemplateExpansion:
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000310 if (TemplateDecl *Template
John McCalldf25c432013-02-16 00:17:33 +0000311 = arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
312 LV.merge(getLVForDecl(Template, LVForValue));
313 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000314
315 case TemplateArgument::Pack:
John McCalldf25c432013-02-16 00:17:33 +0000316 LV.merge(getLVForTemplateArgumentList(arg.getPackAsArray()));
317 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000318 }
John McCalldf25c432013-02-16 00:17:33 +0000319 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000320 }
321
John McCall457a04e2010-10-22 21:05:15 +0000322 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000323}
324
Rafael Espindola2f869a32012-01-14 00:30:36 +0000325static LinkageInfo
John McCalldf25c432013-02-16 00:17:33 +0000326getLVForTemplateArgumentList(const TemplateArgumentList &TArgs) {
327 return getLVForTemplateArgumentList(TArgs.asArray());
John McCall8823c652010-08-13 08:35:10 +0000328}
329
John McCall5f46c482013-02-21 23:42:58 +0000330static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
331 const FunctionTemplateSpecializationInfo *specInfo) {
332 // Include visibility from the template parameters and arguments
333 // only if this is not an explicit instantiation or specialization
334 // with direct explicit visibility. (Implicit instantiations won't
335 // have a direct attribute.)
336 if (!specInfo->isExplicitInstantiationOrSpecialization())
337 return true;
338
339 return !fn->hasAttr<VisibilityAttr>();
340}
341
John McCalldf25c432013-02-16 00:17:33 +0000342/// Merge in template-related linkage and visibility for the given
343/// function template specialization.
344///
345/// We don't need a computation kind here because we can assume
346/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000347///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000348/// \param[out] LV the computation to use for the parent
John McCall5f46c482013-02-21 23:42:58 +0000349static void
350mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
351 const FunctionTemplateSpecializationInfo *specInfo) {
352 bool considerVisibility =
353 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000354
355 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000356 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000357 LinkageInfo tempLV =
358 getLVForTemplateParameterList(temp->getTemplateParameters());
359 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
360
361 // Merge information from the template arguments.
362 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
363 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
364 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000365}
366
John McCall5f46c482013-02-21 23:42:58 +0000367/// Does the given declaration have a direct visibility attribute
368/// that would match the given rules?
369static bool hasDirectVisibilityAttribute(const NamedDecl *D,
370 LVComputationKind computation) {
371 switch (computation) {
372 case LVForType:
373 case LVForExplicitType:
374 if (D->hasAttr<TypeVisibilityAttr>())
375 return true;
376 // fallthrough
377 case LVForValue:
378 case LVForExplicitValue:
379 if (D->hasAttr<VisibilityAttr>())
380 return true;
381 return false;
382 }
383 llvm_unreachable("bad visibility computation kind");
384}
385
John McCalld041a9b2013-02-20 01:54:26 +0000386/// Should we consider visibility associated with the template
387/// arguments and parameters of the given class template specialization?
388static bool shouldConsiderTemplateVisibility(
389 const ClassTemplateSpecializationDecl *spec,
390 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000391 // Include visibility from the template parameters and arguments
392 // only if this is not an explicit instantiation or specialization
393 // with direct explicit visibility (and note that implicit
394 // instantiations won't have a direct attribute).
395 //
396 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000397 // for an explicit specialization when computing the visibility of a
398 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000399 //
400 // This is a bit complex; let's unpack it.
401 //
402 // An explicit class specialization is an independent, top-level
403 // declaration. As such, if it or any of its members has an
404 // explicit visibility attribute, that must directly express the
405 // user's intent, and we should honor it. The same logic applies to
406 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000407
408 // Fast path: if this is not an explicit instantiation or
409 // specialization, we always want to consider template-related
410 // visibility restrictions.
411 if (!spec->isExplicitInstantiationOrSpecialization())
412 return true;
413
414 // This is the 'member thereof' check.
415 if (spec->isExplicitSpecialization() &&
416 hasExplicitVisibilityAlready(computation))
417 return false;
418
John McCall5f46c482013-02-21 23:42:58 +0000419 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000420}
421
422/// Merge in template-related linkage and visibility for the given
423/// class template specialization.
424static void mergeTemplateLV(LinkageInfo &LV,
425 const ClassTemplateSpecializationDecl *spec,
426 LVComputationKind computation) {
427 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000428
429 // Merge information from the template parameters, but ignore
430 // visibility if we're only considering template arguments.
431
John McCalld041a9b2013-02-20 01:54:26 +0000432 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000433 LinkageInfo tempLV =
434 getLVForTemplateParameterList(temp->getTemplateParameters());
435 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000436 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000437
438 // Merge information from the template arguments. We ignore
439 // template-argument visibility if we've got an explicit
440 // instantiation with a visibility attribute.
441 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
442 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
443 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000444}
445
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000446static bool useInlineVisibilityHidden(const NamedDecl *D) {
447 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000448 const LangOptions &Opts = D->getASTContext().getLangOpts();
449 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000450 return false;
451
452 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
453 if (!FD)
454 return false;
455
456 TemplateSpecializationKind TSK = TSK_Undeclared;
457 if (FunctionTemplateSpecializationInfo *spec
458 = FD->getTemplateSpecializationInfo()) {
459 TSK = spec->getTemplateSpecializationKind();
460 } else if (MemberSpecializationInfo *MSI =
461 FD->getMemberSpecializationInfo()) {
462 TSK = MSI->getTemplateSpecializationKind();
463 }
464
465 const FunctionDecl *Def = 0;
466 // InlineVisibilityHidden only applies to definitions, and
467 // isInlined() only gives meaningful answers on definitions
468 // anyway.
469 return TSK != TSK_ExplicitInstantiationDeclaration &&
470 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000471 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000472}
473
Benjamin Kramer3e350262013-02-15 12:30:38 +0000474template <typename T> static bool isInExternCContext(T *D) {
Rafael Espindolaf4187652013-02-14 01:18:37 +0000475 const T *First = D->getFirstDeclaration();
476 return First->getDeclContext()->isExternCContext();
477}
478
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000479static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
John McCalldf25c432013-02-16 00:17:33 +0000480 LVComputationKind computation) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000481 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000482 "Not a name having namespace scope");
483 ASTContext &Context = D->getASTContext();
484
485 // C++ [basic.link]p3:
486 // A name having namespace scope (3.3.6) has internal linkage if it
487 // is the name of
488 // - an object, reference, function or function template that is
489 // explicitly declared static; or,
490 // (This bullet corresponds to C99 6.2.2p3.)
491 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
492 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000493 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000494 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000495
Richard Smithdc0ef452012-10-19 06:37:48 +0000496 // - a non-volatile object or reference that is explicitly declared const
497 // or constexpr and neither explicitly declared extern nor previously
498 // declared to have external linkage; or (there is no equivalent in C99)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000499 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000500 Var->getType().isConstQualified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000501 !Var->getType().isVolatileQualified()) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000502 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000503 if (PrevVar)
Rafael Espindolaadea16b2013-04-03 15:50:00 +0000504 return PrevVar->getLinkageAndVisibility();
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000505
506 if (Var->getStorageClass() != SC_Extern &&
507 Var->getStorageClass() != SC_PrivateExtern)
508 return LinkageInfo::internal();
509 }
510
511 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
512 PrevVar = PrevVar->getPreviousDecl()) {
513 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
514 Var->getStorageClass() == SC_None)
515 return PrevVar->getLinkageAndVisibility();
516 // Explicitly declared static.
517 if (PrevVar->getStorageClass() == SC_Static)
518 return LinkageInfo::internal();
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000519 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000520 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000521 // C++ [temp]p4:
522 // A non-member function template can have internal linkage; any
523 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000524 const FunctionDecl *Function = 0;
525 if (const FunctionTemplateDecl *FunTmpl
526 = dyn_cast<FunctionTemplateDecl>(D))
527 Function = FunTmpl->getTemplatedDecl();
528 else
529 Function = cast<FunctionDecl>(D);
530
531 // Explicitly declared static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000532 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000533 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000534 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
535 // - a data member of an anonymous union.
536 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
John McCallc273f242010-10-30 11:50:40 +0000537 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000538 }
539
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000540 if (D->isInAnonymousNamespace()) {
541 const VarDecl *Var = dyn_cast<VarDecl>(D);
542 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
Rafael Espindolaf4187652013-02-14 01:18:37 +0000543 if ((!Var || !isInExternCContext(Var)) &&
544 (!Func || !isInExternCContext(Func)))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000545 return LinkageInfo::uniqueExternal();
546 }
John McCallb7139c42010-10-28 04:18:25 +0000547
John McCall457a04e2010-10-22 21:05:15 +0000548 // Set up the defaults.
549
550 // C99 6.2.2p5:
551 // If the declaration of an identifier for an object has file
552 // scope and no storage-class specifier, its linkage is
553 // external.
John McCallc273f242010-10-30 11:50:40 +0000554 LinkageInfo LV;
555
John McCalld041a9b2013-02-20 01:54:26 +0000556 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000557 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000558 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000559 } else {
560 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000561 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000562 for (const DeclContext *DC = D->getDeclContext();
563 !isa<TranslationUnitDecl>(DC);
564 DC = DC->getParent()) {
565 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
566 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000567 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000568 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000569 break;
570 }
571 }
572 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000573
John McCalldf25c432013-02-16 00:17:33 +0000574 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000575 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000576 // Use global type/value visibility as appropriate.
577 Visibility globalVisibility;
578 if (computation == LVForValue) {
579 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
580 } else {
581 assert(computation == LVForType);
582 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
583 }
584 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000585
586 // If we're paying attention to global visibility, apply
587 // -finline-visibility-hidden if this is an inline method.
588 if (useInlineVisibilityHidden(D))
589 LV.mergeVisibility(HiddenVisibility, true);
590 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000591 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000592
Douglas Gregorf73b2822009-11-25 22:24:25 +0000593 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000594
Douglas Gregorf73b2822009-11-25 22:24:25 +0000595 // A name having namespace scope has external linkage if it is the
596 // name of
597 //
598 // - an object or reference, unless it has internal linkage; or
599 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000600 // GCC applies the following optimization to variables and static
601 // data members, but not to functions:
602 //
John McCall457a04e2010-10-22 21:05:15 +0000603 // Modify the variable's LV by the LV of its type unless this is
604 // C or extern "C". This follows from [basic.link]p9:
605 // A type without linkage shall not be used as the type of a
606 // variable or function with external linkage unless
607 // - the entity has C language linkage, or
608 // - the entity is declared within an unnamed namespace, or
609 // - the entity is not used or is defined in the same
610 // translation unit.
611 // and [basic.link]p10:
612 // ...the types specified by all declarations referring to a
613 // given variable or function shall be identical...
614 // C does not have an equivalent rule.
615 //
John McCall5fe84122010-10-26 04:59:26 +0000616 // Ignore this if we've got an explicit attribute; the user
617 // probably knows what they're doing.
618 //
John McCall457a04e2010-10-22 21:05:15 +0000619 // Note that we don't want to make the variable non-external
620 // because of this, but unique-external linkage suits us.
Rafael Espindolab22b91c2013-03-12 15:22:39 +0000621 if (Context.getLangOpts().CPlusPlus && !isInExternCContext(Var)) {
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000622 LinkageInfo TypeLV = Var->getType()->getLinkageAndVisibility();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000623 if (TypeLV.getLinkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000624 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000625 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000626 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000627 }
628
John McCall23032652010-11-02 18:38:13 +0000629 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000630 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000631
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000632 // Note that Sema::MergeVarDecl already takes care of implementing
633 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
634 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000635
Douglas Gregorf73b2822009-11-25 22:24:25 +0000636 // - a function, unless it has internal linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000637 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000638 // In theory, we can modify the function's LV by the LV of its
639 // type unless it has C linkage (see comment above about variables
640 // for justification). In practice, GCC doesn't do this, so it's
641 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000642
John McCall23032652010-11-02 18:38:13 +0000643 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000644 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000645
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000646 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
647 // merging storage classes and visibility attributes, so we don't have to
648 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000649
John McCallf768aa72011-02-10 06:50:24 +0000650 // In C++, then if the type of the function uses a type with
651 // unique-external linkage, it's not legally usable from outside
652 // this translation unit. However, we should use the C linkage
653 // rules instead for extern "C" declarations.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000654 if (Context.getLangOpts().CPlusPlus &&
Eli Friedman839192f2012-01-15 01:23:58 +0000655 !Function->getDeclContext()->isExternCContext() &&
John McCallf768aa72011-02-10 06:50:24 +0000656 Function->getType()->getLinkage() == UniqueExternalLinkage)
657 return LinkageInfo::uniqueExternal();
658
John McCall5f46c482013-02-21 23:42:58 +0000659 // Consider LV from the template and the template arguments.
660 // We're at file scope, so we do not need to worry about nested
661 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000662 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000663 = Function->getTemplateSpecializationInfo()) {
John McCalldf25c432013-02-16 00:17:33 +0000664 mergeTemplateLV(LV, Function, specInfo);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000665 }
666
Douglas Gregorf73b2822009-11-25 22:24:25 +0000667 // - a named class (Clause 9), or an unnamed class defined in a
668 // typedef declaration in which the class has the typedef name
669 // for linkage purposes (7.1.3); or
670 // - a named enumeration (7.2), or an unnamed enumeration
671 // defined in a typedef declaration in which the enumeration
672 // has the typedef name for linkage purposes (7.1.3); or
John McCall457a04e2010-10-22 21:05:15 +0000673 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
674 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000675 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000676 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000677
John McCall457a04e2010-10-22 21:05:15 +0000678 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000679 // linkage of the template and template arguments. We're at file
680 // scope, so we do not need to worry about nested specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000681 if (const ClassTemplateSpecializationDecl *spec
John McCall457a04e2010-10-22 21:05:15 +0000682 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000683 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000684 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000685
686 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000687 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000688 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000689 computation);
Rafael Espindola4a5da442013-02-27 02:56:45 +0000690 if (!isExternalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000691 return LinkageInfo::none();
692 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000693
694 // - a template, unless it is a function template that has
695 // internal linkage (Clause 14);
John McCall8bc6d5b2011-03-04 10:39:25 +0000696 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000697 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000698 LinkageInfo tempLV =
699 getLVForTemplateParameterList(temp->getTemplateParameters());
700 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
701
Douglas Gregorf73b2822009-11-25 22:24:25 +0000702 // - a namespace (7.3), unless it is declared within an unnamed
703 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000704 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
705 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000706
John McCall457a04e2010-10-22 21:05:15 +0000707 // By extension, we assign external linkage to Objective-C
708 // interfaces.
709 } else if (isa<ObjCInterfaceDecl>(D)) {
710 // fallout
711
712 // Everything not covered here has no linkage.
713 } else {
John McCallc273f242010-10-30 11:50:40 +0000714 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000715 }
716
717 // If we ended up with non-external linkage, visibility should
718 // always be default.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000719 if (LV.getLinkage() != ExternalLinkage)
720 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000721
John McCall457a04e2010-10-22 21:05:15 +0000722 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000723}
724
John McCalldf25c432013-02-16 00:17:33 +0000725static LinkageInfo getLVForClassMember(const NamedDecl *D,
726 LVComputationKind computation) {
John McCall457a04e2010-10-22 21:05:15 +0000727 // Only certain class members have linkage. Note that fields don't
728 // really have linkage, but it's convenient to say they do for the
729 // purposes of calculating linkage of pointer-to-data-member
730 // template arguments.
John McCall8823c652010-08-13 08:35:10 +0000731 if (!(isa<CXXMethodDecl>(D) ||
732 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000733 isa<FieldDecl>(D) ||
David Blaikie095deba2012-11-14 01:52:05 +0000734 isa<TagDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000735 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000736
John McCall07072662010-11-02 01:45:15 +0000737 LinkageInfo LV;
738
John McCall07072662010-11-02 01:45:15 +0000739 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000740 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000741 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000742 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000743 // If we're paying attention to global visibility, apply
744 // -finline-visibility-hidden if this is an inline method.
745 //
746 // Note that we do this before merging information about
747 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000748 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000749 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000750 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000751
752 // If this class member has an explicit visibility attribute, the only
753 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000754 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000755 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000756 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000757 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000758
John McCall5f46c482013-02-21 23:42:58 +0000759 LinkageInfo classLV =
760 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
Rafael Espindola4a5da442013-02-27 02:56:45 +0000761 if (!isExternalLinkage(classLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000762 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000763
764 // If the class already has unique-external linkage, we can't improve.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000765 if (classLV.getLinkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000766 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000767
John McCall5f46c482013-02-21 23:42:58 +0000768 // Otherwise, don't merge in classLV yet, because in certain cases
769 // we need to completely ignore the visibility from it.
770
771 // Specifically, if this decl exists and has an explicit attribute.
772 const NamedDecl *explicitSpecSuppressor = 0;
773
John McCall8823c652010-08-13 08:35:10 +0000774 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000775 // If the type of the function uses a type with unique-external
776 // linkage, it's not legally usable from outside this translation unit.
777 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
778 return LinkageInfo::uniqueExternal();
779
John McCall457a04e2010-10-22 21:05:15 +0000780 // If this is a method template specialization, use the linkage for
781 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000782 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000783 = MD->getTemplateSpecializationInfo()) {
John McCalldf25c432013-02-16 00:17:33 +0000784 mergeTemplateLV(LV, MD, spec);
John McCall5f46c482013-02-21 23:42:58 +0000785 if (spec->isExplicitSpecialization()) {
786 explicitSpecSuppressor = MD;
787 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
788 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
789 }
790 } else if (isExplicitMemberSpecialization(MD)) {
791 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000792 }
John McCall457a04e2010-10-22 21:05:15 +0000793
John McCall37bb6c92010-10-29 22:22:43 +0000794 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCallb8c604a2011-06-27 23:06:04 +0000795 if (const ClassTemplateSpecializationDecl *spec
John McCall37bb6c92010-10-29 22:22:43 +0000796 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000797 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000798 if (spec->isExplicitSpecialization()) {
799 explicitSpecSuppressor = spec;
800 } else {
801 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
802 if (isExplicitMemberSpecialization(temp)) {
803 explicitSpecSuppressor = temp->getTemplatedDecl();
804 }
805 }
806 } else if (isExplicitMemberSpecialization(RD)) {
807 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000808 }
809
John McCall37bb6c92010-10-29 22:22:43 +0000810 // Static data members.
811 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCall36cd5cc2010-10-30 09:18:49 +0000812 // Modify the variable's linkage by its type, but ignore the
813 // type's visibility unless it's a definition.
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000814 LinkageInfo typeLV = VD->getType()->getLinkageAndVisibility();
John McCall5f46c482013-02-21 23:42:58 +0000815 LV.mergeMaybeWithVisibility(typeLV,
Rafael Espindola4a5da442013-02-27 02:56:45 +0000816 !LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit());
John McCall5f46c482013-02-21 23:42:58 +0000817
818 if (isExplicitMemberSpecialization(VD)) {
819 explicitSpecSuppressor = VD;
820 }
John McCalldf25c432013-02-16 00:17:33 +0000821
822 // Template members.
823 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
824 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +0000825 (!LV.isVisibilityExplicit() &&
826 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000827 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000828 LinkageInfo tempLV =
829 getLVForTemplateParameterList(temp->getTemplateParameters());
830 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +0000831
832 if (const RedeclarableTemplateDecl *redeclTemp =
833 dyn_cast<RedeclarableTemplateDecl>(temp)) {
834 if (isExplicitMemberSpecialization(redeclTemp)) {
835 explicitSpecSuppressor = temp->getTemplatedDecl();
836 }
837 }
John McCall37bb6c92010-10-29 22:22:43 +0000838 }
839
John McCall5f46c482013-02-21 23:42:58 +0000840 // We should never be looking for an attribute directly on a template.
841 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
842
843 // If this member is an explicit member specialization, and it has
844 // an explicit attribute, ignore visibility from the parent.
845 bool considerClassVisibility = true;
846 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +0000847 // optimization: hasDVA() is true only with explicit visibility.
848 LV.isVisibilityExplicit() &&
849 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +0000850 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
851 considerClassVisibility = false;
852 }
853
854 // Finally, merge in information from the class.
855 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +0000856 return LV;
John McCall8823c652010-08-13 08:35:10 +0000857}
858
David Blaikie68e081d2011-12-20 02:48:34 +0000859void NamedDecl::anchor() { }
860
Rafael Espindola0e0d0092013-03-14 03:07:35 +0000861bool NamedDecl::isLinkageValid() const {
862 if (!HasCachedLinkage)
863 return true;
John McCalld396b972011-02-08 19:01:05 +0000864
Rafael Espindola0e0d0092013-03-14 03:07:35 +0000865 return getLVForDecl(this, LVForExplicitValue).getLinkage() ==
866 Linkage(CachedLinkage);
John McCalld396b972011-02-08 19:01:05 +0000867}
868
Douglas Gregorbf62d642010-12-06 18:36:25 +0000869Linkage NamedDecl::getLinkage() const {
Richard Smith88581592013-02-12 05:48:23 +0000870 if (HasCachedLinkage)
Rafael Espindola19de5612013-01-12 06:42:30 +0000871 return Linkage(CachedLinkage);
Rafael Espindola19de5612013-01-12 06:42:30 +0000872
John McCalld041a9b2013-02-20 01:54:26 +0000873 // We don't care about visibility here, so ask for the cheapest
874 // possible visibility analysis.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000875 CachedLinkage = getLVForDecl(this, LVForExplicitValue).getLinkage();
Rafael Espindola19de5612013-01-12 06:42:30 +0000876 HasCachedLinkage = 1;
877
878#ifndef NDEBUG
879 verifyLinkage();
880#endif
881
882 return Linkage(CachedLinkage);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000883}
884
John McCallc273f242010-10-30 11:50:40 +0000885LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCalldf25c432013-02-16 00:17:33 +0000886 LVComputationKind computation =
887 (usesTypeVisibility(this) ? LVForType : LVForValue);
888 LinkageInfo LI = getLVForDecl(this, computation);
Rafael Espindola19de5612013-01-12 06:42:30 +0000889 if (HasCachedLinkage) {
Rafael Espindola4a5da442013-02-27 02:56:45 +0000890 assert(Linkage(CachedLinkage) == LI.getLinkage());
Rafael Espindola19de5612013-01-12 06:42:30 +0000891 return LI;
Rafael Espindola54606d52012-12-25 07:31:49 +0000892 }
Rafael Espindola19de5612013-01-12 06:42:30 +0000893 HasCachedLinkage = 1;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000894 CachedLinkage = LI.getLinkage();
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000895
896#ifndef NDEBUG
Rafael Espindola19de5612013-01-12 06:42:30 +0000897 verifyLinkage();
898#endif
899
900 return LI;
901}
902
903void NamedDecl::verifyLinkage() const {
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000904 // In C (because of gnu inline) and in c++ with microsoft extensions an
905 // static can follow an extern, so we can have two decls with different
906 // linkages.
907 const LangOptions &Opts = getASTContext().getLangOpts();
908 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
Rafael Espindola19de5612013-01-12 06:42:30 +0000909 return;
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000910
911 // We have just computed the linkage for this decl. By induction we know
912 // that all other computed linkages match, check that the one we just computed
913 // also does.
914 NamedDecl *D = NULL;
915 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
916 NamedDecl *T = cast<NamedDecl>(*I);
917 if (T == this)
918 continue;
Rafael Espindola19de5612013-01-12 06:42:30 +0000919 if (T->HasCachedLinkage != 0) {
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000920 D = T;
921 break;
922 }
923 }
924 assert(!D || D->CachedLinkage == CachedLinkage);
John McCall033caa52010-10-29 00:29:13 +0000925}
Ted Kremenek926d8602010-04-20 23:15:35 +0000926
David Blaikie05785d12013-02-20 22:23:23 +0000927Optional<Visibility>
John McCalld041a9b2013-02-20 01:54:26 +0000928NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
Rafael Espindola3a52c442013-02-26 19:33:14 +0000929 // Check the declaration itself first.
930 if (Optional<Visibility> V = getVisibilityOf(this, kind))
931 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000932
Rafael Espindola3a52c442013-02-26 19:33:14 +0000933 // If this is a member class of a specialization of a class template
934 // and the corresponding decl has explicit visibility, use that.
935 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(this)) {
936 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
937 if (InstantiatedFrom)
938 return getVisibilityOf(InstantiatedFrom, kind);
939 }
940
941 // If there wasn't explicit visibility there, and this is a
942 // specialization of a class template, check for visibility
943 // on the pattern.
944 if (const ClassTemplateSpecializationDecl *spec
945 = dyn_cast<ClassTemplateSpecializationDecl>(this))
946 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
947 kind);
948
949 // Use the most recent declaration.
950 const NamedDecl *MostRecent = cast<NamedDecl>(this->getMostRecentDecl());
951 if (MostRecent != this)
952 return MostRecent->getExplicitVisibility(kind);
953
954 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
Rafael Espindola96e68242012-05-16 02:10:38 +0000955 if (Var->isStaticDataMember()) {
956 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
957 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +0000958 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +0000959 }
960
David Blaikie7a30dc52013-02-21 01:47:18 +0000961 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +0000962 }
Rafael Espindola3a52c442013-02-26 19:33:14 +0000963 // Also handle function template specializations.
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000964 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000965 // If the function is a specialization of a template with an
966 // explicit visibility attribute, use that.
967 if (FunctionTemplateSpecializationInfo *templateInfo
968 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +0000969 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
970 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000971
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000972 // If the function is a member of a specialization of a class template
973 // and the corresponding decl has explicit visibility, use that.
974 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
975 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +0000976 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000977
David Blaikie7a30dc52013-02-21 01:47:18 +0000978 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000979 }
980
Rafael Espindolafb4263f2012-07-31 19:02:02 +0000981 // The visibility of a template is stored in the templated decl.
982 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(this))
John McCalld041a9b2013-02-20 01:54:26 +0000983 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +0000984
David Blaikie7a30dc52013-02-21 01:47:18 +0000985 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000986}
987
John McCalldf25c432013-02-16 00:17:33 +0000988static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
989 LVComputationKind computation) {
990 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
991 if (Function->isInAnonymousNamespace() &&
992 !Function->getDeclContext()->isExternCContext())
993 return LinkageInfo::uniqueExternal();
994
995 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000996 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCalldf25c432013-02-16 00:17:33 +0000997 return LinkageInfo::internal();
998
999 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001000 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001001 if (Optional<Visibility> Vis =
1002 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001003 LV.mergeVisibility(*Vis, true);
1004 }
1005
1006 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1007 // merging storage classes and visibility attributes, so we don't have to
1008 // look at previous decls in here.
1009
1010 return LV;
1011 }
1012
1013 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001014 if (Var->hasExternalStorage()) {
John McCalldf25c432013-02-16 00:17:33 +00001015 if (Var->isInAnonymousNamespace() &&
1016 !Var->getDeclContext()->isExternCContext())
1017 return LinkageInfo::uniqueExternal();
1018
John McCalldf25c432013-02-16 00:17:33 +00001019 LinkageInfo LV;
1020 if (Var->getStorageClass() == SC_PrivateExtern)
1021 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001022 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001023 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001024 LV.mergeVisibility(*Vis, true);
1025 }
1026
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001027 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1028 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1029 if (PrevLV.getLinkage())
1030 LV.setLinkage(PrevLV.getLinkage());
1031 LV.mergeVisibility(PrevLV);
1032 }
1033
John McCalldf25c432013-02-16 00:17:33 +00001034 return LV;
1035 }
1036 }
1037
1038 return LinkageInfo::none();
1039}
1040
1041static LinkageInfo getLVForDecl(const NamedDecl *D,
1042 LVComputationKind computation) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001043 // Objective-C: treat all Objective-C declarations as having external
1044 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001045 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001046 default:
1047 break;
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001048 case Decl::ParmVar:
1049 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001050 case Decl::TemplateTemplateParm: // count these as external
1051 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001052 case Decl::ObjCAtDefsField:
1053 case Decl::ObjCCategory:
1054 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001055 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001056 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001057 case Decl::ObjCMethod:
1058 case Decl::ObjCProperty:
1059 case Decl::ObjCPropertyImpl:
1060 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +00001061 return LinkageInfo::external();
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001062
1063 case Decl::CXXRecord: {
1064 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1065 if (Record->isLambda()) {
1066 if (!Record->getLambdaManglingNumber()) {
1067 // This lambda has no mangling number, so it's internal.
1068 return LinkageInfo::internal();
1069 }
1070
1071 // This lambda has its linkage/visibility determined by its owner.
1072 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
1073 if (Decl *ContextDecl = Record->getLambdaContextDecl()) {
1074 if (isa<ParmVarDecl>(ContextDecl))
1075 DC = ContextDecl->getDeclContext()->getRedeclContext();
1076 else
John McCalldf25c432013-02-16 00:17:33 +00001077 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001078 }
1079
1080 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
John McCalldf25c432013-02-16 00:17:33 +00001081 return getLVForDecl(ND, computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001082
1083 return LinkageInfo::external();
1084 }
1085
1086 break;
1087 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001088 }
1089
Douglas Gregorf73b2822009-11-25 22:24:25 +00001090 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001091 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCalldf25c432013-02-16 00:17:33 +00001092 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001093
1094 // C++ [basic.link]p5:
1095 // In addition, a member function, static data member, a named
1096 // class or enumeration of class scope, or an unnamed class or
1097 // enumeration defined in a class-scope typedef declaration such
1098 // that the class or enumeration has the typedef name for linkage
1099 // purposes (7.1.3), has external linkage if the name of the class
1100 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001101 if (D->getDeclContext()->isRecord())
John McCalldf25c432013-02-16 00:17:33 +00001102 return getLVForClassMember(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001103
1104 // C++ [basic.link]p6:
1105 // The name of a function declared in block scope and the name of
1106 // an object declared by a block scope extern declaration have
1107 // linkage. If there is a visible declaration of an entity with
1108 // linkage having the same name and type, ignoring entities
1109 // declared outside the innermost enclosing namespace scope, the
1110 // block scope declaration declares that same entity and receives
1111 // the linkage of the previous declaration. If there is more than
1112 // one such matching entity, the program is ill-formed. Otherwise,
1113 // if no matching entity is found, the block scope entity receives
1114 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001115 if (D->getDeclContext()->isFunctionOrMethod())
1116 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001117
1118 // C++ [basic.link]p6:
1119 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001120 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001121}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001122
Douglas Gregor2ada0482009-02-04 17:27:36 +00001123std::string NamedDecl::getQualifiedNameAsString() const {
Douglas Gregor78254c82012-03-27 23:34:16 +00001124 return getQualifiedNameAsString(getASTContext().getPrintingPolicy());
Anders Carlsson2fb08242009-09-08 18:24:21 +00001125}
1126
1127std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001128 std::string QualName;
1129 llvm::raw_string_ostream OS(QualName);
1130 printQualifiedName(OS, P);
1131 return OS.str();
1132}
1133
1134void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1135 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1136}
1137
1138void NamedDecl::printQualifiedName(raw_ostream &OS,
1139 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001140 const DeclContext *Ctx = getDeclContext();
1141
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001142 if (Ctx->isFunctionOrMethod()) {
1143 printName(OS);
1144 return;
1145 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001146
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001147 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001148 ContextsTy Contexts;
1149
1150 // Collect contexts.
1151 while (Ctx && isa<NamedDecl>(Ctx)) {
1152 Contexts.push_back(Ctx);
1153 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001154 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001155
1156 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1157 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00001158 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001159 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001160 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001161 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00001162 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1163 TemplateArgs.data(),
1164 TemplateArgs.size(),
1165 P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001166 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Sam Weinig07d211e2009-12-24 23:15:03 +00001167 if (ND->isAnonymousNamespace())
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001168 OS << "<anonymous namespace>";
Sam Weinig07d211e2009-12-24 23:15:03 +00001169 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001170 OS << *ND;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001171 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1172 if (!RD->getIdentifier())
1173 OS << "<anonymous " << RD->getKindName() << '>';
1174 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001175 OS << *RD;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001176 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Sam Weinigb999f682009-12-28 03:19:38 +00001177 const FunctionProtoType *FT = 0;
1178 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001179 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001180
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001181 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001182 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001183 unsigned NumParams = FD->getNumParams();
1184 for (unsigned i = 0; i < NumParams; ++i) {
1185 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001186 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001187 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001188 }
1189
1190 if (FT->isVariadic()) {
1191 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001192 OS << ", ";
1193 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001194 }
1195 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001196 OS << ')';
1197 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001198 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001199 }
1200 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001201 }
1202
John McCalla2a3f7d2010-03-16 21:48:18 +00001203 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001204 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001205 else
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001206 OS << "<anonymous>";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001207}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001208
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001209void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1210 const PrintingPolicy &Policy,
1211 bool Qualified) const {
1212 if (Qualified)
1213 printQualifiedName(OS, Policy);
1214 else
1215 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001216}
1217
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001218bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001219 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1220
Douglas Gregor889ceb72009-02-03 19:21:40 +00001221 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1222 // We want to keep it, unless it nominates same namespace.
1223 if (getKind() == Decl::UsingDirective) {
Douglas Gregor12441b32011-02-25 16:33:46 +00001224 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1225 ->getOriginalNamespace() ==
1226 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1227 ->getOriginalNamespace();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001228 }
Mike Stump11289f42009-09-09 15:08:12 +00001229
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001230 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1231 // For function declarations, we keep track of redeclarations.
Douglas Gregorec9fd132012-01-14 16:38:05 +00001232 return FD->getPreviousDecl() == OldD;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001233
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001234 // For function templates, the underlying function declarations are linked.
1235 if (const FunctionTemplateDecl *FunctionTemplate
1236 = dyn_cast<FunctionTemplateDecl>(this))
1237 if (const FunctionTemplateDecl *OldFunctionTemplate
1238 = dyn_cast<FunctionTemplateDecl>(OldD))
1239 return FunctionTemplate->getTemplatedDecl()
1240 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001241
Steve Naroffc4173fa2009-02-22 19:35:57 +00001242 // For method declarations, we keep track of redeclarations.
1243 if (isa<ObjCMethodDecl>(this))
1244 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001245
John McCall9f3059a2009-10-09 21:13:30 +00001246 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1247 return true;
1248
John McCall3f746822009-11-17 05:59:44 +00001249 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1250 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1251 cast<UsingShadowDecl>(OldD)->getTargetDecl();
1252
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001253 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1254 ASTContext &Context = getASTContext();
1255 return Context.getCanonicalNestedNameSpecifier(
1256 cast<UsingDecl>(this)->getQualifier()) ==
1257 Context.getCanonicalNestedNameSpecifier(
1258 cast<UsingDecl>(OldD)->getQualifier());
1259 }
Argyrios Kyrtzidis4b520072010-11-04 08:48:52 +00001260
Douglas Gregorb59643b2012-01-03 23:26:26 +00001261 // A typedef of an Objective-C class type can replace an Objective-C class
1262 // declaration or definition, and vice versa.
1263 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1264 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1265 return true;
1266
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001267 // For non-function declarations, if the declarations are of the
1268 // same kind then this must be a redeclaration, or semantic analysis
1269 // would not have given us the new declaration.
1270 return this->getKind() == OldD->getKind();
1271}
1272
Douglas Gregoreddf4332009-02-24 20:03:32 +00001273bool NamedDecl::hasLinkage() const {
Douglas Gregorf73b2822009-11-25 22:24:25 +00001274 return getLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001275}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001276
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001277NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001278 NamedDecl *ND = this;
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001279 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1280 ND = UD->getTargetDecl();
1281
1282 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1283 return AD->getClassInterface();
1284
1285 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001286}
1287
John McCalla8ae2222010-04-06 21:38:20 +00001288bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001289 if (!isCXXClassMember())
1290 return false;
1291
John McCalla8ae2222010-04-06 21:38:20 +00001292 const NamedDecl *D = this;
1293 if (isa<UsingShadowDecl>(D))
1294 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1295
Francois Pichet783dd6e2010-11-21 06:08:52 +00001296 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001297 return true;
1298 if (isa<CXXMethodDecl>(D))
1299 return cast<CXXMethodDecl>(D)->isInstance();
1300 if (isa<FunctionTemplateDecl>(D))
1301 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
1302 ->getTemplatedDecl())->isInstance();
1303 return false;
1304}
1305
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001306//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001307// DeclaratorDecl Implementation
1308//===----------------------------------------------------------------------===//
1309
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001310template <typename DeclT>
1311static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1312 if (decl->getNumTemplateParameterLists() > 0)
1313 return decl->getTemplateParameterList(0)->getTemplateLoc();
1314 else
1315 return decl->getInnerLocStart();
1316}
1317
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001318SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001319 TypeSourceInfo *TSI = getTypeSourceInfo();
1320 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001321 return SourceLocation();
1322}
1323
Douglas Gregor14454802011-02-25 02:25:35 +00001324void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1325 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001326 // Make sure the extended decl info is allocated.
1327 if (!hasExtInfo()) {
1328 // Save (non-extended) type source info pointer.
1329 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1330 // Allocate external info struct.
1331 DeclInfo = new (getASTContext()) ExtInfo;
1332 // Restore savedTInfo into (extended) decl info.
1333 getExtInfo()->TInfo = savedTInfo;
1334 }
1335 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001336 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001337 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001338 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001339 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001340 if (getExtInfo()->NumTemplParamLists == 0) {
1341 // Save type source info pointer.
1342 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1343 // Deallocate the extended decl info.
1344 getASTContext().Deallocate(getExtInfo());
1345 // Restore savedTInfo into (non-extended) decl info.
1346 DeclInfo = savedTInfo;
1347 }
1348 else
1349 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001350 }
1351 }
1352}
1353
Abramo Bagnara60804e12011-03-18 15:16:37 +00001354void
1355DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1356 unsigned NumTPLists,
1357 TemplateParameterList **TPLists) {
1358 assert(NumTPLists > 0);
1359 // Make sure the extended decl info is allocated.
1360 if (!hasExtInfo()) {
1361 // Save (non-extended) type source info pointer.
1362 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1363 // Allocate external info struct.
1364 DeclInfo = new (getASTContext()) ExtInfo;
1365 // Restore savedTInfo into (extended) decl info.
1366 getExtInfo()->TInfo = savedTInfo;
1367 }
1368 // Set the template parameter lists info.
1369 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1370}
1371
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001372SourceLocation DeclaratorDecl::getOuterLocStart() const {
1373 return getTemplateOrInnerLocStart(this);
1374}
1375
Abramo Bagnaraea947882011-03-08 16:41:52 +00001376namespace {
1377
1378// Helper function: returns true if QT is or contains a type
1379// having a postfix component.
1380bool typeIsPostfix(clang::QualType QT) {
1381 while (true) {
1382 const Type* T = QT.getTypePtr();
1383 switch (T->getTypeClass()) {
1384 default:
1385 return false;
1386 case Type::Pointer:
1387 QT = cast<PointerType>(T)->getPointeeType();
1388 break;
1389 case Type::BlockPointer:
1390 QT = cast<BlockPointerType>(T)->getPointeeType();
1391 break;
1392 case Type::MemberPointer:
1393 QT = cast<MemberPointerType>(T)->getPointeeType();
1394 break;
1395 case Type::LValueReference:
1396 case Type::RValueReference:
1397 QT = cast<ReferenceType>(T)->getPointeeType();
1398 break;
1399 case Type::PackExpansion:
1400 QT = cast<PackExpansionType>(T)->getPattern();
1401 break;
1402 case Type::Paren:
1403 case Type::ConstantArray:
1404 case Type::DependentSizedArray:
1405 case Type::IncompleteArray:
1406 case Type::VariableArray:
1407 case Type::FunctionProto:
1408 case Type::FunctionNoProto:
1409 return true;
1410 }
1411 }
1412}
1413
1414} // namespace
1415
1416SourceRange DeclaratorDecl::getSourceRange() const {
1417 SourceLocation RangeEnd = getLocation();
1418 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1419 if (typeIsPostfix(TInfo->getType()))
1420 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1421 }
1422 return SourceRange(getOuterLocStart(), RangeEnd);
1423}
1424
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001425void
Douglas Gregor20527e22010-06-15 17:44:38 +00001426QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1427 unsigned NumTPLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001428 TemplateParameterList **TPLists) {
1429 assert((NumTPLists == 0 || TPLists != 0) &&
1430 "Empty array of template parameters with positive size!");
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001431
1432 // Free previous template parameters (if any).
1433 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001434 Context.Deallocate(TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001435 TemplParamLists = 0;
1436 NumTemplParamLists = 0;
1437 }
1438 // Set info on matched template parameter lists (if any).
1439 if (NumTPLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001440 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001441 NumTemplParamLists = NumTPLists;
1442 for (unsigned i = NumTPLists; i-- > 0; )
1443 TemplParamLists[i] = TPLists[i];
1444 }
1445}
1446
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001447//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001448// VarDecl Implementation
1449//===----------------------------------------------------------------------===//
1450
Sebastian Redl833ef452010-01-26 22:01:41 +00001451const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1452 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001453 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001454 case SC_Auto: return "auto";
1455 case SC_Extern: return "extern";
1456 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1457 case SC_PrivateExtern: return "__private_extern__";
1458 case SC_Register: return "register";
1459 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001460 }
1461
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001462 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001463}
1464
Abramo Bagnaradff19302011-03-08 08:55:46 +00001465VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1466 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001467 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001468 StorageClass S) {
1469 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001470}
1471
Douglas Gregor72172e92012-01-05 21:55:30 +00001472VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1473 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
1474 return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001475 QualType(), 0, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001476}
1477
Douglas Gregorbf62d642010-12-06 18:36:25 +00001478void VarDecl::setStorageClass(StorageClass SC) {
1479 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001480 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001481}
1482
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001483SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001484 if (const Expr *Init = getInit()) {
1485 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001486 // If Init is implicit, ignore its source range and fallback on
1487 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1488 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001489 return SourceRange(getOuterLocStart(), InitEnd);
1490 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001491 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001492}
1493
Rafael Espindola88510672013-01-04 21:18:45 +00001494template<typename T>
Rafael Espindolaf4187652013-02-14 01:18:37 +00001495static LanguageLinkage getLanguageLinkageTemplate(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001496 // C++ [dcl.link]p1: All function types, function names with external linkage,
1497 // and variable names with external linkage have a language linkage.
1498 if (!isExternalLinkage(D.getLinkage()))
1499 return NoLanguageLinkage;
1500
1501 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001502 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001503 ASTContext &Context = D.getASTContext();
1504 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001505 return CLanguageLinkage;
1506
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001507 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1508 // language linkage of the names of class members and the function type of
1509 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001510 const DeclContext *DC = D.getDeclContext();
1511 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001512 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001513
1514 // If the first decl is in an extern "C" context, any other redeclaration
1515 // will have C language linkage. If the first one is not in an extern "C"
1516 // context, we would have reported an error for any other decl being in one.
Rafael Espindola88510672013-01-04 21:18:45 +00001517 const T *First = D.getFirstDeclaration();
Rafael Espindolaf4187652013-02-14 01:18:37 +00001518 if (First->getDeclContext()->isExternCContext())
1519 return CLanguageLinkage;
1520 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001521}
1522
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001523template<typename T>
1524static bool isExternCTemplate(const T &D) {
1525 // Since the context is ignored for class members, they can only have C++
1526 // language linkage or no language linkage.
1527 const DeclContext *DC = D.getDeclContext();
1528 if (DC->isRecord()) {
1529 assert(D.getASTContext().getLangOpts().CPlusPlus);
1530 return false;
1531 }
1532
1533 return D.getLanguageLinkage() == CLanguageLinkage;
1534}
1535
Rafael Espindolaf4187652013-02-14 01:18:37 +00001536LanguageLinkage VarDecl::getLanguageLinkage() const {
1537 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001538}
1539
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001540bool VarDecl::isExternC() const {
1541 return isExternCTemplate(*this);
1542}
1543
Sebastian Redl833ef452010-01-26 22:01:41 +00001544VarDecl *VarDecl::getCanonicalDecl() {
1545 return getFirstDeclaration();
1546}
1547
Daniel Dunbar9d355812012-03-09 01:51:51 +00001548VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1549 ASTContext &C) const
1550{
Sebastian Redl35351a92010-01-31 22:27:38 +00001551 // C++ [basic.def]p2:
1552 // A declaration is a definition unless [...] it contains the 'extern'
1553 // specifier or a linkage-specification and neither an initializer [...],
1554 // it declares a static data member in a class declaration [...].
1555 // C++ [temp.expl.spec]p15:
1556 // An explicit specialization of a static data member of a template is a
1557 // definition if the declaration includes an initializer; otherwise, it is
1558 // a declaration.
1559 if (isStaticDataMember()) {
1560 if (isOutOfLine() && (hasInit() ||
1561 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1562 return Definition;
1563 else
1564 return DeclarationOnly;
1565 }
1566 // C99 6.7p5:
1567 // A definition of an identifier is a declaration for that identifier that
1568 // [...] causes storage to be reserved for that object.
1569 // Note: that applies for all non-file-scope objects.
1570 // C99 6.9.2p1:
1571 // If the declaration of an identifier for an object has file scope and an
1572 // initializer, the declaration is an external definition for the identifier
1573 if (hasInit())
1574 return Definition;
1575 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1576 if (hasExternalStorage())
1577 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00001578
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001579 if (hasExternalStorage()) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00001580 for (const VarDecl *PrevVar = getPreviousDecl();
1581 PrevVar; PrevVar = PrevVar->getPreviousDecl()) {
Rafael Espindola7581f322012-12-17 22:23:47 +00001582 if (PrevVar->getLinkage() == InternalLinkage)
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001583 return DeclarationOnly;
1584 }
1585 }
Sebastian Redl35351a92010-01-31 22:27:38 +00001586 // C99 6.9.2p2:
1587 // A declaration of an object that has file scope without an initializer,
1588 // and without a storage class specifier or the scs 'static', constitutes
1589 // a tentative definition.
1590 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001591 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00001592 return TentativeDefinition;
1593
1594 // What's left is (in C, block-scope) declarations without initializers or
1595 // external storage. These are definitions.
1596 return Definition;
1597}
1598
Sebastian Redl35351a92010-01-31 22:27:38 +00001599VarDecl *VarDecl::getActingDefinition() {
1600 DefinitionKind Kind = isThisDeclarationADefinition();
1601 if (Kind != TentativeDefinition)
1602 return 0;
1603
Chris Lattner48eb14d2010-06-14 18:31:46 +00001604 VarDecl *LastTentative = 0;
Sebastian Redl35351a92010-01-31 22:27:38 +00001605 VarDecl *First = getFirstDeclaration();
1606 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1607 I != E; ++I) {
1608 Kind = (*I)->isThisDeclarationADefinition();
1609 if (Kind == Definition)
1610 return 0;
1611 else if (Kind == TentativeDefinition)
1612 LastTentative = *I;
1613 }
1614 return LastTentative;
1615}
1616
1617bool VarDecl::isTentativeDefinitionNow() const {
1618 DefinitionKind Kind = isThisDeclarationADefinition();
1619 if (Kind != TentativeDefinition)
1620 return false;
1621
1622 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1623 if ((*I)->isThisDeclarationADefinition() == Definition)
1624 return false;
1625 }
Sebastian Redl5ca79842010-02-01 20:16:42 +00001626 return true;
Sebastian Redl35351a92010-01-31 22:27:38 +00001627}
1628
Daniel Dunbar9d355812012-03-09 01:51:51 +00001629VarDecl *VarDecl::getDefinition(ASTContext &C) {
Sebastian Redlccdb5ff2010-02-02 17:55:12 +00001630 VarDecl *First = getFirstDeclaration();
1631 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1632 I != E; ++I) {
Daniel Dunbar9d355812012-03-09 01:51:51 +00001633 if ((*I)->isThisDeclarationADefinition(C) == Definition)
Sebastian Redl5ca79842010-02-01 20:16:42 +00001634 return *I;
1635 }
1636 return 0;
1637}
1638
Daniel Dunbar9d355812012-03-09 01:51:51 +00001639VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00001640 DefinitionKind Kind = DeclarationOnly;
1641
1642 const VarDecl *First = getFirstDeclaration();
1643 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001644 I != E; ++I) {
Daniel Dunbar9d355812012-03-09 01:51:51 +00001645 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001646 if (Kind == Definition)
1647 break;
1648 }
John McCall37bb6c92010-10-29 22:22:43 +00001649
1650 return Kind;
1651}
1652
Sebastian Redl5ca79842010-02-01 20:16:42 +00001653const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Sebastian Redl833ef452010-01-26 22:01:41 +00001654 redecl_iterator I = redecls_begin(), E = redecls_end();
1655 while (I != E && !I->getInit())
1656 ++I;
1657
1658 if (I != E) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001659 D = *I;
Sebastian Redl833ef452010-01-26 22:01:41 +00001660 return I->getInit();
1661 }
1662 return 0;
1663}
1664
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001665bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00001666 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001667 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001668
1669 if (!isStaticDataMember())
1670 return false;
1671
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001672 // If this static data member was instantiated from a static data member of
1673 // a class template, check whether that static data member was defined
1674 // out-of-line.
1675 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1676 return VD->isOutOfLine();
1677
1678 return false;
1679}
1680
Douglas Gregor1d957a32009-10-27 18:42:08 +00001681VarDecl *VarDecl::getOutOfLineDefinition() {
1682 if (!isStaticDataMember())
1683 return 0;
1684
1685 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1686 RD != RDEnd; ++RD) {
1687 if (RD->getLexicalDeclContext()->isFileContext())
1688 return *RD;
1689 }
1690
1691 return 0;
1692}
1693
Douglas Gregord5058122010-02-11 01:19:42 +00001694void VarDecl::setInit(Expr *I) {
Sebastian Redl833ef452010-01-26 22:01:41 +00001695 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1696 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00001697 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00001698 }
1699
1700 Init = I;
1701}
1702
Daniel Dunbar9d355812012-03-09 01:51:51 +00001703bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001704 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00001705
Richard Smith35ecb362012-03-02 04:14:40 +00001706 if (!Lang.CPlusPlus)
1707 return false;
1708
1709 // In C++11, any variable of reference type can be used in a constant
1710 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001711 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00001712 return true;
1713
1714 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00001715 // not require the variable to be non-volatile, but we consider this to be a
1716 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00001717 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00001718 return false;
1719
1720 // In C++, const, non-volatile variables of integral or enumeration types
1721 // can be used in constant expressions.
1722 if (getType()->isIntegralOrEnumerationType())
1723 return true;
1724
Richard Smith35ecb362012-03-02 04:14:40 +00001725 // Additionally, in C++11, non-volatile constexpr variables can be used in
1726 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001727 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00001728}
1729
Richard Smithd0b4dd62011-12-19 06:19:21 +00001730/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1731/// form, which contains extra information on the evaluated value of the
1732/// initializer.
1733EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1734 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1735 if (!Eval) {
1736 Stmt *S = Init.get<Stmt *>();
1737 Eval = new (getASTContext()) EvaluatedStmt;
1738 Eval->Value = S;
1739 Init = Eval;
1740 }
1741 return Eval;
1742}
1743
Richard Smithdafff942012-01-14 04:30:29 +00001744APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001745 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00001746 return evaluateValue(Notes);
1747}
1748
1749APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001750 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001751 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1752
1753 // We only produce notes indicating why an initializer is non-constant the
1754 // first time it is evaluated. FIXME: The notes won't always be emitted the
1755 // first time we try evaluation, so might not be produced at all.
1756 if (Eval->WasEvaluated)
Richard Smithdafff942012-01-14 04:30:29 +00001757 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001758
1759 const Expr *Init = cast<Expr>(Eval->Value);
1760 assert(!Init->isValueDependent());
1761
1762 if (Eval->IsEvaluating) {
1763 // FIXME: Produce a diagnostic for self-initialization.
1764 Eval->CheckedICE = true;
1765 Eval->IsICE = false;
Richard Smithdafff942012-01-14 04:30:29 +00001766 return 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001767 }
1768
1769 Eval->IsEvaluating = true;
1770
1771 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1772 this, Notes);
1773
1774 // Ensure the result is an uninitialized APValue if evaluation fails.
1775 if (!Result)
1776 Eval->Evaluated = APValue();
1777
1778 Eval->IsEvaluating = false;
1779 Eval->WasEvaluated = true;
1780
1781 // In C++11, we have determined whether the initializer was a constant
1782 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001783 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001784 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00001785 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00001786 }
1787
Richard Smithdafff942012-01-14 04:30:29 +00001788 return Result ? &Eval->Evaluated : 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001789}
1790
1791bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00001792 // Initializers of weak variables are never ICEs.
1793 if (isWeak())
1794 return false;
1795
Richard Smithd0b4dd62011-12-19 06:19:21 +00001796 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1797 if (Eval->CheckedICE)
1798 // We have already checked whether this subexpression is an
1799 // integral constant expression.
1800 return Eval->IsICE;
1801
1802 const Expr *Init = cast<Expr>(Eval->Value);
1803 assert(!Init->isValueDependent());
1804
1805 // In C++11, evaluate the initializer to check whether it's a constant
1806 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001807 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001808 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001809 evaluateValue(Notes);
1810 return Eval->IsICE;
1811 }
1812
1813 // It's an ICE whether or not the definition we found is
1814 // out-of-line. See DR 721 and the discussion in Clang PR
1815 // 6206 for details.
1816
1817 if (Eval->CheckingICE)
1818 return false;
1819 Eval->CheckingICE = true;
1820
1821 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1822 Eval->CheckingICE = false;
1823 Eval->CheckedICE = true;
1824 return Eval->IsICE;
1825}
1826
Douglas Gregorfe314812011-06-21 17:03:29 +00001827bool VarDecl::extendsLifetimeOfTemporary() const {
Douglas Gregord410c082011-06-21 18:20:46 +00001828 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
Douglas Gregorfe314812011-06-21 17:03:29 +00001829
1830 const Expr *E = getInit();
1831 if (!E)
1832 return false;
1833
1834 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1835 E = Cleanups->getSubExpr();
1836
1837 return isa<MaterializeTemporaryExpr>(E);
1838}
1839
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001840VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001841 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001842 return cast<VarDecl>(MSI->getInstantiatedFrom());
1843
1844 return 0;
1845}
1846
Douglas Gregor3c74d412009-10-14 20:14:33 +00001847TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001848 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001849 return MSI->getTemplateSpecializationKind();
1850
1851 return TSK_Undeclared;
1852}
1853
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001854MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001855 return getASTContext().getInstantiatedFromStaticDataMember(this);
1856}
1857
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001858void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1859 SourceLocation PointOfInstantiation) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001860 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00001861 assert(MSI && "Not an instantiated static data member?");
1862 MSI->setTemplateSpecializationKind(TSK);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001863 if (TSK != TSK_ExplicitSpecialization &&
1864 PointOfInstantiation.isValid() &&
1865 MSI->getPointOfInstantiation().isInvalid())
1866 MSI->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001867}
1868
Sebastian Redl833ef452010-01-26 22:01:41 +00001869//===----------------------------------------------------------------------===//
1870// ParmVarDecl Implementation
1871//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00001872
Sebastian Redl833ef452010-01-26 22:01:41 +00001873ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001874 SourceLocation StartLoc,
1875 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00001876 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001877 StorageClass S, Expr *DefArg) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001878 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001879 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00001880}
1881
Douglas Gregor72172e92012-01-05 21:55:30 +00001882ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1883 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
1884 return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001885 0, QualType(), 0, SC_None, 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00001886}
1887
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00001888SourceRange ParmVarDecl::getSourceRange() const {
1889 if (!hasInheritedDefaultArg()) {
1890 SourceRange ArgRange = getDefaultArgRange();
1891 if (ArgRange.isValid())
1892 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1893 }
1894
1895 return DeclaratorDecl::getSourceRange();
1896}
1897
Sebastian Redl833ef452010-01-26 22:01:41 +00001898Expr *ParmVarDecl::getDefaultArg() {
1899 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1900 assert(!hasUninstantiatedDefaultArg() &&
1901 "Default argument is not yet instantiated!");
1902
1903 Expr *Arg = getInit();
John McCall5d413782010-12-06 08:20:24 +00001904 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00001905 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00001906
Sebastian Redl833ef452010-01-26 22:01:41 +00001907 return Arg;
1908}
1909
Sebastian Redl833ef452010-01-26 22:01:41 +00001910SourceRange ParmVarDecl::getDefaultArgRange() const {
1911 if (const Expr *E = getInit())
1912 return E->getSourceRange();
1913
1914 if (hasUninstantiatedDefaultArg())
1915 return getUninstantiatedDefaultArg()->getSourceRange();
1916
1917 return SourceRange();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00001918}
1919
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00001920bool ParmVarDecl::isParameterPack() const {
1921 return isa<PackExpansionType>(getType());
1922}
1923
Ted Kremenek540017e2011-10-06 05:00:56 +00001924void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1925 getASTContext().setParameterIndex(this, parameterIndex);
1926 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1927}
1928
1929unsigned ParmVarDecl::getParameterIndexLarge() const {
1930 return getASTContext().getParameterIndex(this);
1931}
1932
Nuno Lopes394ec982008-12-17 23:39:55 +00001933//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00001934// FunctionDecl Implementation
1935//===----------------------------------------------------------------------===//
1936
Benjamin Kramer9170e912013-02-22 15:46:01 +00001937void FunctionDecl::getNameForDiagnostic(
1938 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
1939 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00001940 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1941 if (TemplateArgs)
Benjamin Kramer9170e912013-02-22 15:46:01 +00001942 TemplateSpecializationType::PrintTemplateArgumentList(
1943 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00001944}
1945
Ted Kremenek186a0742010-04-29 16:49:01 +00001946bool FunctionDecl::isVariadic() const {
1947 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1948 return FT->isVariadic();
1949 return false;
1950}
1951
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001952bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1953 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Francois Pichet1c229c02011-04-22 22:18:13 +00001954 if (I->Body || I->IsLateTemplateParsed) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001955 Definition = *I;
1956 return true;
1957 }
1958 }
1959
1960 return false;
1961}
1962
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001963bool FunctionDecl::hasTrivialBody() const
1964{
1965 Stmt *S = getBody();
1966 if (!S) {
1967 // Since we don't have a body for this function, we don't know if it's
1968 // trivial or not.
1969 return false;
1970 }
1971
1972 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
1973 return true;
1974 return false;
1975}
1976
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001977bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
1978 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00001979 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001980 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
1981 return true;
1982 }
1983 }
1984
1985 return false;
1986}
1987
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001988Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Argyrios Kyrtzidis1506d9b2009-07-14 03:20:21 +00001989 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1990 if (I->Body) {
1991 Definition = *I;
1992 return I->Body.get(getASTContext().getExternalSource());
Francois Pichet1c229c02011-04-22 22:18:13 +00001993 } else if (I->IsLateTemplateParsed) {
1994 Definition = *I;
1995 return 0;
Douglas Gregor89f238c2008-04-21 02:02:58 +00001996 }
1997 }
1998
1999 return 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002000}
2001
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002002void FunctionDecl::setBody(Stmt *B) {
2003 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002004 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002005 EndRangeLoc = B->getLocEnd();
2006}
2007
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002008void FunctionDecl::setPure(bool P) {
2009 IsPure = P;
2010 if (P)
2011 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2012 Parent->markedVirtualFunctionPure();
2013}
2014
Douglas Gregor16618f22009-09-12 00:17:51 +00002015bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002016 const TranslationUnitDecl *tunit =
2017 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2018 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002019 !tunit->getASTContext().getLangOpts().Freestanding &&
John McCall53ffd372011-05-15 17:49:20 +00002020 getIdentifier() &&
2021 getIdentifier()->isStr("main");
2022}
2023
2024bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2025 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2026 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2027 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2028 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2029 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2030
2031 if (isa<CXXRecordDecl>(getDeclContext())) return false;
2032 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
2033
2034 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
2035 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
2036
2037 ASTContext &Context =
2038 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2039 ->getASTContext();
2040
2041 // The result type and first argument type are constant across all
2042 // these operators. The second argument must be exactly void*.
2043 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002044}
2045
Rafael Espindolaf4187652013-02-14 01:18:37 +00002046LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Rafael Espindola6239e052013-01-12 15:27:44 +00002047 // Users expect to be able to write
2048 // extern "C" void *__builtin_alloca (size_t);
2049 // so consider builtins as having C language linkage.
Rafael Espindolac48f7342013-01-12 15:27:43 +00002050 if (getBuiltinID())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002051 return CLanguageLinkage;
Rafael Espindolac48f7342013-01-12 15:27:43 +00002052
Rafael Espindolaf4187652013-02-14 01:18:37 +00002053 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002054}
2055
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002056bool FunctionDecl::isExternC() const {
2057 return isExternCTemplate(*this);
2058}
2059
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002060bool FunctionDecl::isGlobal() const {
2061 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2062 return Method->isStatic();
2063
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002064 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002065 return false;
2066
Mike Stump11289f42009-09-09 15:08:12 +00002067 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002068 DC->isNamespace();
2069 DC = DC->getParent()) {
2070 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2071 if (!Namespace->getDeclName())
2072 return false;
2073 break;
2074 }
2075 }
2076
2077 return true;
2078}
2079
Richard Smith10876ef2013-01-17 01:30:42 +00002080bool FunctionDecl::isNoReturn() const {
2081 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
Richard Smithdebc59d2013-01-30 05:45:05 +00002082 hasAttr<C11NoReturnAttr>() ||
Richard Smith10876ef2013-01-17 01:30:42 +00002083 getType()->getAs<FunctionType>()->getNoReturnAttr();
2084}
2085
Sebastian Redl833ef452010-01-26 22:01:41 +00002086void
2087FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2088 redeclarable_base::setPreviousDeclaration(PrevDecl);
2089
2090 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2091 FunctionTemplateDecl *PrevFunTmpl
2092 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
2093 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2094 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
2095 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002096
Axel Naumannfbc7b982011-11-08 18:21:06 +00002097 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002098 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002099}
2100
2101const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
2102 return getFirstDeclaration();
2103}
2104
2105FunctionDecl *FunctionDecl::getCanonicalDecl() {
2106 return getFirstDeclaration();
2107}
2108
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002109/// \brief Returns a value indicating whether this function
2110/// corresponds to a builtin function.
2111///
2112/// The function corresponds to a built-in function if it is
2113/// declared at translation scope or within an extern "C" block and
2114/// its name matches with the name of a builtin. The returned value
2115/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002116/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002117/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002118unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002119 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002120 return 0;
2121
2122 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002123 if (!BuiltinID)
2124 return 0;
2125
2126 ASTContext &Context = getASTContext();
Douglas Gregore711f702009-02-14 18:57:46 +00002127 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2128 return BuiltinID;
2129
2130 // This function has the name of a known C library
2131 // function. Determine whether it actually refers to the C library
2132 // function or whether it just has the same name.
2133
Douglas Gregora908e7f2009-02-17 03:23:10 +00002134 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002135 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002136 return 0;
2137
Douglas Gregore711f702009-02-14 18:57:46 +00002138 // If this function is at translation-unit scope and we're not in
2139 // C++, it refers to the C library function.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002140 if (!Context.getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +00002141 getDeclContext()->isTranslationUnit())
2142 return BuiltinID;
2143
2144 // If the function is in an extern "C" linkage specification and is
2145 // not marked "overloadable", it's the real function.
2146 if (isa<LinkageSpecDecl>(getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002147 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
Douglas Gregore711f702009-02-14 18:57:46 +00002148 == LinkageSpecDecl::lang_c &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002149 !getAttr<OverloadableAttr>())
Douglas Gregore711f702009-02-14 18:57:46 +00002150 return BuiltinID;
2151
2152 // Not a builtin
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002153 return 0;
2154}
2155
2156
Chris Lattner47c0d002009-04-25 06:03:53 +00002157/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002158/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002159/// after it has been created.
2160unsigned FunctionDecl::getNumParams() const {
Eli Friedman5c27c4c2012-08-30 22:22:09 +00002161 const FunctionType *FT = getType()->castAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002162 if (isa<FunctionNoProtoType>(FT))
Chris Lattner88f70d62008-03-15 05:43:15 +00002163 return 0;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002164 return cast<FunctionProtoType>(FT)->getNumArgs();
Mike Stump11289f42009-09-09 15:08:12 +00002165
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002166}
2167
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002168void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002169 ArrayRef<ParmVarDecl *> NewParamInfo) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002170 assert(ParamInfo == 0 && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002171 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002172
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002173 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002174 if (!NewParamInfo.empty()) {
2175 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2176 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002177 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002178}
Chris Lattner41943152007-01-25 04:52:46 +00002179
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002180void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
James Molloy6f8780b2012-02-29 10:24:19 +00002181 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2182
2183 if (!NewDecls.empty()) {
2184 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2185 std::copy(NewDecls.begin(), NewDecls.end(), A);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002186 DeclsInPrototypeScope = ArrayRef<NamedDecl *>(A, NewDecls.size());
James Molloy6f8780b2012-02-29 10:24:19 +00002187 }
2188}
2189
Chris Lattner58258242008-04-10 02:22:51 +00002190/// getMinRequiredArguments - Returns the minimum number of arguments
2191/// needed to call this function. This may be fewer than the number of
2192/// function parameters, if some of the parameters have default
Douglas Gregor7825bf32011-01-06 22:09:01 +00002193/// arguments (in C++) or the last parameter is a parameter pack.
Chris Lattner58258242008-04-10 02:22:51 +00002194unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002195 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002196 return getNumParams();
2197
Douglas Gregor7825bf32011-01-06 22:09:01 +00002198 unsigned NumRequiredArgs = getNumParams();
2199
2200 // If the last parameter is a parameter pack, we don't need an argument for
2201 // it.
2202 if (NumRequiredArgs > 0 &&
2203 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
2204 --NumRequiredArgs;
2205
2206 // If this parameter has a default argument, we don't need an argument for
2207 // it.
2208 while (NumRequiredArgs > 0 &&
2209 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
Chris Lattner58258242008-04-10 02:22:51 +00002210 --NumRequiredArgs;
2211
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002212 // We might have parameter packs before the end. These can't be deduced,
2213 // but they can still handle multiple arguments.
2214 unsigned ArgIdx = NumRequiredArgs;
2215 while (ArgIdx > 0) {
2216 if (getParamDecl(ArgIdx - 1)->isParameterPack())
2217 NumRequiredArgs = ArgIdx;
2218
2219 --ArgIdx;
2220 }
2221
Chris Lattner58258242008-04-10 02:22:51 +00002222 return NumRequiredArgs;
2223}
2224
Eli Friedman1b125c32012-02-07 03:50:18 +00002225static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2226 // Only consider file-scope declarations in this test.
2227 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2228 return false;
2229
2230 // Only consider explicit declarations; the presence of a builtin for a
2231 // libcall shouldn't affect whether a definition is externally visible.
2232 if (Redecl->isImplicit())
2233 return false;
2234
2235 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2236 return true; // Not an inline definition
2237
2238 return false;
2239}
2240
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002241/// \brief For a function declaration in C or C++, determine whether this
2242/// declaration causes the definition to be externally visible.
2243///
Eli Friedman1b125c32012-02-07 03:50:18 +00002244/// Specifically, this determines if adding the current declaration to the set
2245/// of redeclarations of the given functions causes
2246/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002247bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2248 assert(!doesThisDeclarationHaveABody() &&
2249 "Must have a declaration without a body.");
2250
2251 ASTContext &Context = getASTContext();
2252
David Blaikiebbafb8a2012-03-11 07:00:24 +00002253 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002254 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2255 // an externally visible definition.
2256 //
2257 // FIXME: What happens if gnu_inline gets added on after the first
2258 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002259 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002260 return false;
2261
2262 const FunctionDecl *Prev = this;
2263 bool FoundBody = false;
2264 while ((Prev = Prev->getPreviousDecl())) {
2265 FoundBody |= Prev->Body;
2266
2267 if (Prev->Body) {
2268 // If it's not the case that both 'inline' and 'extern' are
2269 // specified on the definition, then it is always externally visible.
2270 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002271 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002272 return false;
2273 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002274 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002275 return false;
2276 }
2277 }
2278 return FoundBody;
2279 }
2280
David Blaikiebbafb8a2012-03-11 07:00:24 +00002281 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002282 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002283
2284 // C99 6.7.4p6:
2285 // [...] If all of the file scope declarations for a function in a
2286 // translation unit include the inline function specifier without extern,
2287 // then the definition in that translation unit is an inline definition.
2288 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002289 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002290 const FunctionDecl *Prev = this;
2291 bool FoundBody = false;
2292 while ((Prev = Prev->getPreviousDecl())) {
2293 FoundBody |= Prev->Body;
2294 if (RedeclForcesDefC99(Prev))
2295 return false;
2296 }
2297 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002298}
2299
Richard Smithf3814ad2013-01-25 00:08:28 +00002300/// \brief For an inline function definition in C, or for a gnu_inline function
2301/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002302///
2303/// Inline function definitions are always available for inlining optimizations.
2304/// However, depending on the language dialect, declaration specifiers, and
2305/// attributes, the definition of an inline function may or may not be
2306/// "externally" visible to other translation units in the program.
2307///
2308/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00002309/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00002310/// inline definition becomes externally visible (C99 6.7.4p6).
2311///
2312/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2313/// definition, we use the GNU semantics for inline, which are nearly the
2314/// opposite of C99 semantics. In particular, "inline" by itself will create
2315/// an externally visible symbol, but "extern inline" will not create an
2316/// externally visible symbol.
2317bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002318 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002319 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00002320 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00002321
David Blaikiebbafb8a2012-03-11 07:00:24 +00002322 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002323 // Note: If you change the logic here, please change
2324 // doesDeclarationForceExternallyVisibleDefinition as well.
2325 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00002326 // If it's not the case that both 'inline' and 'extern' are
2327 // specified on the definition, then this inline definition is
2328 // externally visible.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002329 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00002330 return true;
2331
2332 // If any declaration is 'inline' but not 'extern', then this definition
2333 // is externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002334 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2335 Redecl != RedeclEnd;
2336 ++Redecl) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00002337 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002338 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00002339 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00002340 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00002341
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002342 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002343 }
Eli Friedman1b125c32012-02-07 03:50:18 +00002344
Richard Smithf3814ad2013-01-25 00:08:28 +00002345 // The rest of this function is C-only.
2346 assert(!Context.getLangOpts().CPlusPlus &&
2347 "should not use C inline rules in C++");
2348
Douglas Gregor299d76e2009-09-13 07:46:26 +00002349 // C99 6.7.4p6:
2350 // [...] If all of the file scope declarations for a function in a
2351 // translation unit include the inline function specifier without extern,
2352 // then the definition in that translation unit is an inline definition.
2353 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2354 Redecl != RedeclEnd;
2355 ++Redecl) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002356 if (RedeclForcesDefC99(*Redecl))
2357 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002358 }
2359
2360 // C99 6.7.4p6:
2361 // An inline definition does not provide an external definition for the
2362 // function, and does not forbid an external definition in another
2363 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002364 return false;
2365}
2366
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002367/// getOverloadedOperator - Which C++ overloaded operator this
2368/// function represents, if any.
2369OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00002370 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2371 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002372 else
2373 return OO_None;
2374}
2375
Alexis Huntc88db062010-01-13 09:01:02 +00002376/// getLiteralIdentifier - The literal suffix identifier this function
2377/// represents, if any.
2378const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2379 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2380 return getDeclName().getCXXLiteralIdentifier();
2381 else
2382 return 0;
2383}
2384
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002385FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2386 if (TemplateOrSpecialization.isNull())
2387 return TK_NonTemplate;
2388 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2389 return TK_FunctionTemplate;
2390 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2391 return TK_MemberSpecialization;
2392 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2393 return TK_FunctionTemplateSpecialization;
2394 if (TemplateOrSpecialization.is
2395 <DependentFunctionTemplateSpecializationInfo*>())
2396 return TK_DependentFunctionTemplateSpecialization;
2397
David Blaikie83d382b2011-09-23 05:06:16 +00002398 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002399}
2400
Douglas Gregord801b062009-10-07 23:56:10 +00002401FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002402 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00002403 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2404
2405 return 0;
2406}
2407
2408void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002409FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2410 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00002411 TemplateSpecializationKind TSK) {
2412 assert(TemplateOrSpecialization.isNull() &&
2413 "Member function is already a specialization");
2414 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002415 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00002416 TemplateOrSpecialization = Info;
2417}
2418
Douglas Gregorafca3b42009-10-27 20:53:28 +00002419bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00002420 // If the function is invalid, it can't be implicitly instantiated.
2421 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00002422 return false;
2423
2424 switch (getTemplateSpecializationKind()) {
2425 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00002426 case TSK_ExplicitInstantiationDefinition:
2427 return false;
2428
2429 case TSK_ImplicitInstantiation:
2430 return true;
2431
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002432 // It is possible to instantiate TSK_ExplicitSpecialization kind
2433 // if the FunctionDecl has a class scope specialization pattern.
2434 case TSK_ExplicitSpecialization:
2435 return getClassScopeSpecializationPattern() != 0;
2436
Douglas Gregorafca3b42009-10-27 20:53:28 +00002437 case TSK_ExplicitInstantiationDeclaration:
2438 // Handled below.
2439 break;
2440 }
2441
2442 // Find the actual template from which we will instantiate.
2443 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002444 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00002445 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002446 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00002447
2448 // C++0x [temp.explicit]p9:
2449 // Except for inline functions, other explicit instantiation declarations
2450 // have the effect of suppressing the implicit instantiation of the entity
2451 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002452 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00002453 return true;
2454
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002455 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00002456}
2457
2458bool FunctionDecl::isTemplateInstantiation() const {
2459 switch (getTemplateSpecializationKind()) {
2460 case TSK_Undeclared:
2461 case TSK_ExplicitSpecialization:
2462 return false;
2463 case TSK_ImplicitInstantiation:
2464 case TSK_ExplicitInstantiationDeclaration:
2465 case TSK_ExplicitInstantiationDefinition:
2466 return true;
2467 }
2468 llvm_unreachable("All TSK values handled.");
2469}
Douglas Gregorafca3b42009-10-27 20:53:28 +00002470
2471FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002472 // Handle class scope explicit specialization special case.
2473 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2474 return getClassScopeSpecializationPattern();
2475
Douglas Gregorafca3b42009-10-27 20:53:28 +00002476 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2477 while (Primary->getInstantiatedFromMemberTemplate()) {
2478 // If we have hit a point where the user provided a specialization of
2479 // this template, we're done looking.
2480 if (Primary->isMemberSpecialization())
2481 break;
2482
2483 Primary = Primary->getInstantiatedFromMemberTemplate();
2484 }
2485
2486 return Primary->getTemplatedDecl();
2487 }
2488
2489 return getInstantiatedFromMemberFunction();
2490}
2491
Douglas Gregor70d83e22009-06-29 17:30:29 +00002492FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00002493 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002494 = TemplateOrSpecialization
2495 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00002496 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00002497 }
2498 return 0;
2499}
2500
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002501FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2502 return getASTContext().getClassScopeSpecializationPattern(this);
2503}
2504
Douglas Gregor70d83e22009-06-29 17:30:29 +00002505const TemplateArgumentList *
2506FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00002507 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00002508 = TemplateOrSpecialization
2509 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00002510 return Info->TemplateArguments;
2511 }
2512 return 0;
2513}
2514
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00002515const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002516FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2517 if (FunctionTemplateSpecializationInfo *Info
2518 = TemplateOrSpecialization
2519 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2520 return Info->TemplateArgumentsAsWritten;
2521 }
2522 return 0;
2523}
2524
Mike Stump11289f42009-09-09 15:08:12 +00002525void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002526FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2527 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002528 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002529 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002530 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00002531 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2532 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002533 assert(TSK != TSK_Undeclared &&
2534 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00002535 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002536 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002537 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00002538 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2539 TemplateArgs,
2540 TemplateArgsAsWritten,
2541 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002542 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00002543 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002544}
2545
John McCallb9c78482010-04-08 09:05:18 +00002546void
2547FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2548 const UnresolvedSetImpl &Templates,
2549 const TemplateArgumentListInfo &TemplateArgs) {
2550 assert(TemplateOrSpecialization.isNull());
2551 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2552 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall900d9802010-04-13 22:18:28 +00002553 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallb9c78482010-04-08 09:05:18 +00002554 void *Buffer = Context.Allocate(Size);
2555 DependentFunctionTemplateSpecializationInfo *Info =
2556 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2557 TemplateArgs);
2558 TemplateOrSpecialization = Info;
2559}
2560
2561DependentFunctionTemplateSpecializationInfo::
2562DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2563 const TemplateArgumentListInfo &TArgs)
2564 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2565
2566 d.NumTemplates = Ts.size();
2567 d.NumArgs = TArgs.size();
2568
2569 FunctionTemplateDecl **TsArray =
2570 const_cast<FunctionTemplateDecl**>(getTemplates());
2571 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2572 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2573
2574 TemplateArgumentLoc *ArgsArray =
2575 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2576 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2577 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2578}
2579
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002580TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00002581 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002582 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00002583 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00002584 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00002585 if (FTSInfo)
2586 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00002587
Douglas Gregord801b062009-10-07 23:56:10 +00002588 MemberSpecializationInfo *MSInfo
2589 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2590 if (MSInfo)
2591 return MSInfo->getTemplateSpecializationKind();
2592
2593 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002594}
2595
Mike Stump11289f42009-09-09 15:08:12 +00002596void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002597FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2598 SourceLocation PointOfInstantiation) {
2599 if (FunctionTemplateSpecializationInfo *FTSInfo
2600 = TemplateOrSpecialization.dyn_cast<
2601 FunctionTemplateSpecializationInfo*>()) {
2602 FTSInfo->setTemplateSpecializationKind(TSK);
2603 if (TSK != TSK_ExplicitSpecialization &&
2604 PointOfInstantiation.isValid() &&
2605 FTSInfo->getPointOfInstantiation().isInvalid())
2606 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2607 } else if (MemberSpecializationInfo *MSInfo
2608 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2609 MSInfo->setTemplateSpecializationKind(TSK);
2610 if (TSK != TSK_ExplicitSpecialization &&
2611 PointOfInstantiation.isValid() &&
2612 MSInfo->getPointOfInstantiation().isInvalid())
2613 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2614 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002615 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002616}
2617
2618SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00002619 if (FunctionTemplateSpecializationInfo *FTSInfo
2620 = TemplateOrSpecialization.dyn_cast<
2621 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002622 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00002623 else if (MemberSpecializationInfo *MSInfo
2624 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002625 return MSInfo->getPointOfInstantiation();
2626
2627 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00002628}
2629
Douglas Gregor6411b922009-09-11 20:15:17 +00002630bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002631 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00002632 return true;
2633
2634 // If this function was instantiated from a member function of a
2635 // class template, check whether that member function was defined out-of-line.
2636 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2637 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002638 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002639 return Definition->isOutOfLine();
2640 }
2641
2642 // If this function was instantiated from a function template,
2643 // check whether that function template was defined out-of-line.
2644 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2645 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002646 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002647 return Definition->isOutOfLine();
2648 }
2649
2650 return false;
2651}
2652
Abramo Bagnaraea947882011-03-08 16:41:52 +00002653SourceRange FunctionDecl::getSourceRange() const {
2654 return SourceRange(getOuterLocStart(), EndRangeLoc);
2655}
2656
Anna Zaks28db7ce2012-01-18 02:45:01 +00002657unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00002658 IdentifierInfo *FnInfo = getIdentifier();
2659
2660 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00002661 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002662
2663 // Builtin handling.
2664 switch (getBuiltinID()) {
2665 case Builtin::BI__builtin_memset:
2666 case Builtin::BI__builtin___memset_chk:
2667 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00002668 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00002669
2670 case Builtin::BI__builtin_memcpy:
2671 case Builtin::BI__builtin___memcpy_chk:
2672 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00002673 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002674
2675 case Builtin::BI__builtin_memmove:
2676 case Builtin::BI__builtin___memmove_chk:
2677 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00002678 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00002679
2680 case Builtin::BIstrlcpy:
Anna Zaks22122702012-01-17 00:37:07 +00002681 return Builtin::BIstrlcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002682 case Builtin::BIstrlcat:
Anna Zaks22122702012-01-17 00:37:07 +00002683 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00002684
2685 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00002686 case Builtin::BImemcmp:
2687 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002688
2689 case Builtin::BI__builtin_strncpy:
2690 case Builtin::BI__builtin___strncpy_chk:
2691 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00002692 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002693
2694 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00002695 case Builtin::BIstrncmp:
2696 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002697
2698 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00002699 case Builtin::BIstrncasecmp:
2700 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002701
2702 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00002703 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00002704 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00002705 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00002706
2707 case Builtin::BI__builtin_strndup:
2708 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00002709 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00002710
Anna Zaks314cd092012-02-01 19:08:57 +00002711 case Builtin::BI__builtin_strlen:
2712 case Builtin::BIstrlen:
2713 return Builtin::BIstrlen;
2714
Anna Zaks201d4892012-01-13 21:52:01 +00002715 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00002716 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00002717 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00002718 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00002719 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00002720 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002721 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00002722 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00002723 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002724 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002725 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00002726 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002727 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002728 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002729 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002730 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002731 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00002732 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00002733 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00002734 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00002735 else if (FnInfo->isStr("strlen"))
2736 return Builtin::BIstrlen;
Anna Zaks201d4892012-01-13 21:52:01 +00002737 }
2738 break;
2739 }
Anna Zaks22122702012-01-17 00:37:07 +00002740 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002741}
2742
Chris Lattner59a25942008-03-31 00:36:02 +00002743//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002744// FieldDecl Implementation
2745//===----------------------------------------------------------------------===//
2746
Jay Foad39c79802011-01-12 09:06:06 +00002747FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002748 SourceLocation StartLoc, SourceLocation IdLoc,
2749 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00002750 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00002751 InClassInitStyle InitStyle) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002752 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +00002753 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00002754}
2755
Douglas Gregor72172e92012-01-05 21:55:30 +00002756FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2757 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
2758 return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
Richard Smith2b013182012-06-10 03:12:00 +00002759 0, QualType(), 0, 0, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00002760}
2761
Sebastian Redl833ef452010-01-26 22:01:41 +00002762bool FieldDecl::isAnonymousStructOrUnion() const {
2763 if (!isImplicit() || getDeclName())
2764 return false;
2765
2766 if (const RecordType *Record = getType()->getAs<RecordType>())
2767 return Record->getDecl()->isAnonymousStructOrUnion();
2768
2769 return false;
2770}
2771
Richard Smithcaf33902011-10-10 18:28:20 +00002772unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2773 assert(isBitField() && "not a bitfield");
2774 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2775 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2776}
2777
John McCall4e819612011-01-20 07:57:12 +00002778unsigned FieldDecl::getFieldIndex() const {
2779 if (CachedFieldIndex) return CachedFieldIndex - 1;
2780
Richard Smithd62306a2011-11-10 06:34:14 +00002781 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002782 const RecordDecl *RD = getParent();
2783 const FieldDecl *LastFD = 0;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00002784 bool IsMsStruct = RD->isMsStruct(getASTContext());
Richard Smithd62306a2011-11-10 06:34:14 +00002785
2786 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2787 I != E; ++I, ++Index) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00002788 I->CachedFieldIndex = Index + 1;
John McCall4e819612011-01-20 07:57:12 +00002789
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002790 if (IsMsStruct) {
2791 // Zero-length bitfields following non-bitfield members are ignored.
David Blaikie40ed2972012-06-06 20:45:41 +00002792 if (getASTContext().ZeroBitfieldFollowsNonBitfield(*I, LastFD)) {
Richard Smithd62306a2011-11-10 06:34:14 +00002793 --Index;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002794 continue;
2795 }
David Blaikie40ed2972012-06-06 20:45:41 +00002796 LastFD = *I;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002797 }
John McCall4e819612011-01-20 07:57:12 +00002798 }
2799
Richard Smithd62306a2011-11-10 06:34:14 +00002800 assert(CachedFieldIndex && "failed to find field in parent");
2801 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00002802}
2803
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002804SourceRange FieldDecl::getSourceRange() const {
Abramo Bagnaraff371ac2011-08-05 08:02:55 +00002805 if (const Expr *E = InitializerOrBitWidth.getPointer())
2806 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00002807 return DeclaratorDecl::getSourceRange();
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002808}
2809
Abramo Bagnarab1cdde72012-07-02 20:35:48 +00002810void FieldDecl::setBitWidth(Expr *Width) {
2811 assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
2812 "bit width or initializer already set");
2813 InitializerOrBitWidth.setPointer(Width);
2814}
2815
Richard Smith938f40b2011-06-11 17:19:42 +00002816void FieldDecl::setInClassInitializer(Expr *Init) {
Richard Smith2b013182012-06-10 03:12:00 +00002817 assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
Richard Smith938f40b2011-06-11 17:19:42 +00002818 "bit width or initializer already set");
2819 InitializerOrBitWidth.setPointer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00002820}
2821
Sebastian Redl833ef452010-01-26 22:01:41 +00002822//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002823// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00002824//===----------------------------------------------------------------------===//
2825
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002826SourceLocation TagDecl::getOuterLocStart() const {
2827 return getTemplateOrInnerLocStart(this);
2828}
2829
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002830SourceRange TagDecl::getSourceRange() const {
2831 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002832 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002833}
2834
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002835TagDecl* TagDecl::getCanonicalDecl() {
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002836 return getFirstDeclaration();
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002837}
2838
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00002839void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2840 TypedefNameDeclOrQualifier = TDD;
Douglas Gregora72a4e32010-05-19 18:39:18 +00002841 if (TypeForDecl)
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002842 assert(TypeForDecl->isLinkageValid());
2843 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00002844}
2845
Douglas Gregordee1be82009-01-17 00:42:38 +00002846void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002847 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00002848
David Blaikie095deba2012-11-14 01:52:05 +00002849 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
John McCall67da35c2010-02-04 22:26:26 +00002850 struct CXXRecordDecl::DefinitionData *Data =
2851 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
John McCall93cc7322010-03-26 21:56:38 +00002852 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2853 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00002854 }
Douglas Gregordee1be82009-01-17 00:42:38 +00002855}
2856
2857void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00002858 assert((!isa<CXXRecordDecl>(this) ||
2859 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2860 "definition completed but not started");
2861
John McCallf937c022011-10-07 06:10:15 +00002862 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002863 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00002864
2865 if (ASTMutationListener *L = getASTMutationListener())
2866 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00002867}
2868
John McCallf937c022011-10-07 06:10:15 +00002869TagDecl *TagDecl::getDefinition() const {
2870 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002871 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002872
2873 // If it's possible for us to have an out-of-date definition, check now.
2874 if (MayHaveOutOfDateDef) {
2875 if (IdentifierInfo *II = getIdentifier()) {
2876 if (II->isOutOfDate()) {
2877 updateOutOfDate(*II);
2878 }
2879 }
2880 }
2881
Andrew Trickba266ee2010-10-19 21:54:32 +00002882 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2883 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00002884
2885 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002886 R != REnd; ++R)
John McCallf937c022011-10-07 06:10:15 +00002887 if (R->isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002888 return *R;
Mike Stump11289f42009-09-09 15:08:12 +00002889
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002890 return 0;
Ted Kremenek21475702008-09-05 17:16:31 +00002891}
2892
Douglas Gregor14454802011-02-25 02:25:35 +00002893void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2894 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00002895 // Make sure the extended qualifier info is allocated.
2896 if (!hasExtInfo())
Richard Smithdda56e42011-04-15 14:24:37 +00002897 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00002898 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00002899 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002900 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00002901 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00002902 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00002903 if (getExtInfo()->NumTemplParamLists == 0) {
2904 getASTContext().Deallocate(getExtInfo());
Richard Smithdda56e42011-04-15 14:24:37 +00002905 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002906 }
2907 else
2908 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00002909 }
2910 }
2911}
2912
Abramo Bagnara60804e12011-03-18 15:16:37 +00002913void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2914 unsigned NumTPLists,
2915 TemplateParameterList **TPLists) {
2916 assert(NumTPLists > 0);
2917 // Make sure the extended decl info is allocated.
2918 if (!hasExtInfo())
2919 // Allocate external info struct.
Richard Smithdda56e42011-04-15 14:24:37 +00002920 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002921 // Set the template parameter lists info.
2922 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2923}
2924
Ted Kremenek21475702008-09-05 17:16:31 +00002925//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002926// EnumDecl Implementation
2927//===----------------------------------------------------------------------===//
2928
David Blaikie68e081d2011-12-20 02:48:34 +00002929void EnumDecl::anchor() { }
2930
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002931EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2932 SourceLocation StartLoc, SourceLocation IdLoc,
2933 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002934 EnumDecl *PrevDecl, bool IsScoped,
2935 bool IsScopedUsingClassTag, bool IsFixed) {
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002936 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002937 IsScoped, IsScopedUsingClassTag, IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002938 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00002939 C.getTypeDeclType(Enum, PrevDecl);
2940 return Enum;
2941}
2942
Douglas Gregor72172e92012-01-05 21:55:30 +00002943EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2944 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002945 EnumDecl *Enum = new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(),
2946 0, 0, false, false, false);
2947 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
2948 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00002949}
2950
Douglas Gregord5058122010-02-11 01:19:42 +00002951void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00002952 QualType NewPromotionType,
2953 unsigned NumPositiveBits,
2954 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00002955 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00002956 if (!IntegerType)
2957 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00002958 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00002959 setNumPositiveBits(NumPositiveBits);
2960 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00002961 TagDecl::completeDefinition();
2962}
2963
Richard Smith7d137e32012-03-23 03:33:32 +00002964TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
2965 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2966 return MSI->getTemplateSpecializationKind();
2967
2968 return TSK_Undeclared;
2969}
2970
2971void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2972 SourceLocation PointOfInstantiation) {
2973 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
2974 assert(MSI && "Not an instantiated member enumeration?");
2975 MSI->setTemplateSpecializationKind(TSK);
2976 if (TSK != TSK_ExplicitSpecialization &&
2977 PointOfInstantiation.isValid() &&
2978 MSI->getPointOfInstantiation().isInvalid())
2979 MSI->setPointOfInstantiation(PointOfInstantiation);
2980}
2981
Richard Smith4b38ded2012-03-14 23:13:10 +00002982EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
2983 if (SpecializationInfo)
2984 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
2985
2986 return 0;
2987}
2988
2989void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
2990 TemplateSpecializationKind TSK) {
2991 assert(!SpecializationInfo && "Member enum is already a specialization");
2992 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
2993}
2994
Sebastian Redl833ef452010-01-26 22:01:41 +00002995//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002996// RecordDecl Implementation
2997//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00002998
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002999RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
3000 SourceLocation StartLoc, SourceLocation IdLoc,
3001 IdentifierInfo *Id, RecordDecl *PrevDecl)
3002 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003003 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003004 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003005 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00003006 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003007 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00003008 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003009}
3010
Jay Foad39c79802011-01-12 09:06:06 +00003011RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003012 SourceLocation StartLoc, SourceLocation IdLoc,
3013 IdentifierInfo *Id, RecordDecl* PrevDecl) {
3014 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
3015 PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003016 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3017
Ted Kremenek21475702008-09-05 17:16:31 +00003018 C.getTypeDeclType(R, PrevDecl);
3019 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003020}
3021
Douglas Gregor72172e92012-01-05 21:55:30 +00003022RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
3023 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003024 RecordDecl *R = new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
3025 SourceLocation(), 0, 0);
3026 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3027 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003028}
3029
Douglas Gregordfcad112009-03-25 15:59:44 +00003030bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003031 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003032 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3033}
3034
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003035RecordDecl::field_iterator RecordDecl::field_begin() const {
3036 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3037 LoadFieldsFromExternalStorage();
3038
3039 return field_iterator(decl_iterator(FirstDecl));
3040}
3041
Douglas Gregorb11aad82011-02-19 18:51:44 +00003042/// completeDefinition - Notes that the definition of this type is now
3043/// complete.
3044void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003045 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003046 TagDecl::completeDefinition();
3047}
3048
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003049/// isMsStruct - Get whether or not this record uses ms_struct layout.
3050/// This which can be turned on with an attribute, pragma, or the
3051/// -mms-bitfields command-line option.
3052bool RecordDecl::isMsStruct(const ASTContext &C) const {
3053 return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3054}
3055
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003056static bool isFieldOrIndirectField(Decl::Kind K) {
3057 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3058}
3059
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003060void RecordDecl::LoadFieldsFromExternalStorage() const {
3061 ExternalASTSource *Source = getASTContext().getExternalSource();
3062 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3063
3064 // Notify that we have a RecordDecl doing some initialization.
3065 ExternalASTSource::Deserializing TheFields(Source);
3066
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003067 SmallVector<Decl*, 64> Decls;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003068 LoadedFieldsFromExternalStorage = true;
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003069 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3070 Decls)) {
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003071 case ELR_Success:
3072 break;
3073
3074 case ELR_AlreadyLoaded:
3075 case ELR_Failure:
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003076 return;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003077 }
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003078
3079#ifndef NDEBUG
3080 // Check that all decls we got were FieldDecls.
3081 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003082 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003083#endif
3084
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003085 if (Decls.empty())
3086 return;
3087
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003088 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
3089 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003090}
3091
Steve Naroff415d3d52008-10-08 17:01:13 +00003092//===----------------------------------------------------------------------===//
3093// BlockDecl Implementation
3094//===----------------------------------------------------------------------===//
3095
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003096void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Steve Naroffc4b30e52009-03-13 16:56:44 +00003097 assert(ParamInfo == 0 && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00003098
Steve Naroffc4b30e52009-03-13 16:56:44 +00003099 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003100 if (!NewParamInfo.empty()) {
3101 NumParams = NewParamInfo.size();
3102 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3103 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003104 }
3105}
3106
John McCall351762c2011-02-07 10:33:21 +00003107void BlockDecl::setCaptures(ASTContext &Context,
3108 const Capture *begin,
3109 const Capture *end,
3110 bool capturesCXXThis) {
John McCallc63de662011-02-02 13:00:07 +00003111 CapturesCXXThis = capturesCXXThis;
3112
3113 if (begin == end) {
John McCall351762c2011-02-07 10:33:21 +00003114 NumCaptures = 0;
3115 Captures = 0;
John McCallc63de662011-02-02 13:00:07 +00003116 return;
3117 }
3118
John McCall351762c2011-02-07 10:33:21 +00003119 NumCaptures = end - begin;
3120
3121 // Avoid new Capture[] because we don't want to provide a default
3122 // constructor.
3123 size_t allocationSize = NumCaptures * sizeof(Capture);
3124 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3125 memcpy(buffer, begin, allocationSize);
3126 Captures = static_cast<Capture*>(buffer);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003127}
Sebastian Redl833ef452010-01-26 22:01:41 +00003128
John McCallce45f882011-06-15 22:51:16 +00003129bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3130 for (capture_const_iterator
3131 i = capture_begin(), e = capture_end(); i != e; ++i)
3132 // Only auto vars can be captured, so no redeclaration worries.
3133 if (i->getVariable() == variable)
3134 return true;
3135
3136 return false;
3137}
3138
Douglas Gregor70226da2010-12-21 16:27:07 +00003139SourceRange BlockDecl::getSourceRange() const {
3140 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3141}
Sebastian Redl833ef452010-01-26 22:01:41 +00003142
3143//===----------------------------------------------------------------------===//
3144// Other Decl Allocation/Deallocation Method Implementations
3145//===----------------------------------------------------------------------===//
3146
David Blaikie68e081d2011-12-20 02:48:34 +00003147void TranslationUnitDecl::anchor() { }
3148
Sebastian Redl833ef452010-01-26 22:01:41 +00003149TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
3150 return new (C) TranslationUnitDecl(C);
3151}
3152
David Blaikie68e081d2011-12-20 02:48:34 +00003153void LabelDecl::anchor() { }
3154
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003155LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003156 SourceLocation IdentL, IdentifierInfo *II) {
3157 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
3158}
3159
3160LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3161 SourceLocation IdentL, IdentifierInfo *II,
3162 SourceLocation GnuLabelL) {
3163 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
3164 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003165}
3166
Douglas Gregor72172e92012-01-05 21:55:30 +00003167LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3168 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
3169 return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00003170}
3171
David Blaikie68e081d2011-12-20 02:48:34 +00003172void ValueDecl::anchor() { }
3173
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003174bool ValueDecl::isWeak() const {
3175 for (attr_iterator I = attr_begin(), E = attr_end(); I != E; ++I)
3176 if (isa<WeakAttr>(*I) || isa<WeakRefAttr>(*I))
3177 return true;
3178
3179 return isWeakImported();
3180}
3181
David Blaikie68e081d2011-12-20 02:48:34 +00003182void ImplicitParamDecl::anchor() { }
3183
Sebastian Redl833ef452010-01-26 22:01:41 +00003184ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003185 SourceLocation IdLoc,
3186 IdentifierInfo *Id,
3187 QualType Type) {
3188 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00003189}
3190
Douglas Gregor72172e92012-01-05 21:55:30 +00003191ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
3192 unsigned ID) {
3193 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
3194 return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
3195}
3196
Sebastian Redl833ef452010-01-26 22:01:41 +00003197FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003198 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003199 const DeclarationNameInfo &NameInfo,
3200 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003201 StorageClass SC,
Douglas Gregorff76cb92010-12-09 16:59:22 +00003202 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00003203 bool hasWrittenPrototype,
3204 bool isConstexprSpecified) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003205 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003206 T, TInfo, SC,
Richard Smitha77a0a62011-08-15 21:04:07 +00003207 isInlineSpecified,
3208 isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00003209 New->HasWrittenPrototype = hasWrittenPrototype;
3210 return New;
3211}
3212
Douglas Gregor72172e92012-01-05 21:55:30 +00003213FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3214 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
3215 return new (Mem) FunctionDecl(Function, 0, SourceLocation(),
3216 DeclarationNameInfo(), QualType(), 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003217 SC_None, false, false);
Douglas Gregor72172e92012-01-05 21:55:30 +00003218}
3219
Sebastian Redl833ef452010-01-26 22:01:41 +00003220BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3221 return new (C) BlockDecl(DC, L);
3222}
3223
Douglas Gregor72172e92012-01-05 21:55:30 +00003224BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3225 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
3226 return new (Mem) BlockDecl(0, SourceLocation());
3227}
3228
Sebastian Redl833ef452010-01-26 22:01:41 +00003229EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3230 SourceLocation L,
3231 IdentifierInfo *Id, QualType T,
3232 Expr *E, const llvm::APSInt &V) {
3233 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
3234}
3235
Douglas Gregor72172e92012-01-05 21:55:30 +00003236EnumConstantDecl *
3237EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3238 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
3239 return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
3240 llvm::APSInt());
3241}
3242
David Blaikie68e081d2011-12-20 02:48:34 +00003243void IndirectFieldDecl::anchor() { }
3244
Benjamin Kramer39593702010-11-21 14:11:41 +00003245IndirectFieldDecl *
3246IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3247 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3248 unsigned CHS) {
Francois Pichet783dd6e2010-11-21 06:08:52 +00003249 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
3250}
3251
Douglas Gregor72172e92012-01-05 21:55:30 +00003252IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3253 unsigned ID) {
3254 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
3255 return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
3256 QualType(), 0, 0);
3257}
3258
Douglas Gregorbe996932010-09-01 20:41:53 +00003259SourceRange EnumConstantDecl::getSourceRange() const {
3260 SourceLocation End = getLocation();
3261 if (Init)
3262 End = Init->getLocEnd();
3263 return SourceRange(getLocation(), End);
3264}
3265
David Blaikie68e081d2011-12-20 02:48:34 +00003266void TypeDecl::anchor() { }
3267
Sebastian Redl833ef452010-01-26 22:01:41 +00003268TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003269 SourceLocation StartLoc, SourceLocation IdLoc,
3270 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
3271 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00003272}
3273
David Blaikie68e081d2011-12-20 02:48:34 +00003274void TypedefNameDecl::anchor() { }
3275
Douglas Gregor72172e92012-01-05 21:55:30 +00003276TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3277 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
3278 return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3279}
3280
Richard Smithdda56e42011-04-15 14:24:37 +00003281TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3282 SourceLocation StartLoc,
3283 SourceLocation IdLoc, IdentifierInfo *Id,
3284 TypeSourceInfo *TInfo) {
3285 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
3286}
3287
Douglas Gregor72172e92012-01-05 21:55:30 +00003288TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3289 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
3290 return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3291}
3292
Abramo Bagnaraea947882011-03-08 16:41:52 +00003293SourceRange TypedefDecl::getSourceRange() const {
3294 SourceLocation RangeEnd = getLocation();
3295 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3296 if (typeIsPostfix(TInfo->getType()))
3297 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3298 }
3299 return SourceRange(getLocStart(), RangeEnd);
3300}
3301
Richard Smithdda56e42011-04-15 14:24:37 +00003302SourceRange TypeAliasDecl::getSourceRange() const {
3303 SourceLocation RangeEnd = getLocStart();
3304 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3305 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3306 return SourceRange(getLocStart(), RangeEnd);
3307}
3308
David Blaikie68e081d2011-12-20 02:48:34 +00003309void FileScopeAsmDecl::anchor() { }
3310
Sebastian Redl833ef452010-01-26 22:01:41 +00003311FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00003312 StringLiteral *Str,
3313 SourceLocation AsmLoc,
3314 SourceLocation RParenLoc) {
3315 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00003316}
Douglas Gregorba345522011-12-02 23:23:56 +00003317
Douglas Gregor72172e92012-01-05 21:55:30 +00003318FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
3319 unsigned ID) {
3320 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
3321 return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
3322}
3323
Michael Han84324352013-02-22 17:15:32 +00003324void EmptyDecl::anchor() {}
3325
3326EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3327 return new (C) EmptyDecl(DC, L);
3328}
3329
3330EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3331 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EmptyDecl));
3332 return new (Mem) EmptyDecl(0, SourceLocation());
3333}
3334
Douglas Gregorba345522011-12-02 23:23:56 +00003335//===----------------------------------------------------------------------===//
3336// ImportDecl Implementation
3337//===----------------------------------------------------------------------===//
3338
3339/// \brief Retrieve the number of module identifiers needed to name the given
3340/// module.
3341static unsigned getNumModuleIdentifiers(Module *Mod) {
3342 unsigned Result = 1;
3343 while (Mod->Parent) {
3344 Mod = Mod->Parent;
3345 ++Result;
3346 }
3347 return Result;
3348}
3349
Douglas Gregor22d09742012-01-03 18:04:46 +00003350ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003351 Module *Imported,
3352 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00003353 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003354 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003355{
3356 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3357 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3358 memcpy(StoredLocs, IdentifierLocs.data(),
3359 IdentifierLocs.size() * sizeof(SourceLocation));
3360}
3361
Douglas Gregor22d09742012-01-03 18:04:46 +00003362ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003363 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00003364 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003365 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003366{
3367 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3368}
3369
3370ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003371 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00003372 ArrayRef<SourceLocation> IdentifierLocs) {
3373 void *Mem = C.Allocate(sizeof(ImportDecl) +
3374 IdentifierLocs.size() * sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00003375 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00003376}
3377
3378ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003379 SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003380 Module *Imported,
3381 SourceLocation EndLoc) {
3382 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00003383 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00003384 Import->setImplicit();
3385 return Import;
3386}
3387
Douglas Gregor72172e92012-01-05 21:55:30 +00003388ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3389 unsigned NumLocations) {
3390 void *Mem = AllocateDeserializedDecl(C, ID,
3391 (sizeof(ImportDecl) +
3392 NumLocations * sizeof(SourceLocation)));
Douglas Gregorba345522011-12-02 23:23:56 +00003393 return new (Mem) ImportDecl(EmptyShell());
3394}
3395
3396ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3397 if (!ImportedAndComplete.getInt())
3398 return ArrayRef<SourceLocation>();
3399
3400 const SourceLocation *StoredLocs
3401 = reinterpret_cast<const SourceLocation *>(this + 1);
3402 return ArrayRef<SourceLocation>(StoredLocs,
3403 getNumModuleIdentifiers(getImportedModule()));
3404}
3405
3406SourceRange ImportDecl::getSourceRange() const {
3407 if (!ImportedAndComplete.getInt())
3408 return SourceRange(getLocation(),
3409 *reinterpret_cast<const SourceLocation *>(this + 1));
3410
3411 return SourceRange(getLocation(), getIdentifierLocs().back());
3412}