blob: e4688f09a32500ecfa69488a7e1bf879835354f2 [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
Rafael Espindola2f869a32012-01-14 00:30:36 +0000214static LinkageInfo getLVForType(QualType T) {
215 std::pair<Linkage,Visibility> P = T->getLinkageAndVisibility();
216 return LinkageInfo(P.first, P.second, T->isVisibilityExplicit());
217}
218
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000219/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000220/// template parameter list. For visibility purposes, template
221/// parameters are part of the signature of a template.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000222static LinkageInfo
John McCalldf25c432013-02-16 00:17:33 +0000223getLVForTemplateParameterList(const TemplateParameterList *params) {
224 LinkageInfo LV;
225 for (TemplateParameterList::const_iterator P = params->begin(),
226 PEnd = params->end();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000227 P != PEnd; ++P) {
John McCalldf25c432013-02-16 00:17:33 +0000228
229 // Template type parameters are the most common and never
230 // contribute to visibility, pack or not.
231 if (isa<TemplateTypeParmDecl>(*P))
232 continue;
233
234 // Non-type template parameters can be restricted by the value type, e.g.
235 // template <enum X> class A { ... };
236 // We have to be careful here, though, because we can be dealing with
237 // dependent types.
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000238 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
John McCalldf25c432013-02-16 00:17:33 +0000239 // Handle the non-pack case first.
240 if (!NTTP->isExpandedParameterPack()) {
241 if (!NTTP->getType()->isDependentType()) {
242 LV.merge(getLVForType(NTTP->getType()));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000243 }
244 continue;
245 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000246
John McCalldf25c432013-02-16 00:17:33 +0000247 // Look at all the types in an expanded pack.
248 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
249 QualType type = NTTP->getExpansionType(i);
250 if (!type->isDependentType())
251 LV.merge(getLVForType(type));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000252 }
John McCalldf25c432013-02-16 00:17:33 +0000253 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000254 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000255
John McCalldf25c432013-02-16 00:17:33 +0000256 // Template template parameters can be restricted by their
257 // template parameters, recursively.
258 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
259
260 // Handle the non-pack case first.
261 if (!TTP->isExpandedParameterPack()) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000262 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters()));
John McCalldf25c432013-02-16 00:17:33 +0000263 continue;
264 }
265
266 // Look at all expansions in an expanded pack.
267 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
268 i != n; ++i) {
269 LV.merge(getLVForTemplateParameterList(
270 TTP->getExpansionTemplateParameters(i)));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000271 }
272 }
273
John McCall457a04e2010-10-22 21:05:15 +0000274 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000275}
276
Rafael Espindola19de5612013-01-12 06:42:30 +0000277/// getLVForDecl - Get the linkage and visibility for the given declaration.
John McCalldf25c432013-02-16 00:17:33 +0000278static LinkageInfo getLVForDecl(const NamedDecl *D,
279 LVComputationKind computation);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000280
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000281/// \brief Get the most restrictive linkage for the types and
282/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000283///
284/// Note that we don't take an LVComputationKind because we always
285/// want to honor the visibility of template arguments in the same way.
286static LinkageInfo
287getLVForTemplateArgumentList(ArrayRef<TemplateArgument> args) {
288 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000289
John McCalldf25c432013-02-16 00:17:33 +0000290 for (unsigned i = 0, e = args.size(); i != e; ++i) {
291 const TemplateArgument &arg = args[i];
292 switch (arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000293 case TemplateArgument::Null:
294 case TemplateArgument::Integral:
295 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000296 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000297
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000298 case TemplateArgument::Type:
John McCalldf25c432013-02-16 00:17:33 +0000299 LV.merge(getLVForType(arg.getAsType()));
300 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000301
302 case TemplateArgument::Declaration:
John McCalldf25c432013-02-16 00:17:33 +0000303 if (NamedDecl *ND = dyn_cast<NamedDecl>(arg.getAsDecl())) {
304 assert(!usesTypeVisibility(ND));
305 LV.merge(getLVForDecl(ND, LVForValue));
306 }
307 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +0000308
309 case TemplateArgument::NullPtr:
John McCalldf25c432013-02-16 00:17:33 +0000310 LV.merge(getLVForType(arg.getNullPtrType()));
311 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000312
313 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000314 case TemplateArgument::TemplateExpansion:
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000315 if (TemplateDecl *Template
John McCalldf25c432013-02-16 00:17:33 +0000316 = arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
317 LV.merge(getLVForDecl(Template, LVForValue));
318 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000319
320 case TemplateArgument::Pack:
John McCalldf25c432013-02-16 00:17:33 +0000321 LV.merge(getLVForTemplateArgumentList(arg.getPackAsArray()));
322 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000323 }
John McCalldf25c432013-02-16 00:17:33 +0000324 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000325 }
326
John McCall457a04e2010-10-22 21:05:15 +0000327 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000328}
329
Rafael Espindola2f869a32012-01-14 00:30:36 +0000330static LinkageInfo
John McCalldf25c432013-02-16 00:17:33 +0000331getLVForTemplateArgumentList(const TemplateArgumentList &TArgs) {
332 return getLVForTemplateArgumentList(TArgs.asArray());
John McCall8823c652010-08-13 08:35:10 +0000333}
334
John McCall5f46c482013-02-21 23:42:58 +0000335static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
336 const FunctionTemplateSpecializationInfo *specInfo) {
337 // Include visibility from the template parameters and arguments
338 // only if this is not an explicit instantiation or specialization
339 // with direct explicit visibility. (Implicit instantiations won't
340 // have a direct attribute.)
341 if (!specInfo->isExplicitInstantiationOrSpecialization())
342 return true;
343
344 return !fn->hasAttr<VisibilityAttr>();
345}
346
John McCalldf25c432013-02-16 00:17:33 +0000347/// Merge in template-related linkage and visibility for the given
348/// function template specialization.
349///
350/// We don't need a computation kind here because we can assume
351/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000352///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000353/// \param[out] LV the computation to use for the parent
John McCall5f46c482013-02-21 23:42:58 +0000354static void
355mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
356 const FunctionTemplateSpecializationInfo *specInfo) {
357 bool considerVisibility =
358 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000359
360 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000361 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000362 LinkageInfo tempLV =
363 getLVForTemplateParameterList(temp->getTemplateParameters());
364 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
365
366 // Merge information from the template arguments.
367 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
368 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
369 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000370}
371
John McCall5f46c482013-02-21 23:42:58 +0000372/// Does the given declaration have a direct visibility attribute
373/// that would match the given rules?
374static bool hasDirectVisibilityAttribute(const NamedDecl *D,
375 LVComputationKind computation) {
376 switch (computation) {
377 case LVForType:
378 case LVForExplicitType:
379 if (D->hasAttr<TypeVisibilityAttr>())
380 return true;
381 // fallthrough
382 case LVForValue:
383 case LVForExplicitValue:
384 if (D->hasAttr<VisibilityAttr>())
385 return true;
386 return false;
387 }
388 llvm_unreachable("bad visibility computation kind");
389}
390
John McCalld041a9b2013-02-20 01:54:26 +0000391/// Should we consider visibility associated with the template
392/// arguments and parameters of the given class template specialization?
393static bool shouldConsiderTemplateVisibility(
394 const ClassTemplateSpecializationDecl *spec,
395 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000396 // Include visibility from the template parameters and arguments
397 // only if this is not an explicit instantiation or specialization
398 // with direct explicit visibility (and note that implicit
399 // instantiations won't have a direct attribute).
400 //
401 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000402 // for an explicit specialization when computing the visibility of a
403 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000404 //
405 // This is a bit complex; let's unpack it.
406 //
407 // An explicit class specialization is an independent, top-level
408 // declaration. As such, if it or any of its members has an
409 // explicit visibility attribute, that must directly express the
410 // user's intent, and we should honor it. The same logic applies to
411 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000412
413 // Fast path: if this is not an explicit instantiation or
414 // specialization, we always want to consider template-related
415 // visibility restrictions.
416 if (!spec->isExplicitInstantiationOrSpecialization())
417 return true;
418
419 // This is the 'member thereof' check.
420 if (spec->isExplicitSpecialization() &&
421 hasExplicitVisibilityAlready(computation))
422 return false;
423
John McCall5f46c482013-02-21 23:42:58 +0000424 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000425}
426
427/// Merge in template-related linkage and visibility for the given
428/// class template specialization.
429static void mergeTemplateLV(LinkageInfo &LV,
430 const ClassTemplateSpecializationDecl *spec,
431 LVComputationKind computation) {
432 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000433
434 // Merge information from the template parameters, but ignore
435 // visibility if we're only considering template arguments.
436
John McCalld041a9b2013-02-20 01:54:26 +0000437 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000438 LinkageInfo tempLV =
439 getLVForTemplateParameterList(temp->getTemplateParameters());
440 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000441 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000442
443 // Merge information from the template arguments. We ignore
444 // template-argument visibility if we've got an explicit
445 // instantiation with a visibility attribute.
446 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
447 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
448 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000449}
450
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000451static bool useInlineVisibilityHidden(const NamedDecl *D) {
452 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000453 const LangOptions &Opts = D->getASTContext().getLangOpts();
454 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000455 return false;
456
457 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
458 if (!FD)
459 return false;
460
461 TemplateSpecializationKind TSK = TSK_Undeclared;
462 if (FunctionTemplateSpecializationInfo *spec
463 = FD->getTemplateSpecializationInfo()) {
464 TSK = spec->getTemplateSpecializationKind();
465 } else if (MemberSpecializationInfo *MSI =
466 FD->getMemberSpecializationInfo()) {
467 TSK = MSI->getTemplateSpecializationKind();
468 }
469
470 const FunctionDecl *Def = 0;
471 // InlineVisibilityHidden only applies to definitions, and
472 // isInlined() only gives meaningful answers on definitions
473 // anyway.
474 return TSK != TSK_ExplicitInstantiationDeclaration &&
475 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000476 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000477}
478
Benjamin Kramer3e350262013-02-15 12:30:38 +0000479template <typename T> static bool isInExternCContext(T *D) {
Rafael Espindolaf4187652013-02-14 01:18:37 +0000480 const T *First = D->getFirstDeclaration();
481 return First->getDeclContext()->isExternCContext();
482}
483
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000484static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
John McCalldf25c432013-02-16 00:17:33 +0000485 LVComputationKind computation) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000486 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000487 "Not a name having namespace scope");
488 ASTContext &Context = D->getASTContext();
489
490 // C++ [basic.link]p3:
491 // A name having namespace scope (3.3.6) has internal linkage if it
492 // is the name of
493 // - an object, reference, function or function template that is
494 // explicitly declared static; or,
495 // (This bullet corresponds to C99 6.2.2p3.)
496 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
497 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000498 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000499 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000500
Richard Smithdc0ef452012-10-19 06:37:48 +0000501 // - a non-volatile object or reference that is explicitly declared const
502 // or constexpr and neither explicitly declared extern nor previously
503 // declared to have external linkage; or (there is no equivalent in C99)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000504 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000505 Var->getType().isConstQualified() &&
506 !Var->getType().isVolatileQualified() &&
John McCall8e7d6562010-08-26 03:08:43 +0000507 Var->getStorageClass() != SC_Extern &&
508 Var->getStorageClass() != SC_PrivateExtern) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000509 bool FoundExtern = false;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000510 for (const VarDecl *PrevVar = Var->getPreviousDecl();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000511 PrevVar && !FoundExtern;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000512 PrevVar = PrevVar->getPreviousDecl())
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000513 if (isExternalLinkage(PrevVar->getLinkage()))
Douglas Gregorf73b2822009-11-25 22:24:25 +0000514 FoundExtern = true;
515
516 if (!FoundExtern)
John McCallc273f242010-10-30 11:50:40 +0000517 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000518 }
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000519 if (Var->getStorageClass() == SC_None) {
Douglas Gregorec9fd132012-01-14 16:38:05 +0000520 const VarDecl *PrevVar = Var->getPreviousDecl();
521 for (; PrevVar; PrevVar = PrevVar->getPreviousDecl())
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000522 if (PrevVar->getStorageClass() == SC_PrivateExtern)
523 break;
Eli Friedmana7137bc2012-10-26 23:05:34 +0000524 if (PrevVar)
525 return PrevVar->getLinkageAndVisibility();
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000526 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000527 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000528 // C++ [temp]p4:
529 // A non-member function template can have internal linkage; any
530 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000531 const FunctionDecl *Function = 0;
532 if (const FunctionTemplateDecl *FunTmpl
533 = dyn_cast<FunctionTemplateDecl>(D))
534 Function = FunTmpl->getTemplatedDecl();
535 else
536 Function = cast<FunctionDecl>(D);
537
538 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000539 if (Function->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000540 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000541 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
542 // - a data member of an anonymous union.
543 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
John McCallc273f242010-10-30 11:50:40 +0000544 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000545 }
546
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000547 if (D->isInAnonymousNamespace()) {
548 const VarDecl *Var = dyn_cast<VarDecl>(D);
549 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
Rafael Espindolaf4187652013-02-14 01:18:37 +0000550 if ((!Var || !isInExternCContext(Var)) &&
551 (!Func || !isInExternCContext(Func)))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000552 return LinkageInfo::uniqueExternal();
553 }
John McCallb7139c42010-10-28 04:18:25 +0000554
John McCall457a04e2010-10-22 21:05:15 +0000555 // Set up the defaults.
556
557 // C99 6.2.2p5:
558 // If the declaration of an identifier for an object has file
559 // scope and no storage-class specifier, its linkage is
560 // external.
John McCallc273f242010-10-30 11:50:40 +0000561 LinkageInfo LV;
562
John McCalld041a9b2013-02-20 01:54:26 +0000563 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000564 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000565 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000566 } else {
567 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000568 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000569 for (const DeclContext *DC = D->getDeclContext();
570 !isa<TranslationUnitDecl>(DC);
571 DC = DC->getParent()) {
572 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
573 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000574 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000575 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000576 break;
577 }
578 }
579 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000580
John McCalldf25c432013-02-16 00:17:33 +0000581 // Add in global settings if the above didn't give us direct visibility.
582 if (!LV.visibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000583 // Use global type/value visibility as appropriate.
584 Visibility globalVisibility;
585 if (computation == LVForValue) {
586 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
587 } else {
588 assert(computation == LVForType);
589 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
590 }
591 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000592
593 // If we're paying attention to global visibility, apply
594 // -finline-visibility-hidden if this is an inline method.
595 if (useInlineVisibilityHidden(D))
596 LV.mergeVisibility(HiddenVisibility, true);
597 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000598 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000599
Douglas Gregorf73b2822009-11-25 22:24:25 +0000600 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000601
Douglas Gregorf73b2822009-11-25 22:24:25 +0000602 // A name having namespace scope has external linkage if it is the
603 // name of
604 //
605 // - an object or reference, unless it has internal linkage; or
606 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000607 // GCC applies the following optimization to variables and static
608 // data members, but not to functions:
609 //
John McCall457a04e2010-10-22 21:05:15 +0000610 // Modify the variable's LV by the LV of its type unless this is
611 // C or extern "C". This follows from [basic.link]p9:
612 // A type without linkage shall not be used as the type of a
613 // variable or function with external linkage unless
614 // - the entity has C language linkage, or
615 // - the entity is declared within an unnamed namespace, or
616 // - the entity is not used or is defined in the same
617 // translation unit.
618 // and [basic.link]p10:
619 // ...the types specified by all declarations referring to a
620 // given variable or function shall be identical...
621 // C does not have an equivalent rule.
622 //
John McCall5fe84122010-10-26 04:59:26 +0000623 // Ignore this if we've got an explicit attribute; the user
624 // probably knows what they're doing.
625 //
John McCall457a04e2010-10-22 21:05:15 +0000626 // Note that we don't want to make the variable non-external
627 // because of this, but unique-external linkage suits us.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000628 if (Context.getLangOpts().CPlusPlus &&
Eli Friedman839192f2012-01-15 01:23:58 +0000629 !Var->getDeclContext()->isExternCContext()) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000630 LinkageInfo TypeLV = getLVForType(Var->getType());
631 if (TypeLV.linkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000632 return LinkageInfo::uniqueExternal();
John McCalldf25c432013-02-16 00:17:33 +0000633 if (!LV.visibilityExplicit())
634 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000635 }
636
John McCall23032652010-11-02 18:38:13 +0000637 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000638 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000639
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000640 // Note that Sema::MergeVarDecl already takes care of implementing
641 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
642 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000643
Douglas Gregorf73b2822009-11-25 22:24:25 +0000644 // - a function, unless it has internal linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000645 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000646 // In theory, we can modify the function's LV by the LV of its
647 // type unless it has C linkage (see comment above about variables
648 // for justification). In practice, GCC doesn't do this, so it's
649 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000650
John McCall23032652010-11-02 18:38:13 +0000651 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000652 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000653
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000654 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
655 // merging storage classes and visibility attributes, so we don't have to
656 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000657
John McCallf768aa72011-02-10 06:50:24 +0000658 // In C++, then if the type of the function uses a type with
659 // unique-external linkage, it's not legally usable from outside
660 // this translation unit. However, we should use the C linkage
661 // rules instead for extern "C" declarations.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000662 if (Context.getLangOpts().CPlusPlus &&
Eli Friedman839192f2012-01-15 01:23:58 +0000663 !Function->getDeclContext()->isExternCContext() &&
John McCallf768aa72011-02-10 06:50:24 +0000664 Function->getType()->getLinkage() == UniqueExternalLinkage)
665 return LinkageInfo::uniqueExternal();
666
John McCall5f46c482013-02-21 23:42:58 +0000667 // Consider LV from the template and the template arguments.
668 // We're at file scope, so we do not need to worry about nested
669 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000670 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000671 = Function->getTemplateSpecializationInfo()) {
John McCalldf25c432013-02-16 00:17:33 +0000672 mergeTemplateLV(LV, Function, specInfo);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000673 }
674
Douglas Gregorf73b2822009-11-25 22:24:25 +0000675 // - a named class (Clause 9), or an unnamed class defined in a
676 // typedef declaration in which the class has the typedef name
677 // for linkage purposes (7.1.3); or
678 // - a named enumeration (7.2), or an unnamed enumeration
679 // defined in a typedef declaration in which the enumeration
680 // has the typedef name for linkage purposes (7.1.3); or
John McCall457a04e2010-10-22 21:05:15 +0000681 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
682 // Unnamed tags have no linkage.
Richard Smithdda56e42011-04-15 14:24:37 +0000683 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
John McCallc273f242010-10-30 11:50:40 +0000684 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000685
John McCall457a04e2010-10-22 21:05:15 +0000686 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000687 // linkage of the template and template arguments. We're at file
688 // scope, so we do not need to worry about nested specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000689 if (const ClassTemplateSpecializationDecl *spec
John McCall457a04e2010-10-22 21:05:15 +0000690 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000691 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000692 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000693
694 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000695 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000696 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000697 computation);
John McCallc273f242010-10-30 11:50:40 +0000698 if (!isExternalLinkage(EnumLV.linkage()))
699 return LinkageInfo::none();
700 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000701
702 // - a template, unless it is a function template that has
703 // internal linkage (Clause 14);
John McCall8bc6d5b2011-03-04 10:39:25 +0000704 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000705 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000706 LinkageInfo tempLV =
707 getLVForTemplateParameterList(temp->getTemplateParameters());
708 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
709
Douglas Gregorf73b2822009-11-25 22:24:25 +0000710 // - a namespace (7.3), unless it is declared within an unnamed
711 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000712 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
713 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000714
John McCall457a04e2010-10-22 21:05:15 +0000715 // By extension, we assign external linkage to Objective-C
716 // interfaces.
717 } else if (isa<ObjCInterfaceDecl>(D)) {
718 // fallout
719
720 // Everything not covered here has no linkage.
721 } else {
John McCallc273f242010-10-30 11:50:40 +0000722 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000723 }
724
725 // If we ended up with non-external linkage, visibility should
726 // always be default.
John McCallc273f242010-10-30 11:50:40 +0000727 if (LV.linkage() != ExternalLinkage)
728 return LinkageInfo(LV.linkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000729
John McCall457a04e2010-10-22 21:05:15 +0000730 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000731}
732
John McCalldf25c432013-02-16 00:17:33 +0000733static LinkageInfo getLVForClassMember(const NamedDecl *D,
734 LVComputationKind computation) {
John McCall457a04e2010-10-22 21:05:15 +0000735 // Only certain class members have linkage. Note that fields don't
736 // really have linkage, but it's convenient to say they do for the
737 // purposes of calculating linkage of pointer-to-data-member
738 // template arguments.
John McCall8823c652010-08-13 08:35:10 +0000739 if (!(isa<CXXMethodDecl>(D) ||
740 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000741 isa<FieldDecl>(D) ||
David Blaikie095deba2012-11-14 01:52:05 +0000742 isa<TagDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000743 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000744
John McCall07072662010-11-02 01:45:15 +0000745 LinkageInfo LV;
746
John McCall07072662010-11-02 01:45:15 +0000747 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000748 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000749 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000750 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000751 // If we're paying attention to global visibility, apply
752 // -finline-visibility-hidden if this is an inline method.
753 //
754 // Note that we do this before merging information about
755 // the class visibility.
756 if (!LV.visibilityExplicit() && useInlineVisibilityHidden(D))
757 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000758 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000759
760 // If this class member has an explicit visibility attribute, the only
761 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000762 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000763 LVComputationKind classComputation = computation;
764 if (LV.visibilityExplicit())
765 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000766
John McCall5f46c482013-02-21 23:42:58 +0000767 LinkageInfo classLV =
768 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
769 if (!isExternalLinkage(classLV.linkage()))
John McCallc273f242010-10-30 11:50:40 +0000770 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000771
772 // If the class already has unique-external linkage, we can't improve.
John McCall5f46c482013-02-21 23:42:58 +0000773 if (classLV.linkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000774 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000775
John McCall5f46c482013-02-21 23:42:58 +0000776 // Otherwise, don't merge in classLV yet, because in certain cases
777 // we need to completely ignore the visibility from it.
778
779 // Specifically, if this decl exists and has an explicit attribute.
780 const NamedDecl *explicitSpecSuppressor = 0;
781
John McCall8823c652010-08-13 08:35:10 +0000782 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000783 // If the type of the function uses a type with unique-external
784 // linkage, it's not legally usable from outside this translation unit.
785 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
786 return LinkageInfo::uniqueExternal();
787
John McCall457a04e2010-10-22 21:05:15 +0000788 // If this is a method template specialization, use the linkage for
789 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000790 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000791 = MD->getTemplateSpecializationInfo()) {
John McCalldf25c432013-02-16 00:17:33 +0000792 mergeTemplateLV(LV, MD, spec);
John McCall5f46c482013-02-21 23:42:58 +0000793 if (spec->isExplicitSpecialization()) {
794 explicitSpecSuppressor = MD;
795 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
796 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
797 }
798 } else if (isExplicitMemberSpecialization(MD)) {
799 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000800 }
John McCall457a04e2010-10-22 21:05:15 +0000801
John McCall37bb6c92010-10-29 22:22:43 +0000802 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCallb8c604a2011-06-27 23:06:04 +0000803 if (const ClassTemplateSpecializationDecl *spec
John McCall37bb6c92010-10-29 22:22:43 +0000804 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000805 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000806 if (spec->isExplicitSpecialization()) {
807 explicitSpecSuppressor = spec;
808 } else {
809 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
810 if (isExplicitMemberSpecialization(temp)) {
811 explicitSpecSuppressor = temp->getTemplatedDecl();
812 }
813 }
814 } else if (isExplicitMemberSpecialization(RD)) {
815 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000816 }
817
John McCall37bb6c92010-10-29 22:22:43 +0000818 // Static data members.
819 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCall36cd5cc2010-10-30 09:18:49 +0000820 // Modify the variable's linkage by its type, but ignore the
821 // type's visibility unless it's a definition.
John McCalldf25c432013-02-16 00:17:33 +0000822 LinkageInfo typeLV = getLVForType(VD->getType());
John McCall5f46c482013-02-21 23:42:58 +0000823 LV.mergeMaybeWithVisibility(typeLV,
824 !LV.visibilityExplicit() && !classLV.visibilityExplicit());
825
826 if (isExplicitMemberSpecialization(VD)) {
827 explicitSpecSuppressor = VD;
828 }
John McCalldf25c432013-02-16 00:17:33 +0000829
830 // Template members.
831 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
832 bool considerVisibility =
John McCalld041a9b2013-02-20 01:54:26 +0000833 (!LV.visibilityExplicit() &&
John McCall5f46c482013-02-21 23:42:58 +0000834 !classLV.visibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000835 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000836 LinkageInfo tempLV =
837 getLVForTemplateParameterList(temp->getTemplateParameters());
838 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +0000839
840 if (const RedeclarableTemplateDecl *redeclTemp =
841 dyn_cast<RedeclarableTemplateDecl>(temp)) {
842 if (isExplicitMemberSpecialization(redeclTemp)) {
843 explicitSpecSuppressor = temp->getTemplatedDecl();
844 }
845 }
John McCall37bb6c92010-10-29 22:22:43 +0000846 }
847
John McCall5f46c482013-02-21 23:42:58 +0000848 // We should never be looking for an attribute directly on a template.
849 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
850
851 // If this member is an explicit member specialization, and it has
852 // an explicit attribute, ignore visibility from the parent.
853 bool considerClassVisibility = true;
854 if (explicitSpecSuppressor &&
855 LV.visibilityExplicit() && // optimization: hasDVA() is true only if this
856 classLV.visibility() != DefaultVisibility &&
857 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
858 considerClassVisibility = false;
859 }
860
861 // Finally, merge in information from the class.
862 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +0000863 return LV;
John McCall8823c652010-08-13 08:35:10 +0000864}
865
John McCalld396b972011-02-08 19:01:05 +0000866static void clearLinkageForClass(const CXXRecordDecl *record) {
867 for (CXXRecordDecl::decl_iterator
868 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
869 Decl *child = *i;
870 if (isa<NamedDecl>(child))
Rafael Espindola19de5612013-01-12 06:42:30 +0000871 cast<NamedDecl>(child)->ClearLinkageCache();
John McCalld396b972011-02-08 19:01:05 +0000872 }
873}
874
David Blaikie68e081d2011-12-20 02:48:34 +0000875void NamedDecl::anchor() { }
876
Rafael Espindola19de5612013-01-12 06:42:30 +0000877void NamedDecl::ClearLinkageCache() {
John McCalld396b972011-02-08 19:01:05 +0000878 // Note that we can't skip clearing the linkage of children just
879 // because the parent doesn't have cached linkage: we don't cache
880 // when computing linkage for parent contexts.
881
Rafael Espindola19de5612013-01-12 06:42:30 +0000882 HasCachedLinkage = 0;
John McCalld396b972011-02-08 19:01:05 +0000883
884 // If we're changing the linkage of a class, we need to reset the
885 // linkage of child declarations, too.
886 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
887 clearLinkageForClass(record);
888
Dmitri Gribenkofb04e1b2013-02-03 16:10:26 +0000889 if (ClassTemplateDecl *temp = dyn_cast<ClassTemplateDecl>(this)) {
John McCalld396b972011-02-08 19:01:05 +0000890 // Clear linkage for the template pattern.
891 CXXRecordDecl *record = temp->getTemplatedDecl();
Rafael Espindola19de5612013-01-12 06:42:30 +0000892 record->HasCachedLinkage = 0;
John McCalld396b972011-02-08 19:01:05 +0000893 clearLinkageForClass(record);
894
John McCall83779672011-02-19 02:53:41 +0000895 // We need to clear linkage for specializations, too.
896 for (ClassTemplateDecl::spec_iterator
897 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
Rafael Espindola19de5612013-01-12 06:42:30 +0000898 i->ClearLinkageCache();
John McCalld396b972011-02-08 19:01:05 +0000899 }
John McCall83779672011-02-19 02:53:41 +0000900
901 // Clear cached linkage for function template decls, too.
Dmitri Gribenkofb04e1b2013-02-03 16:10:26 +0000902 if (FunctionTemplateDecl *temp = dyn_cast<FunctionTemplateDecl>(this)) {
Rafael Espindola19de5612013-01-12 06:42:30 +0000903 temp->getTemplatedDecl()->ClearLinkageCache();
John McCall83779672011-02-19 02:53:41 +0000904 for (FunctionTemplateDecl::spec_iterator
905 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
Rafael Espindola19de5612013-01-12 06:42:30 +0000906 i->ClearLinkageCache();
John McCall8f9a4292011-03-22 06:58:49 +0000907 }
John McCall83779672011-02-19 02:53:41 +0000908
John McCalld396b972011-02-08 19:01:05 +0000909}
910
Douglas Gregorbf62d642010-12-06 18:36:25 +0000911Linkage NamedDecl::getLinkage() const {
Richard Smith88581592013-02-12 05:48:23 +0000912 if (HasCachedLinkage)
Rafael Espindola19de5612013-01-12 06:42:30 +0000913 return Linkage(CachedLinkage);
Rafael Espindola19de5612013-01-12 06:42:30 +0000914
John McCalld041a9b2013-02-20 01:54:26 +0000915 // We don't care about visibility here, so ask for the cheapest
916 // possible visibility analysis.
917 CachedLinkage = getLVForDecl(this, LVForExplicitValue).linkage();
Rafael Espindola19de5612013-01-12 06:42:30 +0000918 HasCachedLinkage = 1;
919
920#ifndef NDEBUG
921 verifyLinkage();
922#endif
923
924 return Linkage(CachedLinkage);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000925}
926
John McCallc273f242010-10-30 11:50:40 +0000927LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCalldf25c432013-02-16 00:17:33 +0000928 LVComputationKind computation =
929 (usesTypeVisibility(this) ? LVForType : LVForValue);
930 LinkageInfo LI = getLVForDecl(this, computation);
Rafael Espindola19de5612013-01-12 06:42:30 +0000931 if (HasCachedLinkage) {
932 assert(Linkage(CachedLinkage) == LI.linkage());
933 return LI;
Rafael Espindola54606d52012-12-25 07:31:49 +0000934 }
Rafael Espindola19de5612013-01-12 06:42:30 +0000935 HasCachedLinkage = 1;
936 CachedLinkage = LI.linkage();
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000937
938#ifndef NDEBUG
Rafael Espindola19de5612013-01-12 06:42:30 +0000939 verifyLinkage();
940#endif
941
942 return LI;
943}
944
945void NamedDecl::verifyLinkage() const {
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000946 // In C (because of gnu inline) and in c++ with microsoft extensions an
947 // static can follow an extern, so we can have two decls with different
948 // linkages.
949 const LangOptions &Opts = getASTContext().getLangOpts();
950 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
Rafael Espindola19de5612013-01-12 06:42:30 +0000951 return;
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000952
953 // We have just computed the linkage for this decl. By induction we know
954 // that all other computed linkages match, check that the one we just computed
955 // also does.
956 NamedDecl *D = NULL;
957 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
958 NamedDecl *T = cast<NamedDecl>(*I);
959 if (T == this)
960 continue;
Rafael Espindola19de5612013-01-12 06:42:30 +0000961 if (T->HasCachedLinkage != 0) {
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000962 D = T;
963 break;
964 }
965 }
966 assert(!D || D->CachedLinkage == CachedLinkage);
John McCall033caa52010-10-29 00:29:13 +0000967}
Ted Kremenek926d8602010-04-20 23:15:35 +0000968
David Blaikie05785d12013-02-20 22:23:23 +0000969Optional<Visibility>
John McCalld041a9b2013-02-20 01:54:26 +0000970NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
Rafael Espindola3a52c442013-02-26 19:33:14 +0000971 // Check the declaration itself first.
972 if (Optional<Visibility> V = getVisibilityOf(this, kind))
973 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000974
Rafael Espindola3a52c442013-02-26 19:33:14 +0000975 // If this is a member class of a specialization of a class template
976 // and the corresponding decl has explicit visibility, use that.
977 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(this)) {
978 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
979 if (InstantiatedFrom)
980 return getVisibilityOf(InstantiatedFrom, kind);
981 }
982
983 // If there wasn't explicit visibility there, and this is a
984 // specialization of a class template, check for visibility
985 // on the pattern.
986 if (const ClassTemplateSpecializationDecl *spec
987 = dyn_cast<ClassTemplateSpecializationDecl>(this))
988 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
989 kind);
990
991 // Use the most recent declaration.
992 const NamedDecl *MostRecent = cast<NamedDecl>(this->getMostRecentDecl());
993 if (MostRecent != this)
994 return MostRecent->getExplicitVisibility(kind);
995
996 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
Rafael Espindola96e68242012-05-16 02:10:38 +0000997 if (Var->isStaticDataMember()) {
998 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
999 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001000 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +00001001 }
1002
David Blaikie7a30dc52013-02-21 01:47:18 +00001003 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +00001004 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001005 // Also handle function template specializations.
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001006 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001007 // If the function is a specialization of a template with an
1008 // explicit visibility attribute, use that.
1009 if (FunctionTemplateSpecializationInfo *templateInfo
1010 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +00001011 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1012 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001013
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001014 // If the function is a member of a specialization of a class template
1015 // and the corresponding decl has explicit visibility, use that.
1016 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1017 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001018 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001019
David Blaikie7a30dc52013-02-21 01:47:18 +00001020 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001021 }
1022
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001023 // The visibility of a template is stored in the templated decl.
1024 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(this))
John McCalld041a9b2013-02-20 01:54:26 +00001025 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001026
David Blaikie7a30dc52013-02-21 01:47:18 +00001027 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001028}
1029
John McCalldf25c432013-02-16 00:17:33 +00001030static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1031 LVComputationKind computation) {
1032 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1033 if (Function->isInAnonymousNamespace() &&
1034 !Function->getDeclContext()->isExternCContext())
1035 return LinkageInfo::uniqueExternal();
1036
1037 // This is a "void f();" which got merged with a file static.
1038 if (Function->getStorageClass() == SC_Static)
1039 return LinkageInfo::internal();
1040
1041 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001042 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001043 if (Optional<Visibility> Vis =
1044 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001045 LV.mergeVisibility(*Vis, true);
1046 }
1047
1048 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1049 // merging storage classes and visibility attributes, so we don't have to
1050 // look at previous decls in here.
1051
1052 return LV;
1053 }
1054
1055 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1056 if (Var->getStorageClassAsWritten() == SC_Extern ||
1057 Var->getStorageClassAsWritten() == SC_PrivateExtern) {
1058 if (Var->isInAnonymousNamespace() &&
1059 !Var->getDeclContext()->isExternCContext())
1060 return LinkageInfo::uniqueExternal();
1061
1062 // This is an "extern int foo;" which got merged with a file static.
1063 if (Var->getStorageClass() == SC_Static)
1064 return LinkageInfo::internal();
1065
1066 LinkageInfo LV;
1067 if (Var->getStorageClass() == SC_PrivateExtern)
1068 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001069 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001070 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001071 LV.mergeVisibility(*Vis, true);
1072 }
1073
1074 // Note that Sema::MergeVarDecl already takes care of implementing
1075 // C99 6.2.2p4 and propagating the visibility attribute, so we don't
1076 // have to do it here.
1077 return LV;
1078 }
1079 }
1080
1081 return LinkageInfo::none();
1082}
1083
1084static LinkageInfo getLVForDecl(const NamedDecl *D,
1085 LVComputationKind computation) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001086 // Objective-C: treat all Objective-C declarations as having external
1087 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001088 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001089 default:
1090 break;
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001091 case Decl::ParmVar:
1092 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001093 case Decl::TemplateTemplateParm: // count these as external
1094 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001095 case Decl::ObjCAtDefsField:
1096 case Decl::ObjCCategory:
1097 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001098 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001099 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001100 case Decl::ObjCMethod:
1101 case Decl::ObjCProperty:
1102 case Decl::ObjCPropertyImpl:
1103 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +00001104 return LinkageInfo::external();
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001105
1106 case Decl::CXXRecord: {
1107 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1108 if (Record->isLambda()) {
1109 if (!Record->getLambdaManglingNumber()) {
1110 // This lambda has no mangling number, so it's internal.
1111 return LinkageInfo::internal();
1112 }
1113
1114 // This lambda has its linkage/visibility determined by its owner.
1115 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
1116 if (Decl *ContextDecl = Record->getLambdaContextDecl()) {
1117 if (isa<ParmVarDecl>(ContextDecl))
1118 DC = ContextDecl->getDeclContext()->getRedeclContext();
1119 else
John McCalldf25c432013-02-16 00:17:33 +00001120 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001121 }
1122
1123 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
John McCalldf25c432013-02-16 00:17:33 +00001124 return getLVForDecl(ND, computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001125
1126 return LinkageInfo::external();
1127 }
1128
1129 break;
1130 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001131 }
1132
Douglas Gregorf73b2822009-11-25 22:24:25 +00001133 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001134 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCalldf25c432013-02-16 00:17:33 +00001135 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001136
1137 // C++ [basic.link]p5:
1138 // In addition, a member function, static data member, a named
1139 // class or enumeration of class scope, or an unnamed class or
1140 // enumeration defined in a class-scope typedef declaration such
1141 // that the class or enumeration has the typedef name for linkage
1142 // purposes (7.1.3), has external linkage if the name of the class
1143 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001144 if (D->getDeclContext()->isRecord())
John McCalldf25c432013-02-16 00:17:33 +00001145 return getLVForClassMember(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001146
1147 // C++ [basic.link]p6:
1148 // The name of a function declared in block scope and the name of
1149 // an object declared by a block scope extern declaration have
1150 // linkage. If there is a visible declaration of an entity with
1151 // linkage having the same name and type, ignoring entities
1152 // declared outside the innermost enclosing namespace scope, the
1153 // block scope declaration declares that same entity and receives
1154 // the linkage of the previous declaration. If there is more than
1155 // one such matching entity, the program is ill-formed. Otherwise,
1156 // if no matching entity is found, the block scope entity receives
1157 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001158 if (D->getDeclContext()->isFunctionOrMethod())
1159 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001160
1161 // C++ [basic.link]p6:
1162 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001163 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001164}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001165
Douglas Gregor2ada0482009-02-04 17:27:36 +00001166std::string NamedDecl::getQualifiedNameAsString() const {
Douglas Gregor78254c82012-03-27 23:34:16 +00001167 return getQualifiedNameAsString(getASTContext().getPrintingPolicy());
Anders Carlsson2fb08242009-09-08 18:24:21 +00001168}
1169
1170std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001171 std::string QualName;
1172 llvm::raw_string_ostream OS(QualName);
1173 printQualifiedName(OS, P);
1174 return OS.str();
1175}
1176
1177void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1178 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1179}
1180
1181void NamedDecl::printQualifiedName(raw_ostream &OS,
1182 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001183 const DeclContext *Ctx = getDeclContext();
1184
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001185 if (Ctx->isFunctionOrMethod()) {
1186 printName(OS);
1187 return;
1188 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001189
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001190 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001191 ContextsTy Contexts;
1192
1193 // Collect contexts.
1194 while (Ctx && isa<NamedDecl>(Ctx)) {
1195 Contexts.push_back(Ctx);
1196 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001197 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001198
1199 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1200 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00001201 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001202 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001203 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001204 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00001205 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1206 TemplateArgs.data(),
1207 TemplateArgs.size(),
1208 P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001209 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Sam Weinig07d211e2009-12-24 23:15:03 +00001210 if (ND->isAnonymousNamespace())
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001211 OS << "<anonymous namespace>";
Sam Weinig07d211e2009-12-24 23:15:03 +00001212 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001213 OS << *ND;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001214 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1215 if (!RD->getIdentifier())
1216 OS << "<anonymous " << RD->getKindName() << '>';
1217 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001218 OS << *RD;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001219 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Sam Weinigb999f682009-12-28 03:19:38 +00001220 const FunctionProtoType *FT = 0;
1221 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001222 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001223
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001224 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001225 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001226 unsigned NumParams = FD->getNumParams();
1227 for (unsigned i = 0; i < NumParams; ++i) {
1228 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001229 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001230 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001231 }
1232
1233 if (FT->isVariadic()) {
1234 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001235 OS << ", ";
1236 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001237 }
1238 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001239 OS << ')';
1240 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001241 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001242 }
1243 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001244 }
1245
John McCalla2a3f7d2010-03-16 21:48:18 +00001246 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001247 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001248 else
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001249 OS << "<anonymous>";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001250}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001251
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001252void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1253 const PrintingPolicy &Policy,
1254 bool Qualified) const {
1255 if (Qualified)
1256 printQualifiedName(OS, Policy);
1257 else
1258 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001259}
1260
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001261bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001262 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1263
Douglas Gregor889ceb72009-02-03 19:21:40 +00001264 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1265 // We want to keep it, unless it nominates same namespace.
1266 if (getKind() == Decl::UsingDirective) {
Douglas Gregor12441b32011-02-25 16:33:46 +00001267 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1268 ->getOriginalNamespace() ==
1269 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1270 ->getOriginalNamespace();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001271 }
Mike Stump11289f42009-09-09 15:08:12 +00001272
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001273 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1274 // For function declarations, we keep track of redeclarations.
Douglas Gregorec9fd132012-01-14 16:38:05 +00001275 return FD->getPreviousDecl() == OldD;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001276
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001277 // For function templates, the underlying function declarations are linked.
1278 if (const FunctionTemplateDecl *FunctionTemplate
1279 = dyn_cast<FunctionTemplateDecl>(this))
1280 if (const FunctionTemplateDecl *OldFunctionTemplate
1281 = dyn_cast<FunctionTemplateDecl>(OldD))
1282 return FunctionTemplate->getTemplatedDecl()
1283 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001284
Steve Naroffc4173fa2009-02-22 19:35:57 +00001285 // For method declarations, we keep track of redeclarations.
1286 if (isa<ObjCMethodDecl>(this))
1287 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001288
John McCall9f3059a2009-10-09 21:13:30 +00001289 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1290 return true;
1291
John McCall3f746822009-11-17 05:59:44 +00001292 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1293 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1294 cast<UsingShadowDecl>(OldD)->getTargetDecl();
1295
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001296 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1297 ASTContext &Context = getASTContext();
1298 return Context.getCanonicalNestedNameSpecifier(
1299 cast<UsingDecl>(this)->getQualifier()) ==
1300 Context.getCanonicalNestedNameSpecifier(
1301 cast<UsingDecl>(OldD)->getQualifier());
1302 }
Argyrios Kyrtzidis4b520072010-11-04 08:48:52 +00001303
Douglas Gregorb59643b2012-01-03 23:26:26 +00001304 // A typedef of an Objective-C class type can replace an Objective-C class
1305 // declaration or definition, and vice versa.
1306 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1307 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1308 return true;
1309
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001310 // For non-function declarations, if the declarations are of the
1311 // same kind then this must be a redeclaration, or semantic analysis
1312 // would not have given us the new declaration.
1313 return this->getKind() == OldD->getKind();
1314}
1315
Douglas Gregoreddf4332009-02-24 20:03:32 +00001316bool NamedDecl::hasLinkage() const {
Douglas Gregorf73b2822009-11-25 22:24:25 +00001317 return getLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001318}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001319
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001320NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001321 NamedDecl *ND = this;
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001322 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1323 ND = UD->getTargetDecl();
1324
1325 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1326 return AD->getClassInterface();
1327
1328 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001329}
1330
John McCalla8ae2222010-04-06 21:38:20 +00001331bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001332 if (!isCXXClassMember())
1333 return false;
1334
John McCalla8ae2222010-04-06 21:38:20 +00001335 const NamedDecl *D = this;
1336 if (isa<UsingShadowDecl>(D))
1337 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1338
Francois Pichet783dd6e2010-11-21 06:08:52 +00001339 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001340 return true;
1341 if (isa<CXXMethodDecl>(D))
1342 return cast<CXXMethodDecl>(D)->isInstance();
1343 if (isa<FunctionTemplateDecl>(D))
1344 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
1345 ->getTemplatedDecl())->isInstance();
1346 return false;
1347}
1348
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001349//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001350// DeclaratorDecl Implementation
1351//===----------------------------------------------------------------------===//
1352
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001353template <typename DeclT>
1354static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1355 if (decl->getNumTemplateParameterLists() > 0)
1356 return decl->getTemplateParameterList(0)->getTemplateLoc();
1357 else
1358 return decl->getInnerLocStart();
1359}
1360
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001361SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001362 TypeSourceInfo *TSI = getTypeSourceInfo();
1363 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001364 return SourceLocation();
1365}
1366
Douglas Gregor14454802011-02-25 02:25:35 +00001367void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1368 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001369 // Make sure the extended decl info is allocated.
1370 if (!hasExtInfo()) {
1371 // Save (non-extended) type source info pointer.
1372 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1373 // Allocate external info struct.
1374 DeclInfo = new (getASTContext()) ExtInfo;
1375 // Restore savedTInfo into (extended) decl info.
1376 getExtInfo()->TInfo = savedTInfo;
1377 }
1378 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001379 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001380 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001381 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001382 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001383 if (getExtInfo()->NumTemplParamLists == 0) {
1384 // Save type source info pointer.
1385 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1386 // Deallocate the extended decl info.
1387 getASTContext().Deallocate(getExtInfo());
1388 // Restore savedTInfo into (non-extended) decl info.
1389 DeclInfo = savedTInfo;
1390 }
1391 else
1392 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001393 }
1394 }
1395}
1396
Abramo Bagnara60804e12011-03-18 15:16:37 +00001397void
1398DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1399 unsigned NumTPLists,
1400 TemplateParameterList **TPLists) {
1401 assert(NumTPLists > 0);
1402 // Make sure the extended decl info is allocated.
1403 if (!hasExtInfo()) {
1404 // Save (non-extended) type source info pointer.
1405 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1406 // Allocate external info struct.
1407 DeclInfo = new (getASTContext()) ExtInfo;
1408 // Restore savedTInfo into (extended) decl info.
1409 getExtInfo()->TInfo = savedTInfo;
1410 }
1411 // Set the template parameter lists info.
1412 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1413}
1414
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001415SourceLocation DeclaratorDecl::getOuterLocStart() const {
1416 return getTemplateOrInnerLocStart(this);
1417}
1418
Abramo Bagnaraea947882011-03-08 16:41:52 +00001419namespace {
1420
1421// Helper function: returns true if QT is or contains a type
1422// having a postfix component.
1423bool typeIsPostfix(clang::QualType QT) {
1424 while (true) {
1425 const Type* T = QT.getTypePtr();
1426 switch (T->getTypeClass()) {
1427 default:
1428 return false;
1429 case Type::Pointer:
1430 QT = cast<PointerType>(T)->getPointeeType();
1431 break;
1432 case Type::BlockPointer:
1433 QT = cast<BlockPointerType>(T)->getPointeeType();
1434 break;
1435 case Type::MemberPointer:
1436 QT = cast<MemberPointerType>(T)->getPointeeType();
1437 break;
1438 case Type::LValueReference:
1439 case Type::RValueReference:
1440 QT = cast<ReferenceType>(T)->getPointeeType();
1441 break;
1442 case Type::PackExpansion:
1443 QT = cast<PackExpansionType>(T)->getPattern();
1444 break;
1445 case Type::Paren:
1446 case Type::ConstantArray:
1447 case Type::DependentSizedArray:
1448 case Type::IncompleteArray:
1449 case Type::VariableArray:
1450 case Type::FunctionProto:
1451 case Type::FunctionNoProto:
1452 return true;
1453 }
1454 }
1455}
1456
1457} // namespace
1458
1459SourceRange DeclaratorDecl::getSourceRange() const {
1460 SourceLocation RangeEnd = getLocation();
1461 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1462 if (typeIsPostfix(TInfo->getType()))
1463 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1464 }
1465 return SourceRange(getOuterLocStart(), RangeEnd);
1466}
1467
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001468void
Douglas Gregor20527e22010-06-15 17:44:38 +00001469QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1470 unsigned NumTPLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001471 TemplateParameterList **TPLists) {
1472 assert((NumTPLists == 0 || TPLists != 0) &&
1473 "Empty array of template parameters with positive size!");
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001474
1475 // Free previous template parameters (if any).
1476 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001477 Context.Deallocate(TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001478 TemplParamLists = 0;
1479 NumTemplParamLists = 0;
1480 }
1481 // Set info on matched template parameter lists (if any).
1482 if (NumTPLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001483 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001484 NumTemplParamLists = NumTPLists;
1485 for (unsigned i = NumTPLists; i-- > 0; )
1486 TemplParamLists[i] = TPLists[i];
1487 }
1488}
1489
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001490//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001491// VarDecl Implementation
1492//===----------------------------------------------------------------------===//
1493
Sebastian Redl833ef452010-01-26 22:01:41 +00001494const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1495 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001496 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001497 case SC_Auto: return "auto";
1498 case SC_Extern: return "extern";
1499 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1500 case SC_PrivateExtern: return "__private_extern__";
1501 case SC_Register: return "register";
1502 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001503 }
1504
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001505 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001506}
1507
Abramo Bagnaradff19302011-03-08 08:55:46 +00001508VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1509 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001510 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001511 StorageClass S, StorageClass SCAsWritten) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001512 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
Nuno Lopes394ec982008-12-17 23:39:55 +00001513}
1514
Douglas Gregor72172e92012-01-05 21:55:30 +00001515VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1516 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
1517 return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1518 QualType(), 0, SC_None, SC_None);
1519}
1520
Douglas Gregorbf62d642010-12-06 18:36:25 +00001521void VarDecl::setStorageClass(StorageClass SC) {
1522 assert(isLegalForVariable(SC));
1523 if (getStorageClass() != SC)
Rafael Espindola19de5612013-01-12 06:42:30 +00001524 ClearLinkageCache();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001525
John McCallbeaa11c2011-05-01 02:13:58 +00001526 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001527}
1528
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001529SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001530 if (const Expr *Init = getInit()) {
1531 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001532 // If Init is implicit, ignore its source range and fallback on
1533 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1534 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001535 return SourceRange(getOuterLocStart(), InitEnd);
1536 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001537 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001538}
1539
Rafael Espindola88510672013-01-04 21:18:45 +00001540template<typename T>
Rafael Espindolaf4187652013-02-14 01:18:37 +00001541static LanguageLinkage getLanguageLinkageTemplate(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001542 // C++ [dcl.link]p1: All function types, function names with external linkage,
1543 // and variable names with external linkage have a language linkage.
1544 if (!isExternalLinkage(D.getLinkage()))
1545 return NoLanguageLinkage;
1546
1547 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001548 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001549 ASTContext &Context = D.getASTContext();
1550 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001551 return CLanguageLinkage;
1552
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001553 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1554 // language linkage of the names of class members and the function type of
1555 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001556 const DeclContext *DC = D.getDeclContext();
1557 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001558 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001559
1560 // If the first decl is in an extern "C" context, any other redeclaration
1561 // will have C language linkage. If the first one is not in an extern "C"
1562 // context, we would have reported an error for any other decl being in one.
Rafael Espindola88510672013-01-04 21:18:45 +00001563 const T *First = D.getFirstDeclaration();
Rafael Espindolaf4187652013-02-14 01:18:37 +00001564 if (First->getDeclContext()->isExternCContext())
1565 return CLanguageLinkage;
1566 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001567}
1568
Rafael Espindolaf4187652013-02-14 01:18:37 +00001569LanguageLinkage VarDecl::getLanguageLinkage() const {
1570 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001571}
1572
Sebastian Redl833ef452010-01-26 22:01:41 +00001573VarDecl *VarDecl::getCanonicalDecl() {
1574 return getFirstDeclaration();
1575}
1576
Daniel Dunbar9d355812012-03-09 01:51:51 +00001577VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1578 ASTContext &C) const
1579{
Sebastian Redl35351a92010-01-31 22:27:38 +00001580 // C++ [basic.def]p2:
1581 // A declaration is a definition unless [...] it contains the 'extern'
1582 // specifier or a linkage-specification and neither an initializer [...],
1583 // it declares a static data member in a class declaration [...].
1584 // C++ [temp.expl.spec]p15:
1585 // An explicit specialization of a static data member of a template is a
1586 // definition if the declaration includes an initializer; otherwise, it is
1587 // a declaration.
1588 if (isStaticDataMember()) {
1589 if (isOutOfLine() && (hasInit() ||
1590 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1591 return Definition;
1592 else
1593 return DeclarationOnly;
1594 }
1595 // C99 6.7p5:
1596 // A definition of an identifier is a declaration for that identifier that
1597 // [...] causes storage to be reserved for that object.
1598 // Note: that applies for all non-file-scope objects.
1599 // C99 6.9.2p1:
1600 // If the declaration of an identifier for an object has file scope and an
1601 // initializer, the declaration is an external definition for the identifier
1602 if (hasInit())
1603 return Definition;
1604 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1605 if (hasExternalStorage())
1606 return DeclarationOnly;
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001607
John McCall8e7d6562010-08-26 03:08:43 +00001608 if (getStorageClassAsWritten() == SC_Extern ||
1609 getStorageClassAsWritten() == SC_PrivateExtern) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00001610 for (const VarDecl *PrevVar = getPreviousDecl();
1611 PrevVar; PrevVar = PrevVar->getPreviousDecl()) {
Rafael Espindola7581f322012-12-17 22:23:47 +00001612 if (PrevVar->getLinkage() == InternalLinkage)
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001613 return DeclarationOnly;
1614 }
1615 }
Sebastian Redl35351a92010-01-31 22:27:38 +00001616 // C99 6.9.2p2:
1617 // A declaration of an object that has file scope without an initializer,
1618 // and without a storage class specifier or the scs 'static', constitutes
1619 // a tentative definition.
1620 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001621 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00001622 return TentativeDefinition;
1623
1624 // What's left is (in C, block-scope) declarations without initializers or
1625 // external storage. These are definitions.
1626 return Definition;
1627}
1628
Sebastian Redl35351a92010-01-31 22:27:38 +00001629VarDecl *VarDecl::getActingDefinition() {
1630 DefinitionKind Kind = isThisDeclarationADefinition();
1631 if (Kind != TentativeDefinition)
1632 return 0;
1633
Chris Lattner48eb14d2010-06-14 18:31:46 +00001634 VarDecl *LastTentative = 0;
Sebastian Redl35351a92010-01-31 22:27:38 +00001635 VarDecl *First = getFirstDeclaration();
1636 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1637 I != E; ++I) {
1638 Kind = (*I)->isThisDeclarationADefinition();
1639 if (Kind == Definition)
1640 return 0;
1641 else if (Kind == TentativeDefinition)
1642 LastTentative = *I;
1643 }
1644 return LastTentative;
1645}
1646
1647bool VarDecl::isTentativeDefinitionNow() const {
1648 DefinitionKind Kind = isThisDeclarationADefinition();
1649 if (Kind != TentativeDefinition)
1650 return false;
1651
1652 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1653 if ((*I)->isThisDeclarationADefinition() == Definition)
1654 return false;
1655 }
Sebastian Redl5ca79842010-02-01 20:16:42 +00001656 return true;
Sebastian Redl35351a92010-01-31 22:27:38 +00001657}
1658
Daniel Dunbar9d355812012-03-09 01:51:51 +00001659VarDecl *VarDecl::getDefinition(ASTContext &C) {
Sebastian Redlccdb5ff2010-02-02 17:55:12 +00001660 VarDecl *First = getFirstDeclaration();
1661 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1662 I != E; ++I) {
Daniel Dunbar9d355812012-03-09 01:51:51 +00001663 if ((*I)->isThisDeclarationADefinition(C) == Definition)
Sebastian Redl5ca79842010-02-01 20:16:42 +00001664 return *I;
1665 }
1666 return 0;
1667}
1668
Daniel Dunbar9d355812012-03-09 01:51:51 +00001669VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00001670 DefinitionKind Kind = DeclarationOnly;
1671
1672 const VarDecl *First = getFirstDeclaration();
1673 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001674 I != E; ++I) {
Daniel Dunbar9d355812012-03-09 01:51:51 +00001675 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001676 if (Kind == Definition)
1677 break;
1678 }
John McCall37bb6c92010-10-29 22:22:43 +00001679
1680 return Kind;
1681}
1682
Sebastian Redl5ca79842010-02-01 20:16:42 +00001683const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Sebastian Redl833ef452010-01-26 22:01:41 +00001684 redecl_iterator I = redecls_begin(), E = redecls_end();
1685 while (I != E && !I->getInit())
1686 ++I;
1687
1688 if (I != E) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001689 D = *I;
Sebastian Redl833ef452010-01-26 22:01:41 +00001690 return I->getInit();
1691 }
1692 return 0;
1693}
1694
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001695bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00001696 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001697 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001698
1699 if (!isStaticDataMember())
1700 return false;
1701
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001702 // If this static data member was instantiated from a static data member of
1703 // a class template, check whether that static data member was defined
1704 // out-of-line.
1705 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1706 return VD->isOutOfLine();
1707
1708 return false;
1709}
1710
Douglas Gregor1d957a32009-10-27 18:42:08 +00001711VarDecl *VarDecl::getOutOfLineDefinition() {
1712 if (!isStaticDataMember())
1713 return 0;
1714
1715 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1716 RD != RDEnd; ++RD) {
1717 if (RD->getLexicalDeclContext()->isFileContext())
1718 return *RD;
1719 }
1720
1721 return 0;
1722}
1723
Douglas Gregord5058122010-02-11 01:19:42 +00001724void VarDecl::setInit(Expr *I) {
Sebastian Redl833ef452010-01-26 22:01:41 +00001725 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1726 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00001727 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00001728 }
1729
1730 Init = I;
1731}
1732
Daniel Dunbar9d355812012-03-09 01:51:51 +00001733bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001734 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00001735
Richard Smith35ecb362012-03-02 04:14:40 +00001736 if (!Lang.CPlusPlus)
1737 return false;
1738
1739 // In C++11, any variable of reference type can be used in a constant
1740 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001741 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00001742 return true;
1743
1744 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00001745 // not require the variable to be non-volatile, but we consider this to be a
1746 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00001747 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00001748 return false;
1749
1750 // In C++, const, non-volatile variables of integral or enumeration types
1751 // can be used in constant expressions.
1752 if (getType()->isIntegralOrEnumerationType())
1753 return true;
1754
Richard Smith35ecb362012-03-02 04:14:40 +00001755 // Additionally, in C++11, non-volatile constexpr variables can be used in
1756 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001757 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00001758}
1759
Richard Smithd0b4dd62011-12-19 06:19:21 +00001760/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1761/// form, which contains extra information on the evaluated value of the
1762/// initializer.
1763EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1764 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1765 if (!Eval) {
1766 Stmt *S = Init.get<Stmt *>();
1767 Eval = new (getASTContext()) EvaluatedStmt;
1768 Eval->Value = S;
1769 Init = Eval;
1770 }
1771 return Eval;
1772}
1773
Richard Smithdafff942012-01-14 04:30:29 +00001774APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001775 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00001776 return evaluateValue(Notes);
1777}
1778
1779APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001780 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001781 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1782
1783 // We only produce notes indicating why an initializer is non-constant the
1784 // first time it is evaluated. FIXME: The notes won't always be emitted the
1785 // first time we try evaluation, so might not be produced at all.
1786 if (Eval->WasEvaluated)
Richard Smithdafff942012-01-14 04:30:29 +00001787 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001788
1789 const Expr *Init = cast<Expr>(Eval->Value);
1790 assert(!Init->isValueDependent());
1791
1792 if (Eval->IsEvaluating) {
1793 // FIXME: Produce a diagnostic for self-initialization.
1794 Eval->CheckedICE = true;
1795 Eval->IsICE = false;
Richard Smithdafff942012-01-14 04:30:29 +00001796 return 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001797 }
1798
1799 Eval->IsEvaluating = true;
1800
1801 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1802 this, Notes);
1803
1804 // Ensure the result is an uninitialized APValue if evaluation fails.
1805 if (!Result)
1806 Eval->Evaluated = APValue();
1807
1808 Eval->IsEvaluating = false;
1809 Eval->WasEvaluated = true;
1810
1811 // In C++11, we have determined whether the initializer was a constant
1812 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001813 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001814 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00001815 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00001816 }
1817
Richard Smithdafff942012-01-14 04:30:29 +00001818 return Result ? &Eval->Evaluated : 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001819}
1820
1821bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00001822 // Initializers of weak variables are never ICEs.
1823 if (isWeak())
1824 return false;
1825
Richard Smithd0b4dd62011-12-19 06:19:21 +00001826 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1827 if (Eval->CheckedICE)
1828 // We have already checked whether this subexpression is an
1829 // integral constant expression.
1830 return Eval->IsICE;
1831
1832 const Expr *Init = cast<Expr>(Eval->Value);
1833 assert(!Init->isValueDependent());
1834
1835 // In C++11, evaluate the initializer to check whether it's a constant
1836 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001837 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001838 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001839 evaluateValue(Notes);
1840 return Eval->IsICE;
1841 }
1842
1843 // It's an ICE whether or not the definition we found is
1844 // out-of-line. See DR 721 and the discussion in Clang PR
1845 // 6206 for details.
1846
1847 if (Eval->CheckingICE)
1848 return false;
1849 Eval->CheckingICE = true;
1850
1851 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1852 Eval->CheckingICE = false;
1853 Eval->CheckedICE = true;
1854 return Eval->IsICE;
1855}
1856
Douglas Gregorfe314812011-06-21 17:03:29 +00001857bool VarDecl::extendsLifetimeOfTemporary() const {
Douglas Gregord410c082011-06-21 18:20:46 +00001858 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
Douglas Gregorfe314812011-06-21 17:03:29 +00001859
1860 const Expr *E = getInit();
1861 if (!E)
1862 return false;
1863
1864 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1865 E = Cleanups->getSubExpr();
1866
1867 return isa<MaterializeTemporaryExpr>(E);
1868}
1869
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001870VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001871 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001872 return cast<VarDecl>(MSI->getInstantiatedFrom());
1873
1874 return 0;
1875}
1876
Douglas Gregor3c74d412009-10-14 20:14:33 +00001877TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001878 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001879 return MSI->getTemplateSpecializationKind();
1880
1881 return TSK_Undeclared;
1882}
1883
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001884MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001885 return getASTContext().getInstantiatedFromStaticDataMember(this);
1886}
1887
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001888void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1889 SourceLocation PointOfInstantiation) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001890 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00001891 assert(MSI && "Not an instantiated static data member?");
1892 MSI->setTemplateSpecializationKind(TSK);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001893 if (TSK != TSK_ExplicitSpecialization &&
1894 PointOfInstantiation.isValid() &&
1895 MSI->getPointOfInstantiation().isInvalid())
1896 MSI->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001897}
1898
Sebastian Redl833ef452010-01-26 22:01:41 +00001899//===----------------------------------------------------------------------===//
1900// ParmVarDecl Implementation
1901//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00001902
Sebastian Redl833ef452010-01-26 22:01:41 +00001903ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001904 SourceLocation StartLoc,
1905 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00001906 QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001907 StorageClass S, StorageClass SCAsWritten,
1908 Expr *DefArg) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001909 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001910 S, SCAsWritten, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00001911}
1912
Douglas Gregor72172e92012-01-05 21:55:30 +00001913ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1914 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
1915 return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
1916 0, QualType(), 0, SC_None, SC_None, 0);
1917}
1918
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00001919SourceRange ParmVarDecl::getSourceRange() const {
1920 if (!hasInheritedDefaultArg()) {
1921 SourceRange ArgRange = getDefaultArgRange();
1922 if (ArgRange.isValid())
1923 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1924 }
1925
1926 return DeclaratorDecl::getSourceRange();
1927}
1928
Sebastian Redl833ef452010-01-26 22:01:41 +00001929Expr *ParmVarDecl::getDefaultArg() {
1930 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1931 assert(!hasUninstantiatedDefaultArg() &&
1932 "Default argument is not yet instantiated!");
1933
1934 Expr *Arg = getInit();
John McCall5d413782010-12-06 08:20:24 +00001935 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00001936 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00001937
Sebastian Redl833ef452010-01-26 22:01:41 +00001938 return Arg;
1939}
1940
Sebastian Redl833ef452010-01-26 22:01:41 +00001941SourceRange ParmVarDecl::getDefaultArgRange() const {
1942 if (const Expr *E = getInit())
1943 return E->getSourceRange();
1944
1945 if (hasUninstantiatedDefaultArg())
1946 return getUninstantiatedDefaultArg()->getSourceRange();
1947
1948 return SourceRange();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00001949}
1950
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00001951bool ParmVarDecl::isParameterPack() const {
1952 return isa<PackExpansionType>(getType());
1953}
1954
Ted Kremenek540017e2011-10-06 05:00:56 +00001955void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1956 getASTContext().setParameterIndex(this, parameterIndex);
1957 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1958}
1959
1960unsigned ParmVarDecl::getParameterIndexLarge() const {
1961 return getASTContext().getParameterIndex(this);
1962}
1963
Nuno Lopes394ec982008-12-17 23:39:55 +00001964//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00001965// FunctionDecl Implementation
1966//===----------------------------------------------------------------------===//
1967
Benjamin Kramer9170e912013-02-22 15:46:01 +00001968void FunctionDecl::getNameForDiagnostic(
1969 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
1970 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00001971 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1972 if (TemplateArgs)
Benjamin Kramer9170e912013-02-22 15:46:01 +00001973 TemplateSpecializationType::PrintTemplateArgumentList(
1974 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00001975}
1976
Ted Kremenek186a0742010-04-29 16:49:01 +00001977bool FunctionDecl::isVariadic() const {
1978 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1979 return FT->isVariadic();
1980 return false;
1981}
1982
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001983bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1984 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Francois Pichet1c229c02011-04-22 22:18:13 +00001985 if (I->Body || I->IsLateTemplateParsed) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001986 Definition = *I;
1987 return true;
1988 }
1989 }
1990
1991 return false;
1992}
1993
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001994bool FunctionDecl::hasTrivialBody() const
1995{
1996 Stmt *S = getBody();
1997 if (!S) {
1998 // Since we don't have a body for this function, we don't know if it's
1999 // trivial or not.
2000 return false;
2001 }
2002
2003 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2004 return true;
2005 return false;
2006}
2007
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002008bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
2009 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00002010 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002011 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
2012 return true;
2013 }
2014 }
2015
2016 return false;
2017}
2018
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002019Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Argyrios Kyrtzidis1506d9b2009-07-14 03:20:21 +00002020 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
2021 if (I->Body) {
2022 Definition = *I;
2023 return I->Body.get(getASTContext().getExternalSource());
Francois Pichet1c229c02011-04-22 22:18:13 +00002024 } else if (I->IsLateTemplateParsed) {
2025 Definition = *I;
2026 return 0;
Douglas Gregor89f238c2008-04-21 02:02:58 +00002027 }
2028 }
2029
2030 return 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002031}
2032
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002033void FunctionDecl::setBody(Stmt *B) {
2034 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002035 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002036 EndRangeLoc = B->getLocEnd();
2037}
2038
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002039void FunctionDecl::setPure(bool P) {
2040 IsPure = P;
2041 if (P)
2042 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2043 Parent->markedVirtualFunctionPure();
2044}
2045
Douglas Gregor16618f22009-09-12 00:17:51 +00002046bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002047 const TranslationUnitDecl *tunit =
2048 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2049 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002050 !tunit->getASTContext().getLangOpts().Freestanding &&
John McCall53ffd372011-05-15 17:49:20 +00002051 getIdentifier() &&
2052 getIdentifier()->isStr("main");
2053}
2054
2055bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2056 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2057 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2058 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2059 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2060 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2061
2062 if (isa<CXXRecordDecl>(getDeclContext())) return false;
2063 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
2064
2065 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
2066 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
2067
2068 ASTContext &Context =
2069 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2070 ->getASTContext();
2071
2072 // The result type and first argument type are constant across all
2073 // these operators. The second argument must be exactly void*.
2074 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002075}
2076
Rafael Espindolaf4187652013-02-14 01:18:37 +00002077LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Rafael Espindola6239e052013-01-12 15:27:44 +00002078 // Users expect to be able to write
2079 // extern "C" void *__builtin_alloca (size_t);
2080 // so consider builtins as having C language linkage.
Rafael Espindolac48f7342013-01-12 15:27:43 +00002081 if (getBuiltinID())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002082 return CLanguageLinkage;
Rafael Espindolac48f7342013-01-12 15:27:43 +00002083
Rafael Espindolaf4187652013-02-14 01:18:37 +00002084 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002085}
2086
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002087bool FunctionDecl::isGlobal() const {
2088 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2089 return Method->isStatic();
2090
John McCall8e7d6562010-08-26 03:08:43 +00002091 if (getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002092 return false;
2093
Mike Stump11289f42009-09-09 15:08:12 +00002094 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002095 DC->isNamespace();
2096 DC = DC->getParent()) {
2097 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2098 if (!Namespace->getDeclName())
2099 return false;
2100 break;
2101 }
2102 }
2103
2104 return true;
2105}
2106
Richard Smith10876ef2013-01-17 01:30:42 +00002107bool FunctionDecl::isNoReturn() const {
2108 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
Richard Smithdebc59d2013-01-30 05:45:05 +00002109 hasAttr<C11NoReturnAttr>() ||
Richard Smith10876ef2013-01-17 01:30:42 +00002110 getType()->getAs<FunctionType>()->getNoReturnAttr();
2111}
2112
Sebastian Redl833ef452010-01-26 22:01:41 +00002113void
2114FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2115 redeclarable_base::setPreviousDeclaration(PrevDecl);
2116
2117 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2118 FunctionTemplateDecl *PrevFunTmpl
2119 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
2120 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2121 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
2122 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002123
Axel Naumannfbc7b982011-11-08 18:21:06 +00002124 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002125 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002126}
2127
2128const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
2129 return getFirstDeclaration();
2130}
2131
2132FunctionDecl *FunctionDecl::getCanonicalDecl() {
2133 return getFirstDeclaration();
2134}
2135
Douglas Gregorbf62d642010-12-06 18:36:25 +00002136void FunctionDecl::setStorageClass(StorageClass SC) {
2137 assert(isLegalForFunction(SC));
2138 if (getStorageClass() != SC)
Rafael Espindola19de5612013-01-12 06:42:30 +00002139 ClearLinkageCache();
Douglas Gregorbf62d642010-12-06 18:36:25 +00002140
2141 SClass = SC;
2142}
2143
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002144/// \brief Returns a value indicating whether this function
2145/// corresponds to a builtin function.
2146///
2147/// The function corresponds to a built-in function if it is
2148/// declared at translation scope or within an extern "C" block and
2149/// its name matches with the name of a builtin. The returned value
2150/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002151/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002152/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002153unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002154 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002155 return 0;
2156
2157 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002158 if (!BuiltinID)
2159 return 0;
2160
2161 ASTContext &Context = getASTContext();
Douglas Gregore711f702009-02-14 18:57:46 +00002162 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2163 return BuiltinID;
2164
2165 // This function has the name of a known C library
2166 // function. Determine whether it actually refers to the C library
2167 // function or whether it just has the same name.
2168
Douglas Gregora908e7f2009-02-17 03:23:10 +00002169 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002170 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002171 return 0;
2172
Douglas Gregore711f702009-02-14 18:57:46 +00002173 // If this function is at translation-unit scope and we're not in
2174 // C++, it refers to the C library function.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002175 if (!Context.getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +00002176 getDeclContext()->isTranslationUnit())
2177 return BuiltinID;
2178
2179 // If the function is in an extern "C" linkage specification and is
2180 // not marked "overloadable", it's the real function.
2181 if (isa<LinkageSpecDecl>(getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002182 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
Douglas Gregore711f702009-02-14 18:57:46 +00002183 == LinkageSpecDecl::lang_c &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002184 !getAttr<OverloadableAttr>())
Douglas Gregore711f702009-02-14 18:57:46 +00002185 return BuiltinID;
2186
2187 // Not a builtin
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002188 return 0;
2189}
2190
2191
Chris Lattner47c0d002009-04-25 06:03:53 +00002192/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002193/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002194/// after it has been created.
2195unsigned FunctionDecl::getNumParams() const {
Eli Friedman5c27c4c2012-08-30 22:22:09 +00002196 const FunctionType *FT = getType()->castAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002197 if (isa<FunctionNoProtoType>(FT))
Chris Lattner88f70d62008-03-15 05:43:15 +00002198 return 0;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002199 return cast<FunctionProtoType>(FT)->getNumArgs();
Mike Stump11289f42009-09-09 15:08:12 +00002200
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002201}
2202
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002203void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002204 ArrayRef<ParmVarDecl *> NewParamInfo) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002205 assert(ParamInfo == 0 && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002206 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002207
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002208 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002209 if (!NewParamInfo.empty()) {
2210 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2211 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002212 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002213}
Chris Lattner41943152007-01-25 04:52:46 +00002214
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002215void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
James Molloy6f8780b2012-02-29 10:24:19 +00002216 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2217
2218 if (!NewDecls.empty()) {
2219 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2220 std::copy(NewDecls.begin(), NewDecls.end(), A);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002221 DeclsInPrototypeScope = ArrayRef<NamedDecl *>(A, NewDecls.size());
James Molloy6f8780b2012-02-29 10:24:19 +00002222 }
2223}
2224
Chris Lattner58258242008-04-10 02:22:51 +00002225/// getMinRequiredArguments - Returns the minimum number of arguments
2226/// needed to call this function. This may be fewer than the number of
2227/// function parameters, if some of the parameters have default
Douglas Gregor7825bf32011-01-06 22:09:01 +00002228/// arguments (in C++) or the last parameter is a parameter pack.
Chris Lattner58258242008-04-10 02:22:51 +00002229unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002230 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002231 return getNumParams();
2232
Douglas Gregor7825bf32011-01-06 22:09:01 +00002233 unsigned NumRequiredArgs = getNumParams();
2234
2235 // If the last parameter is a parameter pack, we don't need an argument for
2236 // it.
2237 if (NumRequiredArgs > 0 &&
2238 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
2239 --NumRequiredArgs;
2240
2241 // If this parameter has a default argument, we don't need an argument for
2242 // it.
2243 while (NumRequiredArgs > 0 &&
2244 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
Chris Lattner58258242008-04-10 02:22:51 +00002245 --NumRequiredArgs;
2246
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002247 // We might have parameter packs before the end. These can't be deduced,
2248 // but they can still handle multiple arguments.
2249 unsigned ArgIdx = NumRequiredArgs;
2250 while (ArgIdx > 0) {
2251 if (getParamDecl(ArgIdx - 1)->isParameterPack())
2252 NumRequiredArgs = ArgIdx;
2253
2254 --ArgIdx;
2255 }
2256
Chris Lattner58258242008-04-10 02:22:51 +00002257 return NumRequiredArgs;
2258}
2259
Eli Friedman1b125c32012-02-07 03:50:18 +00002260static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2261 // Only consider file-scope declarations in this test.
2262 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2263 return false;
2264
2265 // Only consider explicit declarations; the presence of a builtin for a
2266 // libcall shouldn't affect whether a definition is externally visible.
2267 if (Redecl->isImplicit())
2268 return false;
2269
2270 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2271 return true; // Not an inline definition
2272
2273 return false;
2274}
2275
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002276/// \brief For a function declaration in C or C++, determine whether this
2277/// declaration causes the definition to be externally visible.
2278///
Eli Friedman1b125c32012-02-07 03:50:18 +00002279/// Specifically, this determines if adding the current declaration to the set
2280/// of redeclarations of the given functions causes
2281/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002282bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2283 assert(!doesThisDeclarationHaveABody() &&
2284 "Must have a declaration without a body.");
2285
2286 ASTContext &Context = getASTContext();
2287
David Blaikiebbafb8a2012-03-11 07:00:24 +00002288 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002289 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2290 // an externally visible definition.
2291 //
2292 // FIXME: What happens if gnu_inline gets added on after the first
2293 // declaration?
2294 if (!isInlineSpecified() || getStorageClassAsWritten() == SC_Extern)
2295 return false;
2296
2297 const FunctionDecl *Prev = this;
2298 bool FoundBody = false;
2299 while ((Prev = Prev->getPreviousDecl())) {
2300 FoundBody |= Prev->Body;
2301
2302 if (Prev->Body) {
2303 // If it's not the case that both 'inline' and 'extern' are
2304 // specified on the definition, then it is always externally visible.
2305 if (!Prev->isInlineSpecified() ||
2306 Prev->getStorageClassAsWritten() != SC_Extern)
2307 return false;
2308 } else if (Prev->isInlineSpecified() &&
2309 Prev->getStorageClassAsWritten() != SC_Extern) {
2310 return false;
2311 }
2312 }
2313 return FoundBody;
2314 }
2315
David Blaikiebbafb8a2012-03-11 07:00:24 +00002316 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002317 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002318
2319 // C99 6.7.4p6:
2320 // [...] If all of the file scope declarations for a function in a
2321 // translation unit include the inline function specifier without extern,
2322 // then the definition in that translation unit is an inline definition.
2323 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002324 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002325 const FunctionDecl *Prev = this;
2326 bool FoundBody = false;
2327 while ((Prev = Prev->getPreviousDecl())) {
2328 FoundBody |= Prev->Body;
2329 if (RedeclForcesDefC99(Prev))
2330 return false;
2331 }
2332 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002333}
2334
Richard Smithf3814ad2013-01-25 00:08:28 +00002335/// \brief For an inline function definition in C, or for a gnu_inline function
2336/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002337///
2338/// Inline function definitions are always available for inlining optimizations.
2339/// However, depending on the language dialect, declaration specifiers, and
2340/// attributes, the definition of an inline function may or may not be
2341/// "externally" visible to other translation units in the program.
2342///
2343/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00002344/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00002345/// inline definition becomes externally visible (C99 6.7.4p6).
2346///
2347/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2348/// definition, we use the GNU semantics for inline, which are nearly the
2349/// opposite of C99 semantics. In particular, "inline" by itself will create
2350/// an externally visible symbol, but "extern inline" will not create an
2351/// externally visible symbol.
2352bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002353 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002354 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00002355 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00002356
David Blaikiebbafb8a2012-03-11 07:00:24 +00002357 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002358 // Note: If you change the logic here, please change
2359 // doesDeclarationForceExternallyVisibleDefinition as well.
2360 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00002361 // If it's not the case that both 'inline' and 'extern' are
2362 // specified on the definition, then this inline definition is
2363 // externally visible.
2364 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
2365 return true;
2366
2367 // If any declaration is 'inline' but not 'extern', then this definition
2368 // is externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002369 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2370 Redecl != RedeclEnd;
2371 ++Redecl) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00002372 if (Redecl->isInlineSpecified() &&
2373 Redecl->getStorageClassAsWritten() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00002374 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00002375 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00002376
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002377 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002378 }
Eli Friedman1b125c32012-02-07 03:50:18 +00002379
Richard Smithf3814ad2013-01-25 00:08:28 +00002380 // The rest of this function is C-only.
2381 assert(!Context.getLangOpts().CPlusPlus &&
2382 "should not use C inline rules in C++");
2383
Douglas Gregor299d76e2009-09-13 07:46:26 +00002384 // C99 6.7.4p6:
2385 // [...] If all of the file scope declarations for a function in a
2386 // translation unit include the inline function specifier without extern,
2387 // then the definition in that translation unit is an inline definition.
2388 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2389 Redecl != RedeclEnd;
2390 ++Redecl) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002391 if (RedeclForcesDefC99(*Redecl))
2392 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002393 }
2394
2395 // C99 6.7.4p6:
2396 // An inline definition does not provide an external definition for the
2397 // function, and does not forbid an external definition in another
2398 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002399 return false;
2400}
2401
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002402/// getOverloadedOperator - Which C++ overloaded operator this
2403/// function represents, if any.
2404OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00002405 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2406 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002407 else
2408 return OO_None;
2409}
2410
Alexis Huntc88db062010-01-13 09:01:02 +00002411/// getLiteralIdentifier - The literal suffix identifier this function
2412/// represents, if any.
2413const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2414 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2415 return getDeclName().getCXXLiteralIdentifier();
2416 else
2417 return 0;
2418}
2419
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002420FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2421 if (TemplateOrSpecialization.isNull())
2422 return TK_NonTemplate;
2423 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2424 return TK_FunctionTemplate;
2425 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2426 return TK_MemberSpecialization;
2427 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2428 return TK_FunctionTemplateSpecialization;
2429 if (TemplateOrSpecialization.is
2430 <DependentFunctionTemplateSpecializationInfo*>())
2431 return TK_DependentFunctionTemplateSpecialization;
2432
David Blaikie83d382b2011-09-23 05:06:16 +00002433 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002434}
2435
Douglas Gregord801b062009-10-07 23:56:10 +00002436FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002437 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00002438 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2439
2440 return 0;
2441}
2442
2443void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002444FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2445 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00002446 TemplateSpecializationKind TSK) {
2447 assert(TemplateOrSpecialization.isNull() &&
2448 "Member function is already a specialization");
2449 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002450 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00002451 TemplateOrSpecialization = Info;
2452}
2453
Douglas Gregorafca3b42009-10-27 20:53:28 +00002454bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00002455 // If the function is invalid, it can't be implicitly instantiated.
2456 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00002457 return false;
2458
2459 switch (getTemplateSpecializationKind()) {
2460 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00002461 case TSK_ExplicitInstantiationDefinition:
2462 return false;
2463
2464 case TSK_ImplicitInstantiation:
2465 return true;
2466
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002467 // It is possible to instantiate TSK_ExplicitSpecialization kind
2468 // if the FunctionDecl has a class scope specialization pattern.
2469 case TSK_ExplicitSpecialization:
2470 return getClassScopeSpecializationPattern() != 0;
2471
Douglas Gregorafca3b42009-10-27 20:53:28 +00002472 case TSK_ExplicitInstantiationDeclaration:
2473 // Handled below.
2474 break;
2475 }
2476
2477 // Find the actual template from which we will instantiate.
2478 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002479 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00002480 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002481 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00002482
2483 // C++0x [temp.explicit]p9:
2484 // Except for inline functions, other explicit instantiation declarations
2485 // have the effect of suppressing the implicit instantiation of the entity
2486 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002487 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00002488 return true;
2489
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002490 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00002491}
2492
2493bool FunctionDecl::isTemplateInstantiation() const {
2494 switch (getTemplateSpecializationKind()) {
2495 case TSK_Undeclared:
2496 case TSK_ExplicitSpecialization:
2497 return false;
2498 case TSK_ImplicitInstantiation:
2499 case TSK_ExplicitInstantiationDeclaration:
2500 case TSK_ExplicitInstantiationDefinition:
2501 return true;
2502 }
2503 llvm_unreachable("All TSK values handled.");
2504}
Douglas Gregorafca3b42009-10-27 20:53:28 +00002505
2506FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002507 // Handle class scope explicit specialization special case.
2508 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2509 return getClassScopeSpecializationPattern();
2510
Douglas Gregorafca3b42009-10-27 20:53:28 +00002511 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2512 while (Primary->getInstantiatedFromMemberTemplate()) {
2513 // If we have hit a point where the user provided a specialization of
2514 // this template, we're done looking.
2515 if (Primary->isMemberSpecialization())
2516 break;
2517
2518 Primary = Primary->getInstantiatedFromMemberTemplate();
2519 }
2520
2521 return Primary->getTemplatedDecl();
2522 }
2523
2524 return getInstantiatedFromMemberFunction();
2525}
2526
Douglas Gregor70d83e22009-06-29 17:30:29 +00002527FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00002528 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002529 = TemplateOrSpecialization
2530 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00002531 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00002532 }
2533 return 0;
2534}
2535
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002536FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2537 return getASTContext().getClassScopeSpecializationPattern(this);
2538}
2539
Douglas Gregor70d83e22009-06-29 17:30:29 +00002540const TemplateArgumentList *
2541FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00002542 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00002543 = TemplateOrSpecialization
2544 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00002545 return Info->TemplateArguments;
2546 }
2547 return 0;
2548}
2549
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00002550const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002551FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2552 if (FunctionTemplateSpecializationInfo *Info
2553 = TemplateOrSpecialization
2554 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2555 return Info->TemplateArgumentsAsWritten;
2556 }
2557 return 0;
2558}
2559
Mike Stump11289f42009-09-09 15:08:12 +00002560void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002561FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2562 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002563 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002564 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002565 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00002566 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2567 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002568 assert(TSK != TSK_Undeclared &&
2569 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00002570 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002571 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002572 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00002573 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2574 TemplateArgs,
2575 TemplateArgsAsWritten,
2576 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002577 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00002578 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002579}
2580
John McCallb9c78482010-04-08 09:05:18 +00002581void
2582FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2583 const UnresolvedSetImpl &Templates,
2584 const TemplateArgumentListInfo &TemplateArgs) {
2585 assert(TemplateOrSpecialization.isNull());
2586 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2587 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall900d9802010-04-13 22:18:28 +00002588 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallb9c78482010-04-08 09:05:18 +00002589 void *Buffer = Context.Allocate(Size);
2590 DependentFunctionTemplateSpecializationInfo *Info =
2591 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2592 TemplateArgs);
2593 TemplateOrSpecialization = Info;
2594}
2595
2596DependentFunctionTemplateSpecializationInfo::
2597DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2598 const TemplateArgumentListInfo &TArgs)
2599 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2600
2601 d.NumTemplates = Ts.size();
2602 d.NumArgs = TArgs.size();
2603
2604 FunctionTemplateDecl **TsArray =
2605 const_cast<FunctionTemplateDecl**>(getTemplates());
2606 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2607 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2608
2609 TemplateArgumentLoc *ArgsArray =
2610 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2611 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2612 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2613}
2614
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002615TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00002616 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002617 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00002618 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00002619 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00002620 if (FTSInfo)
2621 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00002622
Douglas Gregord801b062009-10-07 23:56:10 +00002623 MemberSpecializationInfo *MSInfo
2624 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2625 if (MSInfo)
2626 return MSInfo->getTemplateSpecializationKind();
2627
2628 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002629}
2630
Mike Stump11289f42009-09-09 15:08:12 +00002631void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002632FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2633 SourceLocation PointOfInstantiation) {
2634 if (FunctionTemplateSpecializationInfo *FTSInfo
2635 = TemplateOrSpecialization.dyn_cast<
2636 FunctionTemplateSpecializationInfo*>()) {
2637 FTSInfo->setTemplateSpecializationKind(TSK);
2638 if (TSK != TSK_ExplicitSpecialization &&
2639 PointOfInstantiation.isValid() &&
2640 FTSInfo->getPointOfInstantiation().isInvalid())
2641 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2642 } else if (MemberSpecializationInfo *MSInfo
2643 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2644 MSInfo->setTemplateSpecializationKind(TSK);
2645 if (TSK != TSK_ExplicitSpecialization &&
2646 PointOfInstantiation.isValid() &&
2647 MSInfo->getPointOfInstantiation().isInvalid())
2648 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2649 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002650 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002651}
2652
2653SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00002654 if (FunctionTemplateSpecializationInfo *FTSInfo
2655 = TemplateOrSpecialization.dyn_cast<
2656 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002657 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00002658 else if (MemberSpecializationInfo *MSInfo
2659 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002660 return MSInfo->getPointOfInstantiation();
2661
2662 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00002663}
2664
Douglas Gregor6411b922009-09-11 20:15:17 +00002665bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002666 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00002667 return true;
2668
2669 // If this function was instantiated from a member function of a
2670 // class template, check whether that member function was defined out-of-line.
2671 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2672 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002673 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002674 return Definition->isOutOfLine();
2675 }
2676
2677 // If this function was instantiated from a function template,
2678 // check whether that function template was defined out-of-line.
2679 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2680 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002681 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002682 return Definition->isOutOfLine();
2683 }
2684
2685 return false;
2686}
2687
Abramo Bagnaraea947882011-03-08 16:41:52 +00002688SourceRange FunctionDecl::getSourceRange() const {
2689 return SourceRange(getOuterLocStart(), EndRangeLoc);
2690}
2691
Anna Zaks28db7ce2012-01-18 02:45:01 +00002692unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00002693 IdentifierInfo *FnInfo = getIdentifier();
2694
2695 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00002696 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002697
2698 // Builtin handling.
2699 switch (getBuiltinID()) {
2700 case Builtin::BI__builtin_memset:
2701 case Builtin::BI__builtin___memset_chk:
2702 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00002703 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00002704
2705 case Builtin::BI__builtin_memcpy:
2706 case Builtin::BI__builtin___memcpy_chk:
2707 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00002708 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002709
2710 case Builtin::BI__builtin_memmove:
2711 case Builtin::BI__builtin___memmove_chk:
2712 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00002713 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00002714
2715 case Builtin::BIstrlcpy:
Anna Zaks22122702012-01-17 00:37:07 +00002716 return Builtin::BIstrlcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002717 case Builtin::BIstrlcat:
Anna Zaks22122702012-01-17 00:37:07 +00002718 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00002719
2720 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00002721 case Builtin::BImemcmp:
2722 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002723
2724 case Builtin::BI__builtin_strncpy:
2725 case Builtin::BI__builtin___strncpy_chk:
2726 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00002727 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002728
2729 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00002730 case Builtin::BIstrncmp:
2731 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002732
2733 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00002734 case Builtin::BIstrncasecmp:
2735 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002736
2737 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00002738 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00002739 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00002740 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00002741
2742 case Builtin::BI__builtin_strndup:
2743 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00002744 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00002745
Anna Zaks314cd092012-02-01 19:08:57 +00002746 case Builtin::BI__builtin_strlen:
2747 case Builtin::BIstrlen:
2748 return Builtin::BIstrlen;
2749
Anna Zaks201d4892012-01-13 21:52:01 +00002750 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00002751 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00002752 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00002753 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00002754 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00002755 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002756 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00002757 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00002758 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002759 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002760 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00002761 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002762 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002763 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002764 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002765 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002766 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00002767 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00002768 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00002769 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00002770 else if (FnInfo->isStr("strlen"))
2771 return Builtin::BIstrlen;
Anna Zaks201d4892012-01-13 21:52:01 +00002772 }
2773 break;
2774 }
Anna Zaks22122702012-01-17 00:37:07 +00002775 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002776}
2777
Chris Lattner59a25942008-03-31 00:36:02 +00002778//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002779// FieldDecl Implementation
2780//===----------------------------------------------------------------------===//
2781
Jay Foad39c79802011-01-12 09:06:06 +00002782FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002783 SourceLocation StartLoc, SourceLocation IdLoc,
2784 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00002785 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00002786 InClassInitStyle InitStyle) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002787 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +00002788 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00002789}
2790
Douglas Gregor72172e92012-01-05 21:55:30 +00002791FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2792 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
2793 return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
Richard Smith2b013182012-06-10 03:12:00 +00002794 0, QualType(), 0, 0, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00002795}
2796
Sebastian Redl833ef452010-01-26 22:01:41 +00002797bool FieldDecl::isAnonymousStructOrUnion() const {
2798 if (!isImplicit() || getDeclName())
2799 return false;
2800
2801 if (const RecordType *Record = getType()->getAs<RecordType>())
2802 return Record->getDecl()->isAnonymousStructOrUnion();
2803
2804 return false;
2805}
2806
Richard Smithcaf33902011-10-10 18:28:20 +00002807unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2808 assert(isBitField() && "not a bitfield");
2809 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2810 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2811}
2812
John McCall4e819612011-01-20 07:57:12 +00002813unsigned FieldDecl::getFieldIndex() const {
2814 if (CachedFieldIndex) return CachedFieldIndex - 1;
2815
Richard Smithd62306a2011-11-10 06:34:14 +00002816 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002817 const RecordDecl *RD = getParent();
2818 const FieldDecl *LastFD = 0;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00002819 bool IsMsStruct = RD->isMsStruct(getASTContext());
Richard Smithd62306a2011-11-10 06:34:14 +00002820
2821 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2822 I != E; ++I, ++Index) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00002823 I->CachedFieldIndex = Index + 1;
John McCall4e819612011-01-20 07:57:12 +00002824
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002825 if (IsMsStruct) {
2826 // Zero-length bitfields following non-bitfield members are ignored.
David Blaikie40ed2972012-06-06 20:45:41 +00002827 if (getASTContext().ZeroBitfieldFollowsNonBitfield(*I, LastFD)) {
Richard Smithd62306a2011-11-10 06:34:14 +00002828 --Index;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002829 continue;
2830 }
David Blaikie40ed2972012-06-06 20:45:41 +00002831 LastFD = *I;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002832 }
John McCall4e819612011-01-20 07:57:12 +00002833 }
2834
Richard Smithd62306a2011-11-10 06:34:14 +00002835 assert(CachedFieldIndex && "failed to find field in parent");
2836 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00002837}
2838
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002839SourceRange FieldDecl::getSourceRange() const {
Abramo Bagnaraff371ac2011-08-05 08:02:55 +00002840 if (const Expr *E = InitializerOrBitWidth.getPointer())
2841 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00002842 return DeclaratorDecl::getSourceRange();
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002843}
2844
Abramo Bagnarab1cdde72012-07-02 20:35:48 +00002845void FieldDecl::setBitWidth(Expr *Width) {
2846 assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
2847 "bit width or initializer already set");
2848 InitializerOrBitWidth.setPointer(Width);
2849}
2850
Richard Smith938f40b2011-06-11 17:19:42 +00002851void FieldDecl::setInClassInitializer(Expr *Init) {
Richard Smith2b013182012-06-10 03:12:00 +00002852 assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
Richard Smith938f40b2011-06-11 17:19:42 +00002853 "bit width or initializer already set");
2854 InitializerOrBitWidth.setPointer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00002855}
2856
Sebastian Redl833ef452010-01-26 22:01:41 +00002857//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002858// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00002859//===----------------------------------------------------------------------===//
2860
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002861SourceLocation TagDecl::getOuterLocStart() const {
2862 return getTemplateOrInnerLocStart(this);
2863}
2864
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002865SourceRange TagDecl::getSourceRange() const {
2866 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002867 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002868}
2869
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002870TagDecl* TagDecl::getCanonicalDecl() {
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002871 return getFirstDeclaration();
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002872}
2873
Richard Smithdda56e42011-04-15 14:24:37 +00002874void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2875 TypedefNameDeclOrQualifier = TDD;
Douglas Gregora72a4e32010-05-19 18:39:18 +00002876 if (TypeForDecl)
Rafael Espindola19de5612013-01-12 06:42:30 +00002877 const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
2878 ClearLinkageCache();
Douglas Gregora72a4e32010-05-19 18:39:18 +00002879}
2880
Douglas Gregordee1be82009-01-17 00:42:38 +00002881void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002882 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00002883
David Blaikie095deba2012-11-14 01:52:05 +00002884 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
John McCall67da35c2010-02-04 22:26:26 +00002885 struct CXXRecordDecl::DefinitionData *Data =
2886 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
John McCall93cc7322010-03-26 21:56:38 +00002887 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2888 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00002889 }
Douglas Gregordee1be82009-01-17 00:42:38 +00002890}
2891
2892void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00002893 assert((!isa<CXXRecordDecl>(this) ||
2894 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2895 "definition completed but not started");
2896
John McCallf937c022011-10-07 06:10:15 +00002897 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002898 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00002899
2900 if (ASTMutationListener *L = getASTMutationListener())
2901 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00002902}
2903
John McCallf937c022011-10-07 06:10:15 +00002904TagDecl *TagDecl::getDefinition() const {
2905 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002906 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002907
2908 // If it's possible for us to have an out-of-date definition, check now.
2909 if (MayHaveOutOfDateDef) {
2910 if (IdentifierInfo *II = getIdentifier()) {
2911 if (II->isOutOfDate()) {
2912 updateOutOfDate(*II);
2913 }
2914 }
2915 }
2916
Andrew Trickba266ee2010-10-19 21:54:32 +00002917 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2918 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00002919
2920 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002921 R != REnd; ++R)
John McCallf937c022011-10-07 06:10:15 +00002922 if (R->isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002923 return *R;
Mike Stump11289f42009-09-09 15:08:12 +00002924
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002925 return 0;
Ted Kremenek21475702008-09-05 17:16:31 +00002926}
2927
Douglas Gregor14454802011-02-25 02:25:35 +00002928void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2929 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00002930 // Make sure the extended qualifier info is allocated.
2931 if (!hasExtInfo())
Richard Smithdda56e42011-04-15 14:24:37 +00002932 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00002933 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00002934 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002935 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00002936 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00002937 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00002938 if (getExtInfo()->NumTemplParamLists == 0) {
2939 getASTContext().Deallocate(getExtInfo());
Richard Smithdda56e42011-04-15 14:24:37 +00002940 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002941 }
2942 else
2943 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00002944 }
2945 }
2946}
2947
Abramo Bagnara60804e12011-03-18 15:16:37 +00002948void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2949 unsigned NumTPLists,
2950 TemplateParameterList **TPLists) {
2951 assert(NumTPLists > 0);
2952 // Make sure the extended decl info is allocated.
2953 if (!hasExtInfo())
2954 // Allocate external info struct.
Richard Smithdda56e42011-04-15 14:24:37 +00002955 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002956 // Set the template parameter lists info.
2957 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2958}
2959
Ted Kremenek21475702008-09-05 17:16:31 +00002960//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002961// EnumDecl Implementation
2962//===----------------------------------------------------------------------===//
2963
David Blaikie68e081d2011-12-20 02:48:34 +00002964void EnumDecl::anchor() { }
2965
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002966EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2967 SourceLocation StartLoc, SourceLocation IdLoc,
2968 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002969 EnumDecl *PrevDecl, bool IsScoped,
2970 bool IsScopedUsingClassTag, bool IsFixed) {
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002971 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002972 IsScoped, IsScopedUsingClassTag, IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002973 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00002974 C.getTypeDeclType(Enum, PrevDecl);
2975 return Enum;
2976}
2977
Douglas Gregor72172e92012-01-05 21:55:30 +00002978EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2979 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002980 EnumDecl *Enum = new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(),
2981 0, 0, false, false, false);
2982 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
2983 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00002984}
2985
Douglas Gregord5058122010-02-11 01:19:42 +00002986void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00002987 QualType NewPromotionType,
2988 unsigned NumPositiveBits,
2989 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00002990 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00002991 if (!IntegerType)
2992 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00002993 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00002994 setNumPositiveBits(NumPositiveBits);
2995 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00002996 TagDecl::completeDefinition();
2997}
2998
Richard Smith7d137e32012-03-23 03:33:32 +00002999TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3000 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3001 return MSI->getTemplateSpecializationKind();
3002
3003 return TSK_Undeclared;
3004}
3005
3006void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3007 SourceLocation PointOfInstantiation) {
3008 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3009 assert(MSI && "Not an instantiated member enumeration?");
3010 MSI->setTemplateSpecializationKind(TSK);
3011 if (TSK != TSK_ExplicitSpecialization &&
3012 PointOfInstantiation.isValid() &&
3013 MSI->getPointOfInstantiation().isInvalid())
3014 MSI->setPointOfInstantiation(PointOfInstantiation);
3015}
3016
Richard Smith4b38ded2012-03-14 23:13:10 +00003017EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3018 if (SpecializationInfo)
3019 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3020
3021 return 0;
3022}
3023
3024void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3025 TemplateSpecializationKind TSK) {
3026 assert(!SpecializationInfo && "Member enum is already a specialization");
3027 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3028}
3029
Sebastian Redl833ef452010-01-26 22:01:41 +00003030//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003031// RecordDecl Implementation
3032//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003033
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003034RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
3035 SourceLocation StartLoc, SourceLocation IdLoc,
3036 IdentifierInfo *Id, RecordDecl *PrevDecl)
3037 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003038 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003039 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003040 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00003041 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003042 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00003043 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003044}
3045
Jay Foad39c79802011-01-12 09:06:06 +00003046RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003047 SourceLocation StartLoc, SourceLocation IdLoc,
3048 IdentifierInfo *Id, RecordDecl* PrevDecl) {
3049 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
3050 PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003051 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3052
Ted Kremenek21475702008-09-05 17:16:31 +00003053 C.getTypeDeclType(R, PrevDecl);
3054 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003055}
3056
Douglas Gregor72172e92012-01-05 21:55:30 +00003057RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
3058 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003059 RecordDecl *R = new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
3060 SourceLocation(), 0, 0);
3061 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3062 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003063}
3064
Douglas Gregordfcad112009-03-25 15:59:44 +00003065bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003066 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003067 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3068}
3069
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003070RecordDecl::field_iterator RecordDecl::field_begin() const {
3071 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3072 LoadFieldsFromExternalStorage();
3073
3074 return field_iterator(decl_iterator(FirstDecl));
3075}
3076
Douglas Gregorb11aad82011-02-19 18:51:44 +00003077/// completeDefinition - Notes that the definition of this type is now
3078/// complete.
3079void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003080 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003081 TagDecl::completeDefinition();
3082}
3083
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003084/// isMsStruct - Get whether or not this record uses ms_struct layout.
3085/// This which can be turned on with an attribute, pragma, or the
3086/// -mms-bitfields command-line option.
3087bool RecordDecl::isMsStruct(const ASTContext &C) const {
3088 return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3089}
3090
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003091static bool isFieldOrIndirectField(Decl::Kind K) {
3092 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3093}
3094
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003095void RecordDecl::LoadFieldsFromExternalStorage() const {
3096 ExternalASTSource *Source = getASTContext().getExternalSource();
3097 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3098
3099 // Notify that we have a RecordDecl doing some initialization.
3100 ExternalASTSource::Deserializing TheFields(Source);
3101
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003102 SmallVector<Decl*, 64> Decls;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003103 LoadedFieldsFromExternalStorage = true;
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003104 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3105 Decls)) {
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003106 case ELR_Success:
3107 break;
3108
3109 case ELR_AlreadyLoaded:
3110 case ELR_Failure:
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003111 return;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003112 }
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003113
3114#ifndef NDEBUG
3115 // Check that all decls we got were FieldDecls.
3116 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003117 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003118#endif
3119
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003120 if (Decls.empty())
3121 return;
3122
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003123 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
3124 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003125}
3126
Steve Naroff415d3d52008-10-08 17:01:13 +00003127//===----------------------------------------------------------------------===//
3128// BlockDecl Implementation
3129//===----------------------------------------------------------------------===//
3130
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003131void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Steve Naroffc4b30e52009-03-13 16:56:44 +00003132 assert(ParamInfo == 0 && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00003133
Steve Naroffc4b30e52009-03-13 16:56:44 +00003134 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003135 if (!NewParamInfo.empty()) {
3136 NumParams = NewParamInfo.size();
3137 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3138 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003139 }
3140}
3141
John McCall351762c2011-02-07 10:33:21 +00003142void BlockDecl::setCaptures(ASTContext &Context,
3143 const Capture *begin,
3144 const Capture *end,
3145 bool capturesCXXThis) {
John McCallc63de662011-02-02 13:00:07 +00003146 CapturesCXXThis = capturesCXXThis;
3147
3148 if (begin == end) {
John McCall351762c2011-02-07 10:33:21 +00003149 NumCaptures = 0;
3150 Captures = 0;
John McCallc63de662011-02-02 13:00:07 +00003151 return;
3152 }
3153
John McCall351762c2011-02-07 10:33:21 +00003154 NumCaptures = end - begin;
3155
3156 // Avoid new Capture[] because we don't want to provide a default
3157 // constructor.
3158 size_t allocationSize = NumCaptures * sizeof(Capture);
3159 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3160 memcpy(buffer, begin, allocationSize);
3161 Captures = static_cast<Capture*>(buffer);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003162}
Sebastian Redl833ef452010-01-26 22:01:41 +00003163
John McCallce45f882011-06-15 22:51:16 +00003164bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3165 for (capture_const_iterator
3166 i = capture_begin(), e = capture_end(); i != e; ++i)
3167 // Only auto vars can be captured, so no redeclaration worries.
3168 if (i->getVariable() == variable)
3169 return true;
3170
3171 return false;
3172}
3173
Douglas Gregor70226da2010-12-21 16:27:07 +00003174SourceRange BlockDecl::getSourceRange() const {
3175 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3176}
Sebastian Redl833ef452010-01-26 22:01:41 +00003177
3178//===----------------------------------------------------------------------===//
3179// Other Decl Allocation/Deallocation Method Implementations
3180//===----------------------------------------------------------------------===//
3181
David Blaikie68e081d2011-12-20 02:48:34 +00003182void TranslationUnitDecl::anchor() { }
3183
Sebastian Redl833ef452010-01-26 22:01:41 +00003184TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
3185 return new (C) TranslationUnitDecl(C);
3186}
3187
David Blaikie68e081d2011-12-20 02:48:34 +00003188void LabelDecl::anchor() { }
3189
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003190LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003191 SourceLocation IdentL, IdentifierInfo *II) {
3192 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
3193}
3194
3195LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3196 SourceLocation IdentL, IdentifierInfo *II,
3197 SourceLocation GnuLabelL) {
3198 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
3199 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003200}
3201
Douglas Gregor72172e92012-01-05 21:55:30 +00003202LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3203 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
3204 return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00003205}
3206
David Blaikie68e081d2011-12-20 02:48:34 +00003207void ValueDecl::anchor() { }
3208
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003209bool ValueDecl::isWeak() const {
3210 for (attr_iterator I = attr_begin(), E = attr_end(); I != E; ++I)
3211 if (isa<WeakAttr>(*I) || isa<WeakRefAttr>(*I))
3212 return true;
3213
3214 return isWeakImported();
3215}
3216
David Blaikie68e081d2011-12-20 02:48:34 +00003217void ImplicitParamDecl::anchor() { }
3218
Sebastian Redl833ef452010-01-26 22:01:41 +00003219ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003220 SourceLocation IdLoc,
3221 IdentifierInfo *Id,
3222 QualType Type) {
3223 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00003224}
3225
Douglas Gregor72172e92012-01-05 21:55:30 +00003226ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
3227 unsigned ID) {
3228 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
3229 return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
3230}
3231
Sebastian Redl833ef452010-01-26 22:01:41 +00003232FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003233 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003234 const DeclarationNameInfo &NameInfo,
3235 QualType T, TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003236 StorageClass SC, StorageClass SCAsWritten,
Douglas Gregorff76cb92010-12-09 16:59:22 +00003237 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00003238 bool hasWrittenPrototype,
3239 bool isConstexprSpecified) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003240 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
3241 T, TInfo, SC, SCAsWritten,
Richard Smitha77a0a62011-08-15 21:04:07 +00003242 isInlineSpecified,
3243 isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00003244 New->HasWrittenPrototype = hasWrittenPrototype;
3245 return New;
3246}
3247
Douglas Gregor72172e92012-01-05 21:55:30 +00003248FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3249 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
3250 return new (Mem) FunctionDecl(Function, 0, SourceLocation(),
3251 DeclarationNameInfo(), QualType(), 0,
3252 SC_None, SC_None, false, false);
3253}
3254
Sebastian Redl833ef452010-01-26 22:01:41 +00003255BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3256 return new (C) BlockDecl(DC, L);
3257}
3258
Douglas Gregor72172e92012-01-05 21:55:30 +00003259BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3260 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
3261 return new (Mem) BlockDecl(0, SourceLocation());
3262}
3263
Sebastian Redl833ef452010-01-26 22:01:41 +00003264EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3265 SourceLocation L,
3266 IdentifierInfo *Id, QualType T,
3267 Expr *E, const llvm::APSInt &V) {
3268 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
3269}
3270
Douglas Gregor72172e92012-01-05 21:55:30 +00003271EnumConstantDecl *
3272EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3273 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
3274 return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
3275 llvm::APSInt());
3276}
3277
David Blaikie68e081d2011-12-20 02:48:34 +00003278void IndirectFieldDecl::anchor() { }
3279
Benjamin Kramer39593702010-11-21 14:11:41 +00003280IndirectFieldDecl *
3281IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3282 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3283 unsigned CHS) {
Francois Pichet783dd6e2010-11-21 06:08:52 +00003284 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
3285}
3286
Douglas Gregor72172e92012-01-05 21:55:30 +00003287IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3288 unsigned ID) {
3289 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
3290 return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
3291 QualType(), 0, 0);
3292}
3293
Douglas Gregorbe996932010-09-01 20:41:53 +00003294SourceRange EnumConstantDecl::getSourceRange() const {
3295 SourceLocation End = getLocation();
3296 if (Init)
3297 End = Init->getLocEnd();
3298 return SourceRange(getLocation(), End);
3299}
3300
David Blaikie68e081d2011-12-20 02:48:34 +00003301void TypeDecl::anchor() { }
3302
Sebastian Redl833ef452010-01-26 22:01:41 +00003303TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003304 SourceLocation StartLoc, SourceLocation IdLoc,
3305 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
3306 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00003307}
3308
David Blaikie68e081d2011-12-20 02:48:34 +00003309void TypedefNameDecl::anchor() { }
3310
Douglas Gregor72172e92012-01-05 21:55:30 +00003311TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3312 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
3313 return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3314}
3315
Richard Smithdda56e42011-04-15 14:24:37 +00003316TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3317 SourceLocation StartLoc,
3318 SourceLocation IdLoc, IdentifierInfo *Id,
3319 TypeSourceInfo *TInfo) {
3320 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
3321}
3322
Douglas Gregor72172e92012-01-05 21:55:30 +00003323TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3324 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
3325 return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3326}
3327
Abramo Bagnaraea947882011-03-08 16:41:52 +00003328SourceRange TypedefDecl::getSourceRange() const {
3329 SourceLocation RangeEnd = getLocation();
3330 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3331 if (typeIsPostfix(TInfo->getType()))
3332 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3333 }
3334 return SourceRange(getLocStart(), RangeEnd);
3335}
3336
Richard Smithdda56e42011-04-15 14:24:37 +00003337SourceRange TypeAliasDecl::getSourceRange() const {
3338 SourceLocation RangeEnd = getLocStart();
3339 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3340 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3341 return SourceRange(getLocStart(), RangeEnd);
3342}
3343
David Blaikie68e081d2011-12-20 02:48:34 +00003344void FileScopeAsmDecl::anchor() { }
3345
Sebastian Redl833ef452010-01-26 22:01:41 +00003346FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00003347 StringLiteral *Str,
3348 SourceLocation AsmLoc,
3349 SourceLocation RParenLoc) {
3350 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00003351}
Douglas Gregorba345522011-12-02 23:23:56 +00003352
Douglas Gregor72172e92012-01-05 21:55:30 +00003353FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
3354 unsigned ID) {
3355 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
3356 return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
3357}
3358
Michael Han84324352013-02-22 17:15:32 +00003359void EmptyDecl::anchor() {}
3360
3361EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3362 return new (C) EmptyDecl(DC, L);
3363}
3364
3365EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3366 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EmptyDecl));
3367 return new (Mem) EmptyDecl(0, SourceLocation());
3368}
3369
Douglas Gregorba345522011-12-02 23:23:56 +00003370//===----------------------------------------------------------------------===//
3371// ImportDecl Implementation
3372//===----------------------------------------------------------------------===//
3373
3374/// \brief Retrieve the number of module identifiers needed to name the given
3375/// module.
3376static unsigned getNumModuleIdentifiers(Module *Mod) {
3377 unsigned Result = 1;
3378 while (Mod->Parent) {
3379 Mod = Mod->Parent;
3380 ++Result;
3381 }
3382 return Result;
3383}
3384
Douglas Gregor22d09742012-01-03 18:04:46 +00003385ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003386 Module *Imported,
3387 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00003388 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003389 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003390{
3391 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3392 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3393 memcpy(StoredLocs, IdentifierLocs.data(),
3394 IdentifierLocs.size() * sizeof(SourceLocation));
3395}
3396
Douglas Gregor22d09742012-01-03 18:04:46 +00003397ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003398 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00003399 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003400 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003401{
3402 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3403}
3404
3405ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003406 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00003407 ArrayRef<SourceLocation> IdentifierLocs) {
3408 void *Mem = C.Allocate(sizeof(ImportDecl) +
3409 IdentifierLocs.size() * sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00003410 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00003411}
3412
3413ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003414 SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003415 Module *Imported,
3416 SourceLocation EndLoc) {
3417 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00003418 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00003419 Import->setImplicit();
3420 return Import;
3421}
3422
Douglas Gregor72172e92012-01-05 21:55:30 +00003423ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3424 unsigned NumLocations) {
3425 void *Mem = AllocateDeserializedDecl(C, ID,
3426 (sizeof(ImportDecl) +
3427 NumLocations * sizeof(SourceLocation)));
Douglas Gregorba345522011-12-02 23:23:56 +00003428 return new (Mem) ImportDecl(EmptyShell());
3429}
3430
3431ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3432 if (!ImportedAndComplete.getInt())
3433 return ArrayRef<SourceLocation>();
3434
3435 const SourceLocation *StoredLocs
3436 = reinterpret_cast<const SourceLocation *>(this + 1);
3437 return ArrayRef<SourceLocation>(StoredLocs,
3438 getNumModuleIdentifiers(getImportedModule()));
3439}
3440
3441SourceRange ImportDecl::getSourceRange() const {
3442 if (!ImportedAndComplete.getInt())
3443 return SourceRange(getLocation(),
3444 *reinterpret_cast<const SourceLocation *>(this + 1));
3445
3446 return SourceRange(getLocation(), getIdentifierLocs().back());
3447}