blob: e29c5e3c9b0fdf41d226e682f3ee5d0cc696ccf4 [file] [log] [blame]
Chris Lattnera11999d2006-10-15 22:34:45 +00001//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera11999d2006-10-15 22:34:45 +00007//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidis63018842008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Chris Lattnera11999d2006-10-15 22:34:45 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
Chris Lattnera7b32872008-03-15 06:12:44 +000015#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000021#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000023#include "clang/AST/PrettyPrinter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000024#include "clang/AST/Stmt.h"
25#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000027#include "clang/Basic/IdentifierTable.h"
Douglas Gregorba345522011-12-02 23:23:56 +000028#include "clang/Basic/Module.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000029#include "clang/Basic/Specifiers.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000030#include "clang/Basic/TargetInfo.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000031#include "llvm/Support/ErrorHandling.h"
David Blaikie9c70e042011-09-21 18:16:56 +000032#include <algorithm>
33
Chris Lattner6d9a6852006-10-25 05:11:20 +000034using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000035
Chris Lattner88f70d62008-03-15 05:43:15 +000036//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000037// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000038//===----------------------------------------------------------------------===//
39
John McCalldf25c432013-02-16 00:17:33 +000040// Visibility rules aren't rigorously externally specified, but here
41// are the basic principles behind what we implement:
42//
43// 1. An explicit visibility attribute is generally a direct expression
44// of the user's intent and should be honored. Only the innermost
45// visibility attribute applies. If no visibility attribute applies,
46// global visibility settings are considered.
47//
48// 2. There is one caveat to the above: on or in a template pattern,
49// an explicit visibility attribute is just a default rule, and
50// visibility can be decreased by the visibility of template
51// arguments. But this, too, has an exception: an attribute on an
52// explicit specialization or instantiation causes all the visibility
53// restrictions of the template arguments to be ignored.
54//
55// 3. A variable that does not otherwise have explicit visibility can
56// be restricted by the visibility of its type.
57//
58// 4. A visibility restriction is explicit if it comes from an
59// attribute (or something like it), not a global visibility setting.
60// When emitting a reference to an external symbol, visibility
61// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +000062//
63// 5. When computing the visibility of a non-type, including a
64// non-type member of a class, only non-type visibility restrictions
65// are considered: the 'visibility' attribute, global value-visibility
66// settings, and a few special cases like __private_extern.
67//
68// 6. When computing the visibility of a type, including a type member
69// of a class, only type visibility restrictions are considered:
70// the 'type_visibility' attribute and global type-visibility settings.
71// However, a 'visibility' attribute counts as a 'type_visibility'
72// attribute on any declaration that only has the former.
73//
74// The visibility of a "secondary" entity, like a template argument,
75// is computed using the kind of that entity, not the kind of the
76// primary entity for which we are computing visibility. For example,
77// the visibility of a specialization of either of these templates:
78// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
79// template <class T, bool (&compare)(T, X)> class matcher;
80// is restricted according to the type visibility of the argument 'T',
81// the type visibility of 'bool(&)(T,X)', and the value visibility of
82// the argument function 'compare'. That 'has_match' is a value
83// and 'matcher' is a type only matters when looking for attributes
84// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +000085
86/// Kinds of LV computation. The linkage side of the computation is
87/// always the same, but different things can change how visibility is
88/// computed.
89enum LVComputationKind {
John McCalldf25c432013-02-16 00:17:33 +000090 /// Do a normal LV computation for, ultimately, a type.
John McCalld041a9b2013-02-20 01:54:26 +000091 LVForType = NamedDecl::VisibilityForType,
John McCalldf25c432013-02-16 00:17:33 +000092
John McCalld041a9b2013-02-20 01:54:26 +000093 /// Do a normal LV computation for, ultimately, a non-type declaration.
94 LVForValue = NamedDecl::VisibilityForValue,
95
96 /// Do a normal LV computation for, ultimately, a type that already
97 /// has some sort of explicit visibility.
98 LVForExplicitType,
99
100 /// Do a normal LV computation for, ultimately, a non-type declaration
101 /// that already has some sort of explicit visibility.
102 LVForExplicitValue
John McCalldf25c432013-02-16 00:17:33 +0000103};
104
John McCalld041a9b2013-02-20 01:54:26 +0000105/// Does this computation kind permit us to consider additional
106/// visibility settings from attributes and the like?
107static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
108 return ((unsigned(computation) & 2) != 0);
109}
110
111/// Given an LVComputationKind, return one of the same type/value sort
112/// that records that it already has explicit visibility.
113static LVComputationKind
114withExplicitVisibilityAlready(LVComputationKind oldKind) {
115 LVComputationKind newKind =
116 static_cast<LVComputationKind>(unsigned(oldKind) | 2);
117 assert(oldKind != LVForType || newKind == LVForExplicitType);
118 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
119 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
120 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
121 return newKind;
122}
123
124static llvm::Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
125 LVComputationKind kind) {
126 assert(!hasExplicitVisibilityAlready(kind) &&
127 "asking for explicit visibility when we shouldn't be");
128 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
129}
130
John McCalldf25c432013-02-16 00:17:33 +0000131typedef NamedDecl::LinkageInfo LinkageInfo;
132
133/// Is the given declaration a "type" or a "value" for the purposes of
134/// visibility computation?
135static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000136 return isa<TypeDecl>(D) ||
137 isa<ClassTemplateDecl>(D) ||
138 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000139}
140
John McCalld041a9b2013-02-20 01:54:26 +0000141/// Given a visibility attribute, return the explicit visibility
142/// associated with it.
143template <class T>
144static Visibility getVisibilityFromAttr(const T *attr) {
145 switch (attr->getVisibility()) {
146 case T::Default:
147 return DefaultVisibility;
148 case T::Hidden:
149 return HiddenVisibility;
150 case T::Protected:
151 return ProtectedVisibility;
152 }
153 llvm_unreachable("bad visibility kind");
154}
155
John McCalldf25c432013-02-16 00:17:33 +0000156/// Return the explicit visibility of the given declaration.
John McCalld041a9b2013-02-20 01:54:26 +0000157static llvm::Optional<Visibility> getVisibilityOf(const NamedDecl *D,
158 NamedDecl::ExplicitVisibilityKind kind) {
159 // If we're ultimately computing the visibility of a type, look for
160 // a 'type_visibility' attribute before looking for 'visibility'.
161 if (kind == NamedDecl::VisibilityForType) {
162 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
163 return getVisibilityFromAttr(A);
164 }
165 }
166
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000167 // If this declaration has an explicit visibility attribute, use it.
168 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000169 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000170 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000171
172 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
173 // implies visibility(default).
Douglas Gregore8bbc122011-09-02 00:18:52 +0000174 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000175 for (specific_attr_iterator<AvailabilityAttr>
176 A = D->specific_attr_begin<AvailabilityAttr>(),
177 AEnd = D->specific_attr_end<AvailabilityAttr>();
178 A != AEnd; ++A)
179 if ((*A)->getPlatform()->getName().equals("macosx"))
180 return DefaultVisibility;
181 }
182
183 return llvm::Optional<Visibility>();
John McCall457a04e2010-10-22 21:05:15 +0000184}
185
Rafael Espindola2f869a32012-01-14 00:30:36 +0000186static LinkageInfo getLVForType(QualType T) {
187 std::pair<Linkage,Visibility> P = T->getLinkageAndVisibility();
188 return LinkageInfo(P.first, P.second, T->isVisibilityExplicit());
189}
190
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000191/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000192/// template parameter list. For visibility purposes, template
193/// parameters are part of the signature of a template.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000194static LinkageInfo
John McCalldf25c432013-02-16 00:17:33 +0000195getLVForTemplateParameterList(const TemplateParameterList *params) {
196 LinkageInfo LV;
197 for (TemplateParameterList::const_iterator P = params->begin(),
198 PEnd = params->end();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000199 P != PEnd; ++P) {
John McCalldf25c432013-02-16 00:17:33 +0000200
201 // Template type parameters are the most common and never
202 // contribute to visibility, pack or not.
203 if (isa<TemplateTypeParmDecl>(*P))
204 continue;
205
206 // Non-type template parameters can be restricted by the value type, e.g.
207 // template <enum X> class A { ... };
208 // We have to be careful here, though, because we can be dealing with
209 // dependent types.
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000210 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
John McCalldf25c432013-02-16 00:17:33 +0000211 // Handle the non-pack case first.
212 if (!NTTP->isExpandedParameterPack()) {
213 if (!NTTP->getType()->isDependentType()) {
214 LV.merge(getLVForType(NTTP->getType()));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000215 }
216 continue;
217 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000218
John McCalldf25c432013-02-16 00:17:33 +0000219 // Look at all the types in an expanded pack.
220 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
221 QualType type = NTTP->getExpansionType(i);
222 if (!type->isDependentType())
223 LV.merge(getLVForType(type));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000224 }
John McCalldf25c432013-02-16 00:17:33 +0000225 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000226 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000227
John McCalldf25c432013-02-16 00:17:33 +0000228 // Template template parameters can be restricted by their
229 // template parameters, recursively.
230 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
231
232 // Handle the non-pack case first.
233 if (!TTP->isExpandedParameterPack()) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000234 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters()));
John McCalldf25c432013-02-16 00:17:33 +0000235 continue;
236 }
237
238 // Look at all expansions in an expanded pack.
239 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
240 i != n; ++i) {
241 LV.merge(getLVForTemplateParameterList(
242 TTP->getExpansionTemplateParameters(i)));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000243 }
244 }
245
John McCall457a04e2010-10-22 21:05:15 +0000246 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000247}
248
Rafael Espindola19de5612013-01-12 06:42:30 +0000249/// getLVForDecl - Get the linkage and visibility for the given declaration.
John McCalldf25c432013-02-16 00:17:33 +0000250static LinkageInfo getLVForDecl(const NamedDecl *D,
251 LVComputationKind computation);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000252
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000253/// \brief Get the most restrictive linkage for the types and
254/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000255///
256/// Note that we don't take an LVComputationKind because we always
257/// want to honor the visibility of template arguments in the same way.
258static LinkageInfo
259getLVForTemplateArgumentList(ArrayRef<TemplateArgument> args) {
260 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000261
John McCalldf25c432013-02-16 00:17:33 +0000262 for (unsigned i = 0, e = args.size(); i != e; ++i) {
263 const TemplateArgument &arg = args[i];
264 switch (arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000265 case TemplateArgument::Null:
266 case TemplateArgument::Integral:
267 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000268 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000269
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000270 case TemplateArgument::Type:
John McCalldf25c432013-02-16 00:17:33 +0000271 LV.merge(getLVForType(arg.getAsType()));
272 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000273
274 case TemplateArgument::Declaration:
John McCalldf25c432013-02-16 00:17:33 +0000275 if (NamedDecl *ND = dyn_cast<NamedDecl>(arg.getAsDecl())) {
276 assert(!usesTypeVisibility(ND));
277 LV.merge(getLVForDecl(ND, LVForValue));
278 }
279 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +0000280
281 case TemplateArgument::NullPtr:
John McCalldf25c432013-02-16 00:17:33 +0000282 LV.merge(getLVForType(arg.getNullPtrType()));
283 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000284
285 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000286 case TemplateArgument::TemplateExpansion:
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000287 if (TemplateDecl *Template
John McCalldf25c432013-02-16 00:17:33 +0000288 = arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
289 LV.merge(getLVForDecl(Template, LVForValue));
290 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000291
292 case TemplateArgument::Pack:
John McCalldf25c432013-02-16 00:17:33 +0000293 LV.merge(getLVForTemplateArgumentList(arg.getPackAsArray()));
294 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000295 }
John McCalldf25c432013-02-16 00:17:33 +0000296 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000297 }
298
John McCall457a04e2010-10-22 21:05:15 +0000299 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000300}
301
Rafael Espindola2f869a32012-01-14 00:30:36 +0000302static LinkageInfo
John McCalldf25c432013-02-16 00:17:33 +0000303getLVForTemplateArgumentList(const TemplateArgumentList &TArgs) {
304 return getLVForTemplateArgumentList(TArgs.asArray());
John McCall8823c652010-08-13 08:35:10 +0000305}
306
John McCalldf25c432013-02-16 00:17:33 +0000307/// Merge in template-related linkage and visibility for the given
308/// function template specialization.
309///
310/// We don't need a computation kind here because we can assume
311/// LVForValue.
312static void mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
313 const FunctionTemplateSpecializationInfo *specInfo) {
314 bool hasExplicitVisibility = fn->hasAttr<VisibilityAttr>();
315 FunctionTemplateDecl *temp = specInfo->getTemplate();
316
317 // Include visibility from the template parameters and arguments
318 // only if this is not an explicit instantiation or specialization
319 // with direct explicit visibility. (Implicit instantiations won't
320 // have a direct attribute.)
321 bool considerVisibility = !hasExplicitVisibility;
322
323 // Merge information from the template parameters.
324 LinkageInfo tempLV =
325 getLVForTemplateParameterList(temp->getTemplateParameters());
326 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
327
328 // Merge information from the template arguments.
329 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
330 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
331 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000332}
333
John McCalld041a9b2013-02-20 01:54:26 +0000334/// Should we consider visibility associated with the template
335/// arguments and parameters of the given class template specialization?
336static bool shouldConsiderTemplateVisibility(
337 const ClassTemplateSpecializationDecl *spec,
338 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000339 // Include visibility from the template parameters and arguments
340 // only if this is not an explicit instantiation or specialization
341 // with direct explicit visibility (and note that implicit
342 // instantiations won't have a direct attribute).
343 //
344 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000345 // for an explicit specialization when computing the visibility of a
346 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000347 //
348 // This is a bit complex; let's unpack it.
349 //
350 // An explicit class specialization is an independent, top-level
351 // declaration. As such, if it or any of its members has an
352 // explicit visibility attribute, that must directly express the
353 // user's intent, and we should honor it. The same logic applies to
354 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000355
356 // Fast path: if this is not an explicit instantiation or
357 // specialization, we always want to consider template-related
358 // visibility restrictions.
359 if (!spec->isExplicitInstantiationOrSpecialization())
360 return true;
361
362 // This is the 'member thereof' check.
363 if (spec->isExplicitSpecialization() &&
364 hasExplicitVisibilityAlready(computation))
365 return false;
366
367 // Otherwise, look to see if we have an attribute.
368 switch (computation) {
369 case LVForType:
370 case LVForExplicitType:
371 if (spec->hasAttr<TypeVisibilityAttr>())
372 return false;
373 // fallthrough
374 case LVForValue:
375 case LVForExplicitValue:
376 if (spec->hasAttr<VisibilityAttr>())
377 return false;
378 return true;
379 }
380 llvm_unreachable("bad visibility computation kind");
381}
382
383/// Merge in template-related linkage and visibility for the given
384/// class template specialization.
385static void mergeTemplateLV(LinkageInfo &LV,
386 const ClassTemplateSpecializationDecl *spec,
387 LVComputationKind computation) {
388 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000389
390 // Merge information from the template parameters, but ignore
391 // visibility if we're only considering template arguments.
392
John McCalld041a9b2013-02-20 01:54:26 +0000393 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000394 LinkageInfo tempLV =
395 getLVForTemplateParameterList(temp->getTemplateParameters());
396 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000397 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000398
399 // Merge information from the template arguments. We ignore
400 // template-argument visibility if we've got an explicit
401 // instantiation with a visibility attribute.
402 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
403 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
404 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000405}
406
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000407static bool useInlineVisibilityHidden(const NamedDecl *D) {
408 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000409 const LangOptions &Opts = D->getASTContext().getLangOpts();
410 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000411 return false;
412
413 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
414 if (!FD)
415 return false;
416
417 TemplateSpecializationKind TSK = TSK_Undeclared;
418 if (FunctionTemplateSpecializationInfo *spec
419 = FD->getTemplateSpecializationInfo()) {
420 TSK = spec->getTemplateSpecializationKind();
421 } else if (MemberSpecializationInfo *MSI =
422 FD->getMemberSpecializationInfo()) {
423 TSK = MSI->getTemplateSpecializationKind();
424 }
425
426 const FunctionDecl *Def = 0;
427 // InlineVisibilityHidden only applies to definitions, and
428 // isInlined() only gives meaningful answers on definitions
429 // anyway.
430 return TSK != TSK_ExplicitInstantiationDeclaration &&
431 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000432 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000433}
434
Benjamin Kramer3e350262013-02-15 12:30:38 +0000435template <typename T> static bool isInExternCContext(T *D) {
Rafael Espindolaf4187652013-02-14 01:18:37 +0000436 const T *First = D->getFirstDeclaration();
437 return First->getDeclContext()->isExternCContext();
438}
439
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000440static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
John McCalldf25c432013-02-16 00:17:33 +0000441 LVComputationKind computation) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000442 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000443 "Not a name having namespace scope");
444 ASTContext &Context = D->getASTContext();
445
446 // C++ [basic.link]p3:
447 // A name having namespace scope (3.3.6) has internal linkage if it
448 // is the name of
449 // - an object, reference, function or function template that is
450 // explicitly declared static; or,
451 // (This bullet corresponds to C99 6.2.2p3.)
452 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
453 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000454 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000455 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000456
Richard Smithdc0ef452012-10-19 06:37:48 +0000457 // - a non-volatile object or reference that is explicitly declared const
458 // or constexpr and neither explicitly declared extern nor previously
459 // declared to have external linkage; or (there is no equivalent in C99)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000460 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000461 Var->getType().isConstQualified() &&
462 !Var->getType().isVolatileQualified() &&
John McCall8e7d6562010-08-26 03:08:43 +0000463 Var->getStorageClass() != SC_Extern &&
464 Var->getStorageClass() != SC_PrivateExtern) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000465 bool FoundExtern = false;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000466 for (const VarDecl *PrevVar = Var->getPreviousDecl();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000467 PrevVar && !FoundExtern;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000468 PrevVar = PrevVar->getPreviousDecl())
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000469 if (isExternalLinkage(PrevVar->getLinkage()))
Douglas Gregorf73b2822009-11-25 22:24:25 +0000470 FoundExtern = true;
471
472 if (!FoundExtern)
John McCallc273f242010-10-30 11:50:40 +0000473 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000474 }
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000475 if (Var->getStorageClass() == SC_None) {
Douglas Gregorec9fd132012-01-14 16:38:05 +0000476 const VarDecl *PrevVar = Var->getPreviousDecl();
477 for (; PrevVar; PrevVar = PrevVar->getPreviousDecl())
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000478 if (PrevVar->getStorageClass() == SC_PrivateExtern)
479 break;
Eli Friedmana7137bc2012-10-26 23:05:34 +0000480 if (PrevVar)
481 return PrevVar->getLinkageAndVisibility();
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000482 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000483 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000484 // C++ [temp]p4:
485 // A non-member function template can have internal linkage; any
486 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000487 const FunctionDecl *Function = 0;
488 if (const FunctionTemplateDecl *FunTmpl
489 = dyn_cast<FunctionTemplateDecl>(D))
490 Function = FunTmpl->getTemplatedDecl();
491 else
492 Function = cast<FunctionDecl>(D);
493
494 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000495 if (Function->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000496 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000497 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
498 // - a data member of an anonymous union.
499 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
John McCallc273f242010-10-30 11:50:40 +0000500 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000501 }
502
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000503 if (D->isInAnonymousNamespace()) {
504 const VarDecl *Var = dyn_cast<VarDecl>(D);
505 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
Rafael Espindolaf4187652013-02-14 01:18:37 +0000506 if ((!Var || !isInExternCContext(Var)) &&
507 (!Func || !isInExternCContext(Func)))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000508 return LinkageInfo::uniqueExternal();
509 }
John McCallb7139c42010-10-28 04:18:25 +0000510
John McCall457a04e2010-10-22 21:05:15 +0000511 // Set up the defaults.
512
513 // C99 6.2.2p5:
514 // If the declaration of an identifier for an object has file
515 // scope and no storage-class specifier, its linkage is
516 // external.
John McCallc273f242010-10-30 11:50:40 +0000517 LinkageInfo LV;
518
John McCalld041a9b2013-02-20 01:54:26 +0000519 if (!hasExplicitVisibilityAlready(computation)) {
520 if (llvm::Optional<Visibility> Vis
521 = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000522 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000523 } else {
524 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000525 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000526 for (const DeclContext *DC = D->getDeclContext();
527 !isa<TranslationUnitDecl>(DC);
528 DC = DC->getParent()) {
529 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
530 if (!ND) continue;
John McCalld041a9b2013-02-20 01:54:26 +0000531 if (llvm::Optional<Visibility> Vis
532 = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000533 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000534 break;
535 }
536 }
537 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000538
John McCalldf25c432013-02-16 00:17:33 +0000539 // Add in global settings if the above didn't give us direct visibility.
540 if (!LV.visibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000541 // Use global type/value visibility as appropriate.
542 Visibility globalVisibility;
543 if (computation == LVForValue) {
544 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
545 } else {
546 assert(computation == LVForType);
547 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
548 }
549 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000550
551 // If we're paying attention to global visibility, apply
552 // -finline-visibility-hidden if this is an inline method.
553 if (useInlineVisibilityHidden(D))
554 LV.mergeVisibility(HiddenVisibility, true);
555 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000556 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000557
Douglas Gregorf73b2822009-11-25 22:24:25 +0000558 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000559
Douglas Gregorf73b2822009-11-25 22:24:25 +0000560 // A name having namespace scope has external linkage if it is the
561 // name of
562 //
563 // - an object or reference, unless it has internal linkage; or
564 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000565 // GCC applies the following optimization to variables and static
566 // data members, but not to functions:
567 //
John McCall457a04e2010-10-22 21:05:15 +0000568 // Modify the variable's LV by the LV of its type unless this is
569 // C or extern "C". This follows from [basic.link]p9:
570 // A type without linkage shall not be used as the type of a
571 // variable or function with external linkage unless
572 // - the entity has C language linkage, or
573 // - the entity is declared within an unnamed namespace, or
574 // - the entity is not used or is defined in the same
575 // translation unit.
576 // and [basic.link]p10:
577 // ...the types specified by all declarations referring to a
578 // given variable or function shall be identical...
579 // C does not have an equivalent rule.
580 //
John McCall5fe84122010-10-26 04:59:26 +0000581 // Ignore this if we've got an explicit attribute; the user
582 // probably knows what they're doing.
583 //
John McCall457a04e2010-10-22 21:05:15 +0000584 // Note that we don't want to make the variable non-external
585 // because of this, but unique-external linkage suits us.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000586 if (Context.getLangOpts().CPlusPlus &&
Eli Friedman839192f2012-01-15 01:23:58 +0000587 !Var->getDeclContext()->isExternCContext()) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000588 LinkageInfo TypeLV = getLVForType(Var->getType());
589 if (TypeLV.linkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000590 return LinkageInfo::uniqueExternal();
John McCalldf25c432013-02-16 00:17:33 +0000591 if (!LV.visibilityExplicit())
592 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000593 }
594
John McCall23032652010-11-02 18:38:13 +0000595 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000596 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000597
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000598 // Note that Sema::MergeVarDecl already takes care of implementing
599 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
600 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000601
Douglas Gregorf73b2822009-11-25 22:24:25 +0000602 // - a function, unless it has internal linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000603 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000604 // In theory, we can modify the function's LV by the LV of its
605 // type unless it has C linkage (see comment above about variables
606 // for justification). In practice, GCC doesn't do this, so it's
607 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000608
John McCall23032652010-11-02 18:38:13 +0000609 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000610 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000611
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000612 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
613 // merging storage classes and visibility attributes, so we don't have to
614 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000615
John McCallf768aa72011-02-10 06:50:24 +0000616 // In C++, then if the type of the function uses a type with
617 // unique-external linkage, it's not legally usable from outside
618 // this translation unit. However, we should use the C linkage
619 // rules instead for extern "C" declarations.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000620 if (Context.getLangOpts().CPlusPlus &&
Eli Friedman839192f2012-01-15 01:23:58 +0000621 !Function->getDeclContext()->isExternCContext() &&
John McCallf768aa72011-02-10 06:50:24 +0000622 Function->getType()->getLinkage() == UniqueExternalLinkage)
623 return LinkageInfo::uniqueExternal();
624
John McCallb8c604a2011-06-27 23:06:04 +0000625 // Consider LV from the template and the template arguments unless
626 // this is an explicit specialization with a visibility attribute.
627 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000628 = Function->getTemplateSpecializationInfo()) {
John McCalldf25c432013-02-16 00:17:33 +0000629 mergeTemplateLV(LV, Function, specInfo);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000630 }
631
Douglas Gregorf73b2822009-11-25 22:24:25 +0000632 // - a named class (Clause 9), or an unnamed class defined in a
633 // typedef declaration in which the class has the typedef name
634 // for linkage purposes (7.1.3); or
635 // - a named enumeration (7.2), or an unnamed enumeration
636 // defined in a typedef declaration in which the enumeration
637 // has the typedef name for linkage purposes (7.1.3); or
John McCall457a04e2010-10-22 21:05:15 +0000638 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
639 // Unnamed tags have no linkage.
Richard Smithdda56e42011-04-15 14:24:37 +0000640 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
John McCallc273f242010-10-30 11:50:40 +0000641 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000642
John McCall457a04e2010-10-22 21:05:15 +0000643 // If this is a class template specialization, consider the
644 // linkage of the template and template arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000645 if (const ClassTemplateSpecializationDecl *spec
John McCall457a04e2010-10-22 21:05:15 +0000646 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000647 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000648 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000649
650 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000651 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000652 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000653 computation);
John McCallc273f242010-10-30 11:50:40 +0000654 if (!isExternalLinkage(EnumLV.linkage()))
655 return LinkageInfo::none();
656 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000657
658 // - a template, unless it is a function template that has
659 // internal linkage (Clause 14);
John McCall8bc6d5b2011-03-04 10:39:25 +0000660 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000661 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000662 LinkageInfo tempLV =
663 getLVForTemplateParameterList(temp->getTemplateParameters());
664 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
665
Douglas Gregorf73b2822009-11-25 22:24:25 +0000666 // - a namespace (7.3), unless it is declared within an unnamed
667 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000668 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
669 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000670
John McCall457a04e2010-10-22 21:05:15 +0000671 // By extension, we assign external linkage to Objective-C
672 // interfaces.
673 } else if (isa<ObjCInterfaceDecl>(D)) {
674 // fallout
675
676 // Everything not covered here has no linkage.
677 } else {
John McCallc273f242010-10-30 11:50:40 +0000678 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000679 }
680
681 // If we ended up with non-external linkage, visibility should
682 // always be default.
John McCallc273f242010-10-30 11:50:40 +0000683 if (LV.linkage() != ExternalLinkage)
684 return LinkageInfo(LV.linkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000685
John McCall457a04e2010-10-22 21:05:15 +0000686 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000687}
688
John McCalldf25c432013-02-16 00:17:33 +0000689static LinkageInfo getLVForClassMember(const NamedDecl *D,
690 LVComputationKind computation) {
John McCall457a04e2010-10-22 21:05:15 +0000691 // Only certain class members have linkage. Note that fields don't
692 // really have linkage, but it's convenient to say they do for the
693 // purposes of calculating linkage of pointer-to-data-member
694 // template arguments.
John McCall8823c652010-08-13 08:35:10 +0000695 if (!(isa<CXXMethodDecl>(D) ||
696 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000697 isa<FieldDecl>(D) ||
David Blaikie095deba2012-11-14 01:52:05 +0000698 isa<TagDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000699 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000700
John McCall07072662010-11-02 01:45:15 +0000701 LinkageInfo LV;
702
John McCall07072662010-11-02 01:45:15 +0000703 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000704 if (!hasExplicitVisibilityAlready(computation)) {
705 if (llvm::Optional<Visibility> Vis
706 = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000707 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000708 // If we're paying attention to global visibility, apply
709 // -finline-visibility-hidden if this is an inline method.
710 //
711 // Note that we do this before merging information about
712 // the class visibility.
713 if (!LV.visibilityExplicit() && useInlineVisibilityHidden(D))
714 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000715 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000716
717 // If this class member has an explicit visibility attribute, the only
718 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000719 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000720 LVComputationKind classComputation = computation;
721 if (LV.visibilityExplicit())
722 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000723
Rafael Espindola53cf2192012-04-19 05:50:08 +0000724 // If this member has an visibility attribute, ClassF will exclude
725 // attributes on the class or command line options, keeping only information
726 // about the template instantiation. If the member has no visibility
727 // attributes, mergeWithMin behaves like merge, so in both cases mergeWithMin
728 // produces the desired result.
John McCalldf25c432013-02-16 00:17:33 +0000729 LV.merge(getLVForDecl(cast<RecordDecl>(D->getDeclContext()),
730 classComputation));
John McCall07072662010-11-02 01:45:15 +0000731 if (!isExternalLinkage(LV.linkage()))
John McCallc273f242010-10-30 11:50:40 +0000732 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000733
734 // If the class already has unique-external linkage, we can't improve.
John McCall07072662010-11-02 01:45:15 +0000735 if (LV.linkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000736 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000737
John McCall8823c652010-08-13 08:35:10 +0000738 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000739 // If the type of the function uses a type with unique-external
740 // linkage, it's not legally usable from outside this translation unit.
741 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
742 return LinkageInfo::uniqueExternal();
743
John McCall457a04e2010-10-22 21:05:15 +0000744 // If this is a method template specialization, use the linkage for
745 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000746 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000747 = MD->getTemplateSpecializationInfo()) {
John McCalldf25c432013-02-16 00:17:33 +0000748 mergeTemplateLV(LV, MD, spec);
John McCalle6e622e2010-11-01 01:29:57 +0000749 }
John McCall457a04e2010-10-22 21:05:15 +0000750
John McCall37bb6c92010-10-29 22:22:43 +0000751 // Note that in contrast to basically every other situation, we
752 // *do* apply -fvisibility to method declarations.
753
754 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCallb8c604a2011-06-27 23:06:04 +0000755 if (const ClassTemplateSpecializationDecl *spec
John McCall37bb6c92010-10-29 22:22:43 +0000756 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000757 mergeTemplateLV(LV, spec, computation);
John McCall37bb6c92010-10-29 22:22:43 +0000758 }
759
John McCall37bb6c92010-10-29 22:22:43 +0000760 // Static data members.
761 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCall36cd5cc2010-10-30 09:18:49 +0000762 // Modify the variable's linkage by its type, but ignore the
763 // type's visibility unless it's a definition.
John McCalldf25c432013-02-16 00:17:33 +0000764 LinkageInfo typeLV = getLVForType(VD->getType());
765 if (typeLV.linkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000766 LV.mergeLinkage(UniqueExternalLinkage);
John McCalldf25c432013-02-16 00:17:33 +0000767 if (!LV.visibilityExplicit())
768 LV.mergeVisibility(typeLV);
769
770 // Template members.
771 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
772 bool considerVisibility =
John McCalld041a9b2013-02-20 01:54:26 +0000773 (!LV.visibilityExplicit() &&
774 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000775 LinkageInfo tempLV =
776 getLVForTemplateParameterList(temp->getTemplateParameters());
777 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall37bb6c92010-10-29 22:22:43 +0000778 }
779
John McCall457a04e2010-10-22 21:05:15 +0000780 return LV;
John McCall8823c652010-08-13 08:35:10 +0000781}
782
John McCalld396b972011-02-08 19:01:05 +0000783static void clearLinkageForClass(const CXXRecordDecl *record) {
784 for (CXXRecordDecl::decl_iterator
785 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
786 Decl *child = *i;
787 if (isa<NamedDecl>(child))
Rafael Espindola19de5612013-01-12 06:42:30 +0000788 cast<NamedDecl>(child)->ClearLinkageCache();
John McCalld396b972011-02-08 19:01:05 +0000789 }
790}
791
David Blaikie68e081d2011-12-20 02:48:34 +0000792void NamedDecl::anchor() { }
793
Rafael Espindola19de5612013-01-12 06:42:30 +0000794void NamedDecl::ClearLinkageCache() {
John McCalld396b972011-02-08 19:01:05 +0000795 // Note that we can't skip clearing the linkage of children just
796 // because the parent doesn't have cached linkage: we don't cache
797 // when computing linkage for parent contexts.
798
Rafael Espindola19de5612013-01-12 06:42:30 +0000799 HasCachedLinkage = 0;
John McCalld396b972011-02-08 19:01:05 +0000800
801 // If we're changing the linkage of a class, we need to reset the
802 // linkage of child declarations, too.
803 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
804 clearLinkageForClass(record);
805
Dmitri Gribenkofb04e1b2013-02-03 16:10:26 +0000806 if (ClassTemplateDecl *temp = dyn_cast<ClassTemplateDecl>(this)) {
John McCalld396b972011-02-08 19:01:05 +0000807 // Clear linkage for the template pattern.
808 CXXRecordDecl *record = temp->getTemplatedDecl();
Rafael Espindola19de5612013-01-12 06:42:30 +0000809 record->HasCachedLinkage = 0;
John McCalld396b972011-02-08 19:01:05 +0000810 clearLinkageForClass(record);
811
John McCall83779672011-02-19 02:53:41 +0000812 // We need to clear linkage for specializations, too.
813 for (ClassTemplateDecl::spec_iterator
814 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
Rafael Espindola19de5612013-01-12 06:42:30 +0000815 i->ClearLinkageCache();
John McCalld396b972011-02-08 19:01:05 +0000816 }
John McCall83779672011-02-19 02:53:41 +0000817
818 // Clear cached linkage for function template decls, too.
Dmitri Gribenkofb04e1b2013-02-03 16:10:26 +0000819 if (FunctionTemplateDecl *temp = dyn_cast<FunctionTemplateDecl>(this)) {
Rafael Espindola19de5612013-01-12 06:42:30 +0000820 temp->getTemplatedDecl()->ClearLinkageCache();
John McCall83779672011-02-19 02:53:41 +0000821 for (FunctionTemplateDecl::spec_iterator
822 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
Rafael Espindola19de5612013-01-12 06:42:30 +0000823 i->ClearLinkageCache();
John McCall8f9a4292011-03-22 06:58:49 +0000824 }
John McCall83779672011-02-19 02:53:41 +0000825
John McCalld396b972011-02-08 19:01:05 +0000826}
827
Douglas Gregorbf62d642010-12-06 18:36:25 +0000828Linkage NamedDecl::getLinkage() const {
Richard Smith88581592013-02-12 05:48:23 +0000829 if (HasCachedLinkage)
Rafael Espindola19de5612013-01-12 06:42:30 +0000830 return Linkage(CachedLinkage);
Rafael Espindola19de5612013-01-12 06:42:30 +0000831
John McCalld041a9b2013-02-20 01:54:26 +0000832 // We don't care about visibility here, so ask for the cheapest
833 // possible visibility analysis.
834 CachedLinkage = getLVForDecl(this, LVForExplicitValue).linkage();
Rafael Espindola19de5612013-01-12 06:42:30 +0000835 HasCachedLinkage = 1;
836
837#ifndef NDEBUG
838 verifyLinkage();
839#endif
840
841 return Linkage(CachedLinkage);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000842}
843
John McCallc273f242010-10-30 11:50:40 +0000844LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCalldf25c432013-02-16 00:17:33 +0000845 LVComputationKind computation =
846 (usesTypeVisibility(this) ? LVForType : LVForValue);
847 LinkageInfo LI = getLVForDecl(this, computation);
Rafael Espindola19de5612013-01-12 06:42:30 +0000848 if (HasCachedLinkage) {
849 assert(Linkage(CachedLinkage) == LI.linkage());
850 return LI;
Rafael Espindola54606d52012-12-25 07:31:49 +0000851 }
Rafael Espindola19de5612013-01-12 06:42:30 +0000852 HasCachedLinkage = 1;
853 CachedLinkage = LI.linkage();
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000854
855#ifndef NDEBUG
Rafael Espindola19de5612013-01-12 06:42:30 +0000856 verifyLinkage();
857#endif
858
859 return LI;
860}
861
862void NamedDecl::verifyLinkage() const {
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000863 // In C (because of gnu inline) and in c++ with microsoft extensions an
864 // static can follow an extern, so we can have two decls with different
865 // linkages.
866 const LangOptions &Opts = getASTContext().getLangOpts();
867 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
Rafael Espindola19de5612013-01-12 06:42:30 +0000868 return;
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000869
870 // We have just computed the linkage for this decl. By induction we know
871 // that all other computed linkages match, check that the one we just computed
872 // also does.
873 NamedDecl *D = NULL;
874 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
875 NamedDecl *T = cast<NamedDecl>(*I);
876 if (T == this)
877 continue;
Rafael Espindola19de5612013-01-12 06:42:30 +0000878 if (T->HasCachedLinkage != 0) {
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000879 D = T;
880 break;
881 }
882 }
883 assert(!D || D->CachedLinkage == CachedLinkage);
John McCall033caa52010-10-29 00:29:13 +0000884}
Ted Kremenek926d8602010-04-20 23:15:35 +0000885
John McCalld041a9b2013-02-20 01:54:26 +0000886llvm::Optional<Visibility>
887NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000888 // Use the most recent declaration of a variable.
Rafael Espindola96e68242012-05-16 02:10:38 +0000889 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
John McCalld041a9b2013-02-20 01:54:26 +0000890 if (llvm::Optional<Visibility> V = getVisibilityOf(Var, kind))
Rafael Espindola96e68242012-05-16 02:10:38 +0000891 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000892
Rafael Espindola96e68242012-05-16 02:10:38 +0000893 if (Var->isStaticDataMember()) {
894 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
895 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +0000896 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +0000897 }
898
899 return llvm::Optional<Visibility>();
900 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000901 // Use the most recent declaration of a function, and also handle
902 // function template specializations.
903 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
John McCalld041a9b2013-02-20 01:54:26 +0000904 if (llvm::Optional<Visibility> V = getVisibilityOf(fn, kind))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000905 return V;
906
907 // If the function is a specialization of a template with an
908 // explicit visibility attribute, use that.
909 if (FunctionTemplateSpecializationInfo *templateInfo
910 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +0000911 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
912 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000913
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000914 // If the function is a member of a specialization of a class template
915 // and the corresponding decl has explicit visibility, use that.
916 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
917 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +0000918 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000919
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000920 return llvm::Optional<Visibility>();
921 }
922
923 // Otherwise, just check the declaration itself first.
John McCalld041a9b2013-02-20 01:54:26 +0000924 if (llvm::Optional<Visibility> V = getVisibilityOf(this, kind))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000925 return V;
926
Rafael Espindolafb4263f2012-07-31 19:02:02 +0000927 // The visibility of a template is stored in the templated decl.
928 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(this))
John McCalld041a9b2013-02-20 01:54:26 +0000929 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +0000930
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000931 // If there wasn't explicit visibility there, and this is a
932 // specialization of a class template, check for visibility
933 // on the pattern.
934 if (const ClassTemplateSpecializationDecl *spec
Rafael Espindolaeca5cd22012-07-13 01:19:08 +0000935 = dyn_cast<ClassTemplateSpecializationDecl>(this))
John McCalld041a9b2013-02-20 01:54:26 +0000936 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
937 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000938
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000939 // If this is a member class of a specialization of a class template
940 // and the corresponding decl has explicit visibility, use that.
941 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(this)) {
942 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
943 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +0000944 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000945 }
946
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000947 return llvm::Optional<Visibility>();
948}
949
John McCalldf25c432013-02-16 00:17:33 +0000950static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
951 LVComputationKind computation) {
952 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
953 if (Function->isInAnonymousNamespace() &&
954 !Function->getDeclContext()->isExternCContext())
955 return LinkageInfo::uniqueExternal();
956
957 // This is a "void f();" which got merged with a file static.
958 if (Function->getStorageClass() == SC_Static)
959 return LinkageInfo::internal();
960
961 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +0000962 if (!hasExplicitVisibilityAlready(computation)) {
963 if (llvm::Optional<Visibility> Vis
964 = getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +0000965 LV.mergeVisibility(*Vis, true);
966 }
967
968 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
969 // merging storage classes and visibility attributes, so we don't have to
970 // look at previous decls in here.
971
972 return LV;
973 }
974
975 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
976 if (Var->getStorageClassAsWritten() == SC_Extern ||
977 Var->getStorageClassAsWritten() == SC_PrivateExtern) {
978 if (Var->isInAnonymousNamespace() &&
979 !Var->getDeclContext()->isExternCContext())
980 return LinkageInfo::uniqueExternal();
981
982 // This is an "extern int foo;" which got merged with a file static.
983 if (Var->getStorageClass() == SC_Static)
984 return LinkageInfo::internal();
985
986 LinkageInfo LV;
987 if (Var->getStorageClass() == SC_PrivateExtern)
988 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +0000989 else if (!hasExplicitVisibilityAlready(computation)) {
990 if (llvm::Optional<Visibility> Vis
991 = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +0000992 LV.mergeVisibility(*Vis, true);
993 }
994
995 // Note that Sema::MergeVarDecl already takes care of implementing
996 // C99 6.2.2p4 and propagating the visibility attribute, so we don't
997 // have to do it here.
998 return LV;
999 }
1000 }
1001
1002 return LinkageInfo::none();
1003}
1004
1005static LinkageInfo getLVForDecl(const NamedDecl *D,
1006 LVComputationKind computation) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001007 // Objective-C: treat all Objective-C declarations as having external
1008 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001009 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001010 default:
1011 break;
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001012 case Decl::ParmVar:
1013 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001014 case Decl::TemplateTemplateParm: // count these as external
1015 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001016 case Decl::ObjCAtDefsField:
1017 case Decl::ObjCCategory:
1018 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001019 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001020 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001021 case Decl::ObjCMethod:
1022 case Decl::ObjCProperty:
1023 case Decl::ObjCPropertyImpl:
1024 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +00001025 return LinkageInfo::external();
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001026
1027 case Decl::CXXRecord: {
1028 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1029 if (Record->isLambda()) {
1030 if (!Record->getLambdaManglingNumber()) {
1031 // This lambda has no mangling number, so it's internal.
1032 return LinkageInfo::internal();
1033 }
1034
1035 // This lambda has its linkage/visibility determined by its owner.
1036 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
1037 if (Decl *ContextDecl = Record->getLambdaContextDecl()) {
1038 if (isa<ParmVarDecl>(ContextDecl))
1039 DC = ContextDecl->getDeclContext()->getRedeclContext();
1040 else
John McCalldf25c432013-02-16 00:17:33 +00001041 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001042 }
1043
1044 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
John McCalldf25c432013-02-16 00:17:33 +00001045 return getLVForDecl(ND, computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001046
1047 return LinkageInfo::external();
1048 }
1049
1050 break;
1051 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001052 }
1053
Douglas Gregorf73b2822009-11-25 22:24:25 +00001054 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001055 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCalldf25c432013-02-16 00:17:33 +00001056 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001057
1058 // C++ [basic.link]p5:
1059 // In addition, a member function, static data member, a named
1060 // class or enumeration of class scope, or an unnamed class or
1061 // enumeration defined in a class-scope typedef declaration such
1062 // that the class or enumeration has the typedef name for linkage
1063 // purposes (7.1.3), has external linkage if the name of the class
1064 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001065 if (D->getDeclContext()->isRecord())
John McCalldf25c432013-02-16 00:17:33 +00001066 return getLVForClassMember(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001067
1068 // C++ [basic.link]p6:
1069 // The name of a function declared in block scope and the name of
1070 // an object declared by a block scope extern declaration have
1071 // linkage. If there is a visible declaration of an entity with
1072 // linkage having the same name and type, ignoring entities
1073 // declared outside the innermost enclosing namespace scope, the
1074 // block scope declaration declares that same entity and receives
1075 // the linkage of the previous declaration. If there is more than
1076 // one such matching entity, the program is ill-formed. Otherwise,
1077 // if no matching entity is found, the block scope entity receives
1078 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001079 if (D->getDeclContext()->isFunctionOrMethod())
1080 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001081
1082 // C++ [basic.link]p6:
1083 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001084 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001085}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001086
Douglas Gregor2ada0482009-02-04 17:27:36 +00001087std::string NamedDecl::getQualifiedNameAsString() const {
Douglas Gregor78254c82012-03-27 23:34:16 +00001088 return getQualifiedNameAsString(getASTContext().getPrintingPolicy());
Anders Carlsson2fb08242009-09-08 18:24:21 +00001089}
1090
1091std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001092 const DeclContext *Ctx = getDeclContext();
1093
1094 if (Ctx->isFunctionOrMethod())
1095 return getNameAsString();
1096
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001097 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001098 ContextsTy Contexts;
1099
1100 // Collect contexts.
1101 while (Ctx && isa<NamedDecl>(Ctx)) {
1102 Contexts.push_back(Ctx);
1103 Ctx = Ctx->getParent();
1104 };
1105
1106 std::string QualName;
1107 llvm::raw_string_ostream OS(QualName);
1108
1109 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1110 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00001111 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001112 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Douglas Gregor85673582009-05-18 17:01:57 +00001113 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1114 std::string TemplateArgsStr
1115 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001116 TemplateArgs.data(),
1117 TemplateArgs.size(),
Anders Carlsson2fb08242009-09-08 18:24:21 +00001118 P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001119 OS << Spec->getName() << TemplateArgsStr;
1120 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Sam Weinig07d211e2009-12-24 23:15:03 +00001121 if (ND->isAnonymousNamespace())
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001122 OS << "<anonymous namespace>";
Sam Weinig07d211e2009-12-24 23:15:03 +00001123 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001124 OS << *ND;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001125 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1126 if (!RD->getIdentifier())
1127 OS << "<anonymous " << RD->getKindName() << '>';
1128 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001129 OS << *RD;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001130 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Sam Weinigb999f682009-12-28 03:19:38 +00001131 const FunctionProtoType *FT = 0;
1132 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001133 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001134
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001135 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001136 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001137 unsigned NumParams = FD->getNumParams();
1138 for (unsigned i = 0; i < NumParams; ++i) {
1139 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001140 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001141 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001142 }
1143
1144 if (FT->isVariadic()) {
1145 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001146 OS << ", ";
1147 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001148 }
1149 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001150 OS << ')';
1151 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001152 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001153 }
1154 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001155 }
1156
John McCalla2a3f7d2010-03-16 21:48:18 +00001157 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001158 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001159 else
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001160 OS << "<anonymous>";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001161
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001162 return OS.str();
Douglas Gregor2ada0482009-02-04 17:27:36 +00001163}
1164
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001165bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001166 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1167
Douglas Gregor889ceb72009-02-03 19:21:40 +00001168 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1169 // We want to keep it, unless it nominates same namespace.
1170 if (getKind() == Decl::UsingDirective) {
Douglas Gregor12441b32011-02-25 16:33:46 +00001171 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1172 ->getOriginalNamespace() ==
1173 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1174 ->getOriginalNamespace();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001175 }
Mike Stump11289f42009-09-09 15:08:12 +00001176
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001177 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1178 // For function declarations, we keep track of redeclarations.
Douglas Gregorec9fd132012-01-14 16:38:05 +00001179 return FD->getPreviousDecl() == OldD;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001180
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001181 // For function templates, the underlying function declarations are linked.
1182 if (const FunctionTemplateDecl *FunctionTemplate
1183 = dyn_cast<FunctionTemplateDecl>(this))
1184 if (const FunctionTemplateDecl *OldFunctionTemplate
1185 = dyn_cast<FunctionTemplateDecl>(OldD))
1186 return FunctionTemplate->getTemplatedDecl()
1187 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001188
Steve Naroffc4173fa2009-02-22 19:35:57 +00001189 // For method declarations, we keep track of redeclarations.
1190 if (isa<ObjCMethodDecl>(this))
1191 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001192
John McCall9f3059a2009-10-09 21:13:30 +00001193 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1194 return true;
1195
John McCall3f746822009-11-17 05:59:44 +00001196 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1197 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1198 cast<UsingShadowDecl>(OldD)->getTargetDecl();
1199
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001200 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1201 ASTContext &Context = getASTContext();
1202 return Context.getCanonicalNestedNameSpecifier(
1203 cast<UsingDecl>(this)->getQualifier()) ==
1204 Context.getCanonicalNestedNameSpecifier(
1205 cast<UsingDecl>(OldD)->getQualifier());
1206 }
Argyrios Kyrtzidis4b520072010-11-04 08:48:52 +00001207
Douglas Gregorb59643b2012-01-03 23:26:26 +00001208 // A typedef of an Objective-C class type can replace an Objective-C class
1209 // declaration or definition, and vice versa.
1210 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1211 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1212 return true;
1213
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001214 // For non-function declarations, if the declarations are of the
1215 // same kind then this must be a redeclaration, or semantic analysis
1216 // would not have given us the new declaration.
1217 return this->getKind() == OldD->getKind();
1218}
1219
Douglas Gregoreddf4332009-02-24 20:03:32 +00001220bool NamedDecl::hasLinkage() const {
Douglas Gregorf73b2822009-11-25 22:24:25 +00001221 return getLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001222}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001223
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001224NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001225 NamedDecl *ND = this;
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001226 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1227 ND = UD->getTargetDecl();
1228
1229 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1230 return AD->getClassInterface();
1231
1232 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001233}
1234
John McCalla8ae2222010-04-06 21:38:20 +00001235bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001236 if (!isCXXClassMember())
1237 return false;
1238
John McCalla8ae2222010-04-06 21:38:20 +00001239 const NamedDecl *D = this;
1240 if (isa<UsingShadowDecl>(D))
1241 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1242
Francois Pichet783dd6e2010-11-21 06:08:52 +00001243 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001244 return true;
1245 if (isa<CXXMethodDecl>(D))
1246 return cast<CXXMethodDecl>(D)->isInstance();
1247 if (isa<FunctionTemplateDecl>(D))
1248 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
1249 ->getTemplatedDecl())->isInstance();
1250 return false;
1251}
1252
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001253//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001254// DeclaratorDecl Implementation
1255//===----------------------------------------------------------------------===//
1256
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001257template <typename DeclT>
1258static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1259 if (decl->getNumTemplateParameterLists() > 0)
1260 return decl->getTemplateParameterList(0)->getTemplateLoc();
1261 else
1262 return decl->getInnerLocStart();
1263}
1264
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001265SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001266 TypeSourceInfo *TSI = getTypeSourceInfo();
1267 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001268 return SourceLocation();
1269}
1270
Douglas Gregor14454802011-02-25 02:25:35 +00001271void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1272 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001273 // Make sure the extended decl info is allocated.
1274 if (!hasExtInfo()) {
1275 // Save (non-extended) type source info pointer.
1276 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1277 // Allocate external info struct.
1278 DeclInfo = new (getASTContext()) ExtInfo;
1279 // Restore savedTInfo into (extended) decl info.
1280 getExtInfo()->TInfo = savedTInfo;
1281 }
1282 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001283 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001284 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001285 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001286 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001287 if (getExtInfo()->NumTemplParamLists == 0) {
1288 // Save type source info pointer.
1289 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1290 // Deallocate the extended decl info.
1291 getASTContext().Deallocate(getExtInfo());
1292 // Restore savedTInfo into (non-extended) decl info.
1293 DeclInfo = savedTInfo;
1294 }
1295 else
1296 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001297 }
1298 }
1299}
1300
Abramo Bagnara60804e12011-03-18 15:16:37 +00001301void
1302DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1303 unsigned NumTPLists,
1304 TemplateParameterList **TPLists) {
1305 assert(NumTPLists > 0);
1306 // Make sure the extended decl info is allocated.
1307 if (!hasExtInfo()) {
1308 // Save (non-extended) type source info pointer.
1309 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1310 // Allocate external info struct.
1311 DeclInfo = new (getASTContext()) ExtInfo;
1312 // Restore savedTInfo into (extended) decl info.
1313 getExtInfo()->TInfo = savedTInfo;
1314 }
1315 // Set the template parameter lists info.
1316 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1317}
1318
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001319SourceLocation DeclaratorDecl::getOuterLocStart() const {
1320 return getTemplateOrInnerLocStart(this);
1321}
1322
Abramo Bagnaraea947882011-03-08 16:41:52 +00001323namespace {
1324
1325// Helper function: returns true if QT is or contains a type
1326// having a postfix component.
1327bool typeIsPostfix(clang::QualType QT) {
1328 while (true) {
1329 const Type* T = QT.getTypePtr();
1330 switch (T->getTypeClass()) {
1331 default:
1332 return false;
1333 case Type::Pointer:
1334 QT = cast<PointerType>(T)->getPointeeType();
1335 break;
1336 case Type::BlockPointer:
1337 QT = cast<BlockPointerType>(T)->getPointeeType();
1338 break;
1339 case Type::MemberPointer:
1340 QT = cast<MemberPointerType>(T)->getPointeeType();
1341 break;
1342 case Type::LValueReference:
1343 case Type::RValueReference:
1344 QT = cast<ReferenceType>(T)->getPointeeType();
1345 break;
1346 case Type::PackExpansion:
1347 QT = cast<PackExpansionType>(T)->getPattern();
1348 break;
1349 case Type::Paren:
1350 case Type::ConstantArray:
1351 case Type::DependentSizedArray:
1352 case Type::IncompleteArray:
1353 case Type::VariableArray:
1354 case Type::FunctionProto:
1355 case Type::FunctionNoProto:
1356 return true;
1357 }
1358 }
1359}
1360
1361} // namespace
1362
1363SourceRange DeclaratorDecl::getSourceRange() const {
1364 SourceLocation RangeEnd = getLocation();
1365 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1366 if (typeIsPostfix(TInfo->getType()))
1367 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1368 }
1369 return SourceRange(getOuterLocStart(), RangeEnd);
1370}
1371
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001372void
Douglas Gregor20527e22010-06-15 17:44:38 +00001373QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1374 unsigned NumTPLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001375 TemplateParameterList **TPLists) {
1376 assert((NumTPLists == 0 || TPLists != 0) &&
1377 "Empty array of template parameters with positive size!");
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001378
1379 // Free previous template parameters (if any).
1380 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001381 Context.Deallocate(TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001382 TemplParamLists = 0;
1383 NumTemplParamLists = 0;
1384 }
1385 // Set info on matched template parameter lists (if any).
1386 if (NumTPLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001387 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001388 NumTemplParamLists = NumTPLists;
1389 for (unsigned i = NumTPLists; i-- > 0; )
1390 TemplParamLists[i] = TPLists[i];
1391 }
1392}
1393
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001394//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001395// VarDecl Implementation
1396//===----------------------------------------------------------------------===//
1397
Sebastian Redl833ef452010-01-26 22:01:41 +00001398const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1399 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001400 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001401 case SC_Auto: return "auto";
1402 case SC_Extern: return "extern";
1403 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1404 case SC_PrivateExtern: return "__private_extern__";
1405 case SC_Register: return "register";
1406 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001407 }
1408
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001409 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001410}
1411
Abramo Bagnaradff19302011-03-08 08:55:46 +00001412VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1413 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001414 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001415 StorageClass S, StorageClass SCAsWritten) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001416 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
Nuno Lopes394ec982008-12-17 23:39:55 +00001417}
1418
Douglas Gregor72172e92012-01-05 21:55:30 +00001419VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1420 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
1421 return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1422 QualType(), 0, SC_None, SC_None);
1423}
1424
Douglas Gregorbf62d642010-12-06 18:36:25 +00001425void VarDecl::setStorageClass(StorageClass SC) {
1426 assert(isLegalForVariable(SC));
1427 if (getStorageClass() != SC)
Rafael Espindola19de5612013-01-12 06:42:30 +00001428 ClearLinkageCache();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001429
John McCallbeaa11c2011-05-01 02:13:58 +00001430 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001431}
1432
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001433SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001434 if (const Expr *Init = getInit()) {
1435 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001436 // If Init is implicit, ignore its source range and fallback on
1437 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1438 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001439 return SourceRange(getOuterLocStart(), InitEnd);
1440 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001441 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001442}
1443
Rafael Espindola88510672013-01-04 21:18:45 +00001444template<typename T>
Rafael Espindolaf4187652013-02-14 01:18:37 +00001445static LanguageLinkage getLanguageLinkageTemplate(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001446 // C++ [dcl.link]p1: All function types, function names with external linkage,
1447 // and variable names with external linkage have a language linkage.
1448 if (!isExternalLinkage(D.getLinkage()))
1449 return NoLanguageLinkage;
1450
1451 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001452 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001453 ASTContext &Context = D.getASTContext();
1454 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001455 return CLanguageLinkage;
1456
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001457 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1458 // language linkage of the names of class members and the function type of
1459 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001460 const DeclContext *DC = D.getDeclContext();
1461 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001462 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001463
1464 // If the first decl is in an extern "C" context, any other redeclaration
1465 // will have C language linkage. If the first one is not in an extern "C"
1466 // context, we would have reported an error for any other decl being in one.
Rafael Espindola88510672013-01-04 21:18:45 +00001467 const T *First = D.getFirstDeclaration();
Rafael Espindolaf4187652013-02-14 01:18:37 +00001468 if (First->getDeclContext()->isExternCContext())
1469 return CLanguageLinkage;
1470 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001471}
1472
Rafael Espindolaf4187652013-02-14 01:18:37 +00001473LanguageLinkage VarDecl::getLanguageLinkage() const {
1474 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001475}
1476
Sebastian Redl833ef452010-01-26 22:01:41 +00001477VarDecl *VarDecl::getCanonicalDecl() {
1478 return getFirstDeclaration();
1479}
1480
Daniel Dunbar9d355812012-03-09 01:51:51 +00001481VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1482 ASTContext &C) const
1483{
Sebastian Redl35351a92010-01-31 22:27:38 +00001484 // C++ [basic.def]p2:
1485 // A declaration is a definition unless [...] it contains the 'extern'
1486 // specifier or a linkage-specification and neither an initializer [...],
1487 // it declares a static data member in a class declaration [...].
1488 // C++ [temp.expl.spec]p15:
1489 // An explicit specialization of a static data member of a template is a
1490 // definition if the declaration includes an initializer; otherwise, it is
1491 // a declaration.
1492 if (isStaticDataMember()) {
1493 if (isOutOfLine() && (hasInit() ||
1494 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1495 return Definition;
1496 else
1497 return DeclarationOnly;
1498 }
1499 // C99 6.7p5:
1500 // A definition of an identifier is a declaration for that identifier that
1501 // [...] causes storage to be reserved for that object.
1502 // Note: that applies for all non-file-scope objects.
1503 // C99 6.9.2p1:
1504 // If the declaration of an identifier for an object has file scope and an
1505 // initializer, the declaration is an external definition for the identifier
1506 if (hasInit())
1507 return Definition;
1508 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1509 if (hasExternalStorage())
1510 return DeclarationOnly;
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001511
John McCall8e7d6562010-08-26 03:08:43 +00001512 if (getStorageClassAsWritten() == SC_Extern ||
1513 getStorageClassAsWritten() == SC_PrivateExtern) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00001514 for (const VarDecl *PrevVar = getPreviousDecl();
1515 PrevVar; PrevVar = PrevVar->getPreviousDecl()) {
Rafael Espindola7581f322012-12-17 22:23:47 +00001516 if (PrevVar->getLinkage() == InternalLinkage)
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001517 return DeclarationOnly;
1518 }
1519 }
Sebastian Redl35351a92010-01-31 22:27:38 +00001520 // C99 6.9.2p2:
1521 // A declaration of an object that has file scope without an initializer,
1522 // and without a storage class specifier or the scs 'static', constitutes
1523 // a tentative definition.
1524 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001525 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00001526 return TentativeDefinition;
1527
1528 // What's left is (in C, block-scope) declarations without initializers or
1529 // external storage. These are definitions.
1530 return Definition;
1531}
1532
Sebastian Redl35351a92010-01-31 22:27:38 +00001533VarDecl *VarDecl::getActingDefinition() {
1534 DefinitionKind Kind = isThisDeclarationADefinition();
1535 if (Kind != TentativeDefinition)
1536 return 0;
1537
Chris Lattner48eb14d2010-06-14 18:31:46 +00001538 VarDecl *LastTentative = 0;
Sebastian Redl35351a92010-01-31 22:27:38 +00001539 VarDecl *First = getFirstDeclaration();
1540 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1541 I != E; ++I) {
1542 Kind = (*I)->isThisDeclarationADefinition();
1543 if (Kind == Definition)
1544 return 0;
1545 else if (Kind == TentativeDefinition)
1546 LastTentative = *I;
1547 }
1548 return LastTentative;
1549}
1550
1551bool VarDecl::isTentativeDefinitionNow() const {
1552 DefinitionKind Kind = isThisDeclarationADefinition();
1553 if (Kind != TentativeDefinition)
1554 return false;
1555
1556 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1557 if ((*I)->isThisDeclarationADefinition() == Definition)
1558 return false;
1559 }
Sebastian Redl5ca79842010-02-01 20:16:42 +00001560 return true;
Sebastian Redl35351a92010-01-31 22:27:38 +00001561}
1562
Daniel Dunbar9d355812012-03-09 01:51:51 +00001563VarDecl *VarDecl::getDefinition(ASTContext &C) {
Sebastian Redlccdb5ff2010-02-02 17:55:12 +00001564 VarDecl *First = getFirstDeclaration();
1565 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1566 I != E; ++I) {
Daniel Dunbar9d355812012-03-09 01:51:51 +00001567 if ((*I)->isThisDeclarationADefinition(C) == Definition)
Sebastian Redl5ca79842010-02-01 20:16:42 +00001568 return *I;
1569 }
1570 return 0;
1571}
1572
Daniel Dunbar9d355812012-03-09 01:51:51 +00001573VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00001574 DefinitionKind Kind = DeclarationOnly;
1575
1576 const VarDecl *First = getFirstDeclaration();
1577 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001578 I != E; ++I) {
Daniel Dunbar9d355812012-03-09 01:51:51 +00001579 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001580 if (Kind == Definition)
1581 break;
1582 }
John McCall37bb6c92010-10-29 22:22:43 +00001583
1584 return Kind;
1585}
1586
Sebastian Redl5ca79842010-02-01 20:16:42 +00001587const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Sebastian Redl833ef452010-01-26 22:01:41 +00001588 redecl_iterator I = redecls_begin(), E = redecls_end();
1589 while (I != E && !I->getInit())
1590 ++I;
1591
1592 if (I != E) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001593 D = *I;
Sebastian Redl833ef452010-01-26 22:01:41 +00001594 return I->getInit();
1595 }
1596 return 0;
1597}
1598
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001599bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00001600 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001601 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001602
1603 if (!isStaticDataMember())
1604 return false;
1605
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001606 // If this static data member was instantiated from a static data member of
1607 // a class template, check whether that static data member was defined
1608 // out-of-line.
1609 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1610 return VD->isOutOfLine();
1611
1612 return false;
1613}
1614
Douglas Gregor1d957a32009-10-27 18:42:08 +00001615VarDecl *VarDecl::getOutOfLineDefinition() {
1616 if (!isStaticDataMember())
1617 return 0;
1618
1619 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1620 RD != RDEnd; ++RD) {
1621 if (RD->getLexicalDeclContext()->isFileContext())
1622 return *RD;
1623 }
1624
1625 return 0;
1626}
1627
Douglas Gregord5058122010-02-11 01:19:42 +00001628void VarDecl::setInit(Expr *I) {
Sebastian Redl833ef452010-01-26 22:01:41 +00001629 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1630 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00001631 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00001632 }
1633
1634 Init = I;
1635}
1636
Daniel Dunbar9d355812012-03-09 01:51:51 +00001637bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001638 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00001639
Richard Smith35ecb362012-03-02 04:14:40 +00001640 if (!Lang.CPlusPlus)
1641 return false;
1642
1643 // In C++11, any variable of reference type can be used in a constant
1644 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001645 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00001646 return true;
1647
1648 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00001649 // not require the variable to be non-volatile, but we consider this to be a
1650 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00001651 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00001652 return false;
1653
1654 // In C++, const, non-volatile variables of integral or enumeration types
1655 // can be used in constant expressions.
1656 if (getType()->isIntegralOrEnumerationType())
1657 return true;
1658
Richard Smith35ecb362012-03-02 04:14:40 +00001659 // Additionally, in C++11, non-volatile constexpr variables can be used in
1660 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001661 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00001662}
1663
Richard Smithd0b4dd62011-12-19 06:19:21 +00001664/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1665/// form, which contains extra information on the evaluated value of the
1666/// initializer.
1667EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1668 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1669 if (!Eval) {
1670 Stmt *S = Init.get<Stmt *>();
1671 Eval = new (getASTContext()) EvaluatedStmt;
1672 Eval->Value = S;
1673 Init = Eval;
1674 }
1675 return Eval;
1676}
1677
Richard Smithdafff942012-01-14 04:30:29 +00001678APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001679 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00001680 return evaluateValue(Notes);
1681}
1682
1683APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001684 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001685 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1686
1687 // We only produce notes indicating why an initializer is non-constant the
1688 // first time it is evaluated. FIXME: The notes won't always be emitted the
1689 // first time we try evaluation, so might not be produced at all.
1690 if (Eval->WasEvaluated)
Richard Smithdafff942012-01-14 04:30:29 +00001691 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001692
1693 const Expr *Init = cast<Expr>(Eval->Value);
1694 assert(!Init->isValueDependent());
1695
1696 if (Eval->IsEvaluating) {
1697 // FIXME: Produce a diagnostic for self-initialization.
1698 Eval->CheckedICE = true;
1699 Eval->IsICE = false;
Richard Smithdafff942012-01-14 04:30:29 +00001700 return 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001701 }
1702
1703 Eval->IsEvaluating = true;
1704
1705 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1706 this, Notes);
1707
1708 // Ensure the result is an uninitialized APValue if evaluation fails.
1709 if (!Result)
1710 Eval->Evaluated = APValue();
1711
1712 Eval->IsEvaluating = false;
1713 Eval->WasEvaluated = true;
1714
1715 // In C++11, we have determined whether the initializer was a constant
1716 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001717 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001718 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00001719 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00001720 }
1721
Richard Smithdafff942012-01-14 04:30:29 +00001722 return Result ? &Eval->Evaluated : 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001723}
1724
1725bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00001726 // Initializers of weak variables are never ICEs.
1727 if (isWeak())
1728 return false;
1729
Richard Smithd0b4dd62011-12-19 06:19:21 +00001730 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1731 if (Eval->CheckedICE)
1732 // We have already checked whether this subexpression is an
1733 // integral constant expression.
1734 return Eval->IsICE;
1735
1736 const Expr *Init = cast<Expr>(Eval->Value);
1737 assert(!Init->isValueDependent());
1738
1739 // In C++11, evaluate the initializer to check whether it's a constant
1740 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001741 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001742 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001743 evaluateValue(Notes);
1744 return Eval->IsICE;
1745 }
1746
1747 // It's an ICE whether or not the definition we found is
1748 // out-of-line. See DR 721 and the discussion in Clang PR
1749 // 6206 for details.
1750
1751 if (Eval->CheckingICE)
1752 return false;
1753 Eval->CheckingICE = true;
1754
1755 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1756 Eval->CheckingICE = false;
1757 Eval->CheckedICE = true;
1758 return Eval->IsICE;
1759}
1760
Douglas Gregorfe314812011-06-21 17:03:29 +00001761bool VarDecl::extendsLifetimeOfTemporary() const {
Douglas Gregord410c082011-06-21 18:20:46 +00001762 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
Douglas Gregorfe314812011-06-21 17:03:29 +00001763
1764 const Expr *E = getInit();
1765 if (!E)
1766 return false;
1767
1768 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1769 E = Cleanups->getSubExpr();
1770
1771 return isa<MaterializeTemporaryExpr>(E);
1772}
1773
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001774VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001775 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001776 return cast<VarDecl>(MSI->getInstantiatedFrom());
1777
1778 return 0;
1779}
1780
Douglas Gregor3c74d412009-10-14 20:14:33 +00001781TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001782 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001783 return MSI->getTemplateSpecializationKind();
1784
1785 return TSK_Undeclared;
1786}
1787
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001788MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001789 return getASTContext().getInstantiatedFromStaticDataMember(this);
1790}
1791
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001792void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1793 SourceLocation PointOfInstantiation) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001794 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00001795 assert(MSI && "Not an instantiated static data member?");
1796 MSI->setTemplateSpecializationKind(TSK);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001797 if (TSK != TSK_ExplicitSpecialization &&
1798 PointOfInstantiation.isValid() &&
1799 MSI->getPointOfInstantiation().isInvalid())
1800 MSI->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001801}
1802
Sebastian Redl833ef452010-01-26 22:01:41 +00001803//===----------------------------------------------------------------------===//
1804// ParmVarDecl Implementation
1805//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00001806
Sebastian Redl833ef452010-01-26 22:01:41 +00001807ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001808 SourceLocation StartLoc,
1809 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00001810 QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001811 StorageClass S, StorageClass SCAsWritten,
1812 Expr *DefArg) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001813 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001814 S, SCAsWritten, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00001815}
1816
Douglas Gregor72172e92012-01-05 21:55:30 +00001817ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1818 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
1819 return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
1820 0, QualType(), 0, SC_None, SC_None, 0);
1821}
1822
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00001823SourceRange ParmVarDecl::getSourceRange() const {
1824 if (!hasInheritedDefaultArg()) {
1825 SourceRange ArgRange = getDefaultArgRange();
1826 if (ArgRange.isValid())
1827 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1828 }
1829
1830 return DeclaratorDecl::getSourceRange();
1831}
1832
Sebastian Redl833ef452010-01-26 22:01:41 +00001833Expr *ParmVarDecl::getDefaultArg() {
1834 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1835 assert(!hasUninstantiatedDefaultArg() &&
1836 "Default argument is not yet instantiated!");
1837
1838 Expr *Arg = getInit();
John McCall5d413782010-12-06 08:20:24 +00001839 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00001840 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00001841
Sebastian Redl833ef452010-01-26 22:01:41 +00001842 return Arg;
1843}
1844
Sebastian Redl833ef452010-01-26 22:01:41 +00001845SourceRange ParmVarDecl::getDefaultArgRange() const {
1846 if (const Expr *E = getInit())
1847 return E->getSourceRange();
1848
1849 if (hasUninstantiatedDefaultArg())
1850 return getUninstantiatedDefaultArg()->getSourceRange();
1851
1852 return SourceRange();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00001853}
1854
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00001855bool ParmVarDecl::isParameterPack() const {
1856 return isa<PackExpansionType>(getType());
1857}
1858
Ted Kremenek540017e2011-10-06 05:00:56 +00001859void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1860 getASTContext().setParameterIndex(this, parameterIndex);
1861 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1862}
1863
1864unsigned ParmVarDecl::getParameterIndexLarge() const {
1865 return getASTContext().getParameterIndex(this);
1866}
1867
Nuno Lopes394ec982008-12-17 23:39:55 +00001868//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00001869// FunctionDecl Implementation
1870//===----------------------------------------------------------------------===//
1871
Douglas Gregorb11aad82011-02-19 18:51:44 +00001872void FunctionDecl::getNameForDiagnostic(std::string &S,
1873 const PrintingPolicy &Policy,
1874 bool Qualified) const {
1875 NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
1876 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1877 if (TemplateArgs)
1878 S += TemplateSpecializationType::PrintTemplateArgumentList(
1879 TemplateArgs->data(),
1880 TemplateArgs->size(),
1881 Policy);
1882
1883}
1884
Ted Kremenek186a0742010-04-29 16:49:01 +00001885bool FunctionDecl::isVariadic() const {
1886 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1887 return FT->isVariadic();
1888 return false;
1889}
1890
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001891bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1892 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Francois Pichet1c229c02011-04-22 22:18:13 +00001893 if (I->Body || I->IsLateTemplateParsed) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001894 Definition = *I;
1895 return true;
1896 }
1897 }
1898
1899 return false;
1900}
1901
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001902bool FunctionDecl::hasTrivialBody() const
1903{
1904 Stmt *S = getBody();
1905 if (!S) {
1906 // Since we don't have a body for this function, we don't know if it's
1907 // trivial or not.
1908 return false;
1909 }
1910
1911 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
1912 return true;
1913 return false;
1914}
1915
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001916bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
1917 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00001918 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001919 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
1920 return true;
1921 }
1922 }
1923
1924 return false;
1925}
1926
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001927Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Argyrios Kyrtzidis1506d9b2009-07-14 03:20:21 +00001928 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1929 if (I->Body) {
1930 Definition = *I;
1931 return I->Body.get(getASTContext().getExternalSource());
Francois Pichet1c229c02011-04-22 22:18:13 +00001932 } else if (I->IsLateTemplateParsed) {
1933 Definition = *I;
1934 return 0;
Douglas Gregor89f238c2008-04-21 02:02:58 +00001935 }
1936 }
1937
1938 return 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001939}
1940
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001941void FunctionDecl::setBody(Stmt *B) {
1942 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00001943 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001944 EndRangeLoc = B->getLocEnd();
1945}
1946
Douglas Gregor7d9120c2010-09-28 21:55:22 +00001947void FunctionDecl::setPure(bool P) {
1948 IsPure = P;
1949 if (P)
1950 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
1951 Parent->markedVirtualFunctionPure();
1952}
1953
Douglas Gregor16618f22009-09-12 00:17:51 +00001954bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00001955 const TranslationUnitDecl *tunit =
1956 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
1957 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001958 !tunit->getASTContext().getLangOpts().Freestanding &&
John McCall53ffd372011-05-15 17:49:20 +00001959 getIdentifier() &&
1960 getIdentifier()->isStr("main");
1961}
1962
1963bool FunctionDecl::isReservedGlobalPlacementOperator() const {
1964 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
1965 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
1966 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
1967 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
1968 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
1969
1970 if (isa<CXXRecordDecl>(getDeclContext())) return false;
1971 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
1972
1973 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
1974 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
1975
1976 ASTContext &Context =
1977 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
1978 ->getASTContext();
1979
1980 // The result type and first argument type are constant across all
1981 // these operators. The second argument must be exactly void*.
1982 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00001983}
1984
Rafael Espindolaf4187652013-02-14 01:18:37 +00001985LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Rafael Espindola6239e052013-01-12 15:27:44 +00001986 // Users expect to be able to write
1987 // extern "C" void *__builtin_alloca (size_t);
1988 // so consider builtins as having C language linkage.
Rafael Espindolac48f7342013-01-12 15:27:43 +00001989 if (getBuiltinID())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001990 return CLanguageLinkage;
Rafael Espindolac48f7342013-01-12 15:27:43 +00001991
Rafael Espindolaf4187652013-02-14 01:18:37 +00001992 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001993}
1994
Douglas Gregorf1b876d2009-03-31 16:35:03 +00001995bool FunctionDecl::isGlobal() const {
1996 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
1997 return Method->isStatic();
1998
John McCall8e7d6562010-08-26 03:08:43 +00001999 if (getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002000 return false;
2001
Mike Stump11289f42009-09-09 15:08:12 +00002002 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002003 DC->isNamespace();
2004 DC = DC->getParent()) {
2005 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2006 if (!Namespace->getDeclName())
2007 return false;
2008 break;
2009 }
2010 }
2011
2012 return true;
2013}
2014
Richard Smith10876ef2013-01-17 01:30:42 +00002015bool FunctionDecl::isNoReturn() const {
2016 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
Richard Smithdebc59d2013-01-30 05:45:05 +00002017 hasAttr<C11NoReturnAttr>() ||
Richard Smith10876ef2013-01-17 01:30:42 +00002018 getType()->getAs<FunctionType>()->getNoReturnAttr();
2019}
2020
Sebastian Redl833ef452010-01-26 22:01:41 +00002021void
2022FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2023 redeclarable_base::setPreviousDeclaration(PrevDecl);
2024
2025 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2026 FunctionTemplateDecl *PrevFunTmpl
2027 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
2028 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2029 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
2030 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002031
Axel Naumannfbc7b982011-11-08 18:21:06 +00002032 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002033 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002034}
2035
2036const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
2037 return getFirstDeclaration();
2038}
2039
2040FunctionDecl *FunctionDecl::getCanonicalDecl() {
2041 return getFirstDeclaration();
2042}
2043
Douglas Gregorbf62d642010-12-06 18:36:25 +00002044void FunctionDecl::setStorageClass(StorageClass SC) {
2045 assert(isLegalForFunction(SC));
2046 if (getStorageClass() != SC)
Rafael Espindola19de5612013-01-12 06:42:30 +00002047 ClearLinkageCache();
Douglas Gregorbf62d642010-12-06 18:36:25 +00002048
2049 SClass = SC;
2050}
2051
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002052/// \brief Returns a value indicating whether this function
2053/// corresponds to a builtin function.
2054///
2055/// The function corresponds to a built-in function if it is
2056/// declared at translation scope or within an extern "C" block and
2057/// its name matches with the name of a builtin. The returned value
2058/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002059/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002060/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002061unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002062 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002063 return 0;
2064
2065 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002066 if (!BuiltinID)
2067 return 0;
2068
2069 ASTContext &Context = getASTContext();
Douglas Gregore711f702009-02-14 18:57:46 +00002070 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2071 return BuiltinID;
2072
2073 // This function has the name of a known C library
2074 // function. Determine whether it actually refers to the C library
2075 // function or whether it just has the same name.
2076
Douglas Gregora908e7f2009-02-17 03:23:10 +00002077 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002078 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002079 return 0;
2080
Douglas Gregore711f702009-02-14 18:57:46 +00002081 // If this function is at translation-unit scope and we're not in
2082 // C++, it refers to the C library function.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002083 if (!Context.getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +00002084 getDeclContext()->isTranslationUnit())
2085 return BuiltinID;
2086
2087 // If the function is in an extern "C" linkage specification and is
2088 // not marked "overloadable", it's the real function.
2089 if (isa<LinkageSpecDecl>(getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002090 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
Douglas Gregore711f702009-02-14 18:57:46 +00002091 == LinkageSpecDecl::lang_c &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002092 !getAttr<OverloadableAttr>())
Douglas Gregore711f702009-02-14 18:57:46 +00002093 return BuiltinID;
2094
2095 // Not a builtin
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002096 return 0;
2097}
2098
2099
Chris Lattner47c0d002009-04-25 06:03:53 +00002100/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002101/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002102/// after it has been created.
2103unsigned FunctionDecl::getNumParams() const {
Eli Friedman5c27c4c2012-08-30 22:22:09 +00002104 const FunctionType *FT = getType()->castAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002105 if (isa<FunctionNoProtoType>(FT))
Chris Lattner88f70d62008-03-15 05:43:15 +00002106 return 0;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002107 return cast<FunctionProtoType>(FT)->getNumArgs();
Mike Stump11289f42009-09-09 15:08:12 +00002108
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002109}
2110
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002111void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002112 ArrayRef<ParmVarDecl *> NewParamInfo) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002113 assert(ParamInfo == 0 && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002114 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002115
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002116 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002117 if (!NewParamInfo.empty()) {
2118 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2119 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002120 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002121}
Chris Lattner41943152007-01-25 04:52:46 +00002122
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002123void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
James Molloy6f8780b2012-02-29 10:24:19 +00002124 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2125
2126 if (!NewDecls.empty()) {
2127 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2128 std::copy(NewDecls.begin(), NewDecls.end(), A);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002129 DeclsInPrototypeScope = ArrayRef<NamedDecl *>(A, NewDecls.size());
James Molloy6f8780b2012-02-29 10:24:19 +00002130 }
2131}
2132
Chris Lattner58258242008-04-10 02:22:51 +00002133/// getMinRequiredArguments - Returns the minimum number of arguments
2134/// needed to call this function. This may be fewer than the number of
2135/// function parameters, if some of the parameters have default
Douglas Gregor7825bf32011-01-06 22:09:01 +00002136/// arguments (in C++) or the last parameter is a parameter pack.
Chris Lattner58258242008-04-10 02:22:51 +00002137unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002138 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002139 return getNumParams();
2140
Douglas Gregor7825bf32011-01-06 22:09:01 +00002141 unsigned NumRequiredArgs = getNumParams();
2142
2143 // If the last parameter is a parameter pack, we don't need an argument for
2144 // it.
2145 if (NumRequiredArgs > 0 &&
2146 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
2147 --NumRequiredArgs;
2148
2149 // If this parameter has a default argument, we don't need an argument for
2150 // it.
2151 while (NumRequiredArgs > 0 &&
2152 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
Chris Lattner58258242008-04-10 02:22:51 +00002153 --NumRequiredArgs;
2154
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002155 // We might have parameter packs before the end. These can't be deduced,
2156 // but they can still handle multiple arguments.
2157 unsigned ArgIdx = NumRequiredArgs;
2158 while (ArgIdx > 0) {
2159 if (getParamDecl(ArgIdx - 1)->isParameterPack())
2160 NumRequiredArgs = ArgIdx;
2161
2162 --ArgIdx;
2163 }
2164
Chris Lattner58258242008-04-10 02:22:51 +00002165 return NumRequiredArgs;
2166}
2167
Eli Friedman1b125c32012-02-07 03:50:18 +00002168static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2169 // Only consider file-scope declarations in this test.
2170 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2171 return false;
2172
2173 // Only consider explicit declarations; the presence of a builtin for a
2174 // libcall shouldn't affect whether a definition is externally visible.
2175 if (Redecl->isImplicit())
2176 return false;
2177
2178 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2179 return true; // Not an inline definition
2180
2181 return false;
2182}
2183
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002184/// \brief For a function declaration in C or C++, determine whether this
2185/// declaration causes the definition to be externally visible.
2186///
Eli Friedman1b125c32012-02-07 03:50:18 +00002187/// Specifically, this determines if adding the current declaration to the set
2188/// of redeclarations of the given functions causes
2189/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002190bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2191 assert(!doesThisDeclarationHaveABody() &&
2192 "Must have a declaration without a body.");
2193
2194 ASTContext &Context = getASTContext();
2195
David Blaikiebbafb8a2012-03-11 07:00:24 +00002196 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002197 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2198 // an externally visible definition.
2199 //
2200 // FIXME: What happens if gnu_inline gets added on after the first
2201 // declaration?
2202 if (!isInlineSpecified() || getStorageClassAsWritten() == SC_Extern)
2203 return false;
2204
2205 const FunctionDecl *Prev = this;
2206 bool FoundBody = false;
2207 while ((Prev = Prev->getPreviousDecl())) {
2208 FoundBody |= Prev->Body;
2209
2210 if (Prev->Body) {
2211 // If it's not the case that both 'inline' and 'extern' are
2212 // specified on the definition, then it is always externally visible.
2213 if (!Prev->isInlineSpecified() ||
2214 Prev->getStorageClassAsWritten() != SC_Extern)
2215 return false;
2216 } else if (Prev->isInlineSpecified() &&
2217 Prev->getStorageClassAsWritten() != SC_Extern) {
2218 return false;
2219 }
2220 }
2221 return FoundBody;
2222 }
2223
David Blaikiebbafb8a2012-03-11 07:00:24 +00002224 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002225 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002226
2227 // C99 6.7.4p6:
2228 // [...] If all of the file scope declarations for a function in a
2229 // translation unit include the inline function specifier without extern,
2230 // then the definition in that translation unit is an inline definition.
2231 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002232 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002233 const FunctionDecl *Prev = this;
2234 bool FoundBody = false;
2235 while ((Prev = Prev->getPreviousDecl())) {
2236 FoundBody |= Prev->Body;
2237 if (RedeclForcesDefC99(Prev))
2238 return false;
2239 }
2240 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002241}
2242
Richard Smithf3814ad2013-01-25 00:08:28 +00002243/// \brief For an inline function definition in C, or for a gnu_inline function
2244/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002245///
2246/// Inline function definitions are always available for inlining optimizations.
2247/// However, depending on the language dialect, declaration specifiers, and
2248/// attributes, the definition of an inline function may or may not be
2249/// "externally" visible to other translation units in the program.
2250///
2251/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00002252/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00002253/// inline definition becomes externally visible (C99 6.7.4p6).
2254///
2255/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2256/// definition, we use the GNU semantics for inline, which are nearly the
2257/// opposite of C99 semantics. In particular, "inline" by itself will create
2258/// an externally visible symbol, but "extern inline" will not create an
2259/// externally visible symbol.
2260bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002261 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002262 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00002263 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00002264
David Blaikiebbafb8a2012-03-11 07:00:24 +00002265 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002266 // Note: If you change the logic here, please change
2267 // doesDeclarationForceExternallyVisibleDefinition as well.
2268 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00002269 // If it's not the case that both 'inline' and 'extern' are
2270 // specified on the definition, then this inline definition is
2271 // externally visible.
2272 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
2273 return true;
2274
2275 // If any declaration is 'inline' but not 'extern', then this definition
2276 // is externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002277 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2278 Redecl != RedeclEnd;
2279 ++Redecl) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00002280 if (Redecl->isInlineSpecified() &&
2281 Redecl->getStorageClassAsWritten() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00002282 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00002283 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00002284
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002285 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002286 }
Eli Friedman1b125c32012-02-07 03:50:18 +00002287
Richard Smithf3814ad2013-01-25 00:08:28 +00002288 // The rest of this function is C-only.
2289 assert(!Context.getLangOpts().CPlusPlus &&
2290 "should not use C inline rules in C++");
2291
Douglas Gregor299d76e2009-09-13 07:46:26 +00002292 // C99 6.7.4p6:
2293 // [...] If all of the file scope declarations for a function in a
2294 // translation unit include the inline function specifier without extern,
2295 // then the definition in that translation unit is an inline definition.
2296 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2297 Redecl != RedeclEnd;
2298 ++Redecl) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002299 if (RedeclForcesDefC99(*Redecl))
2300 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002301 }
2302
2303 // C99 6.7.4p6:
2304 // An inline definition does not provide an external definition for the
2305 // function, and does not forbid an external definition in another
2306 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002307 return false;
2308}
2309
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002310/// getOverloadedOperator - Which C++ overloaded operator this
2311/// function represents, if any.
2312OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00002313 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2314 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002315 else
2316 return OO_None;
2317}
2318
Alexis Huntc88db062010-01-13 09:01:02 +00002319/// getLiteralIdentifier - The literal suffix identifier this function
2320/// represents, if any.
2321const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2322 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2323 return getDeclName().getCXXLiteralIdentifier();
2324 else
2325 return 0;
2326}
2327
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002328FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2329 if (TemplateOrSpecialization.isNull())
2330 return TK_NonTemplate;
2331 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2332 return TK_FunctionTemplate;
2333 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2334 return TK_MemberSpecialization;
2335 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2336 return TK_FunctionTemplateSpecialization;
2337 if (TemplateOrSpecialization.is
2338 <DependentFunctionTemplateSpecializationInfo*>())
2339 return TK_DependentFunctionTemplateSpecialization;
2340
David Blaikie83d382b2011-09-23 05:06:16 +00002341 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002342}
2343
Douglas Gregord801b062009-10-07 23:56:10 +00002344FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002345 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00002346 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2347
2348 return 0;
2349}
2350
Douglas Gregor06db9f52009-10-12 20:18:28 +00002351MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
2352 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2353}
2354
Douglas Gregord801b062009-10-07 23:56:10 +00002355void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002356FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2357 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00002358 TemplateSpecializationKind TSK) {
2359 assert(TemplateOrSpecialization.isNull() &&
2360 "Member function is already a specialization");
2361 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002362 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00002363 TemplateOrSpecialization = Info;
2364}
2365
Douglas Gregorafca3b42009-10-27 20:53:28 +00002366bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00002367 // If the function is invalid, it can't be implicitly instantiated.
2368 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00002369 return false;
2370
2371 switch (getTemplateSpecializationKind()) {
2372 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00002373 case TSK_ExplicitInstantiationDefinition:
2374 return false;
2375
2376 case TSK_ImplicitInstantiation:
2377 return true;
2378
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002379 // It is possible to instantiate TSK_ExplicitSpecialization kind
2380 // if the FunctionDecl has a class scope specialization pattern.
2381 case TSK_ExplicitSpecialization:
2382 return getClassScopeSpecializationPattern() != 0;
2383
Douglas Gregorafca3b42009-10-27 20:53:28 +00002384 case TSK_ExplicitInstantiationDeclaration:
2385 // Handled below.
2386 break;
2387 }
2388
2389 // Find the actual template from which we will instantiate.
2390 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002391 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00002392 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002393 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00002394
2395 // C++0x [temp.explicit]p9:
2396 // Except for inline functions, other explicit instantiation declarations
2397 // have the effect of suppressing the implicit instantiation of the entity
2398 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002399 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00002400 return true;
2401
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002402 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00002403}
2404
2405bool FunctionDecl::isTemplateInstantiation() const {
2406 switch (getTemplateSpecializationKind()) {
2407 case TSK_Undeclared:
2408 case TSK_ExplicitSpecialization:
2409 return false;
2410 case TSK_ImplicitInstantiation:
2411 case TSK_ExplicitInstantiationDeclaration:
2412 case TSK_ExplicitInstantiationDefinition:
2413 return true;
2414 }
2415 llvm_unreachable("All TSK values handled.");
2416}
Douglas Gregorafca3b42009-10-27 20:53:28 +00002417
2418FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002419 // Handle class scope explicit specialization special case.
2420 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2421 return getClassScopeSpecializationPattern();
2422
Douglas Gregorafca3b42009-10-27 20:53:28 +00002423 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2424 while (Primary->getInstantiatedFromMemberTemplate()) {
2425 // If we have hit a point where the user provided a specialization of
2426 // this template, we're done looking.
2427 if (Primary->isMemberSpecialization())
2428 break;
2429
2430 Primary = Primary->getInstantiatedFromMemberTemplate();
2431 }
2432
2433 return Primary->getTemplatedDecl();
2434 }
2435
2436 return getInstantiatedFromMemberFunction();
2437}
2438
Douglas Gregor70d83e22009-06-29 17:30:29 +00002439FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00002440 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002441 = TemplateOrSpecialization
2442 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00002443 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00002444 }
2445 return 0;
2446}
2447
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002448FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2449 return getASTContext().getClassScopeSpecializationPattern(this);
2450}
2451
Douglas Gregor70d83e22009-06-29 17:30:29 +00002452const TemplateArgumentList *
2453FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00002454 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00002455 = TemplateOrSpecialization
2456 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00002457 return Info->TemplateArguments;
2458 }
2459 return 0;
2460}
2461
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00002462const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002463FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2464 if (FunctionTemplateSpecializationInfo *Info
2465 = TemplateOrSpecialization
2466 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2467 return Info->TemplateArgumentsAsWritten;
2468 }
2469 return 0;
2470}
2471
Mike Stump11289f42009-09-09 15:08:12 +00002472void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002473FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2474 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002475 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002476 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002477 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00002478 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2479 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002480 assert(TSK != TSK_Undeclared &&
2481 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00002482 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002483 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002484 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00002485 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2486 TemplateArgs,
2487 TemplateArgsAsWritten,
2488 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002489 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00002490 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002491}
2492
John McCallb9c78482010-04-08 09:05:18 +00002493void
2494FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2495 const UnresolvedSetImpl &Templates,
2496 const TemplateArgumentListInfo &TemplateArgs) {
2497 assert(TemplateOrSpecialization.isNull());
2498 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2499 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall900d9802010-04-13 22:18:28 +00002500 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallb9c78482010-04-08 09:05:18 +00002501 void *Buffer = Context.Allocate(Size);
2502 DependentFunctionTemplateSpecializationInfo *Info =
2503 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2504 TemplateArgs);
2505 TemplateOrSpecialization = Info;
2506}
2507
2508DependentFunctionTemplateSpecializationInfo::
2509DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2510 const TemplateArgumentListInfo &TArgs)
2511 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2512
2513 d.NumTemplates = Ts.size();
2514 d.NumArgs = TArgs.size();
2515
2516 FunctionTemplateDecl **TsArray =
2517 const_cast<FunctionTemplateDecl**>(getTemplates());
2518 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2519 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2520
2521 TemplateArgumentLoc *ArgsArray =
2522 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2523 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2524 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2525}
2526
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002527TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00002528 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002529 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00002530 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00002531 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00002532 if (FTSInfo)
2533 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00002534
Douglas Gregord801b062009-10-07 23:56:10 +00002535 MemberSpecializationInfo *MSInfo
2536 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2537 if (MSInfo)
2538 return MSInfo->getTemplateSpecializationKind();
2539
2540 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002541}
2542
Mike Stump11289f42009-09-09 15:08:12 +00002543void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002544FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2545 SourceLocation PointOfInstantiation) {
2546 if (FunctionTemplateSpecializationInfo *FTSInfo
2547 = TemplateOrSpecialization.dyn_cast<
2548 FunctionTemplateSpecializationInfo*>()) {
2549 FTSInfo->setTemplateSpecializationKind(TSK);
2550 if (TSK != TSK_ExplicitSpecialization &&
2551 PointOfInstantiation.isValid() &&
2552 FTSInfo->getPointOfInstantiation().isInvalid())
2553 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2554 } else if (MemberSpecializationInfo *MSInfo
2555 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2556 MSInfo->setTemplateSpecializationKind(TSK);
2557 if (TSK != TSK_ExplicitSpecialization &&
2558 PointOfInstantiation.isValid() &&
2559 MSInfo->getPointOfInstantiation().isInvalid())
2560 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2561 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002562 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002563}
2564
2565SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00002566 if (FunctionTemplateSpecializationInfo *FTSInfo
2567 = TemplateOrSpecialization.dyn_cast<
2568 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002569 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00002570 else if (MemberSpecializationInfo *MSInfo
2571 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002572 return MSInfo->getPointOfInstantiation();
2573
2574 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00002575}
2576
Douglas Gregor6411b922009-09-11 20:15:17 +00002577bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002578 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00002579 return true;
2580
2581 // If this function was instantiated from a member function of a
2582 // class template, check whether that member function was defined out-of-line.
2583 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2584 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002585 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002586 return Definition->isOutOfLine();
2587 }
2588
2589 // If this function was instantiated from a function template,
2590 // check whether that function template was defined out-of-line.
2591 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2592 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002593 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002594 return Definition->isOutOfLine();
2595 }
2596
2597 return false;
2598}
2599
Abramo Bagnaraea947882011-03-08 16:41:52 +00002600SourceRange FunctionDecl::getSourceRange() const {
2601 return SourceRange(getOuterLocStart(), EndRangeLoc);
2602}
2603
Anna Zaks28db7ce2012-01-18 02:45:01 +00002604unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00002605 IdentifierInfo *FnInfo = getIdentifier();
2606
2607 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00002608 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002609
2610 // Builtin handling.
2611 switch (getBuiltinID()) {
2612 case Builtin::BI__builtin_memset:
2613 case Builtin::BI__builtin___memset_chk:
2614 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00002615 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00002616
2617 case Builtin::BI__builtin_memcpy:
2618 case Builtin::BI__builtin___memcpy_chk:
2619 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00002620 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002621
2622 case Builtin::BI__builtin_memmove:
2623 case Builtin::BI__builtin___memmove_chk:
2624 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00002625 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00002626
2627 case Builtin::BIstrlcpy:
Anna Zaks22122702012-01-17 00:37:07 +00002628 return Builtin::BIstrlcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002629 case Builtin::BIstrlcat:
Anna Zaks22122702012-01-17 00:37:07 +00002630 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00002631
2632 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00002633 case Builtin::BImemcmp:
2634 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002635
2636 case Builtin::BI__builtin_strncpy:
2637 case Builtin::BI__builtin___strncpy_chk:
2638 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00002639 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002640
2641 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00002642 case Builtin::BIstrncmp:
2643 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002644
2645 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00002646 case Builtin::BIstrncasecmp:
2647 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002648
2649 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00002650 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00002651 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00002652 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00002653
2654 case Builtin::BI__builtin_strndup:
2655 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00002656 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00002657
Anna Zaks314cd092012-02-01 19:08:57 +00002658 case Builtin::BI__builtin_strlen:
2659 case Builtin::BIstrlen:
2660 return Builtin::BIstrlen;
2661
Anna Zaks201d4892012-01-13 21:52:01 +00002662 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00002663 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00002664 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00002665 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00002666 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00002667 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002668 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00002669 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00002670 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002671 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002672 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00002673 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002674 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002675 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002676 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002677 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002678 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00002679 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00002680 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00002681 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00002682 else if (FnInfo->isStr("strlen"))
2683 return Builtin::BIstrlen;
Anna Zaks201d4892012-01-13 21:52:01 +00002684 }
2685 break;
2686 }
Anna Zaks22122702012-01-17 00:37:07 +00002687 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002688}
2689
Chris Lattner59a25942008-03-31 00:36:02 +00002690//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002691// FieldDecl Implementation
2692//===----------------------------------------------------------------------===//
2693
Jay Foad39c79802011-01-12 09:06:06 +00002694FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002695 SourceLocation StartLoc, SourceLocation IdLoc,
2696 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00002697 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00002698 InClassInitStyle InitStyle) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002699 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +00002700 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00002701}
2702
Douglas Gregor72172e92012-01-05 21:55:30 +00002703FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2704 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
2705 return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
Richard Smith2b013182012-06-10 03:12:00 +00002706 0, QualType(), 0, 0, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00002707}
2708
Sebastian Redl833ef452010-01-26 22:01:41 +00002709bool FieldDecl::isAnonymousStructOrUnion() const {
2710 if (!isImplicit() || getDeclName())
2711 return false;
2712
2713 if (const RecordType *Record = getType()->getAs<RecordType>())
2714 return Record->getDecl()->isAnonymousStructOrUnion();
2715
2716 return false;
2717}
2718
Richard Smithcaf33902011-10-10 18:28:20 +00002719unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2720 assert(isBitField() && "not a bitfield");
2721 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2722 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2723}
2724
John McCall4e819612011-01-20 07:57:12 +00002725unsigned FieldDecl::getFieldIndex() const {
2726 if (CachedFieldIndex) return CachedFieldIndex - 1;
2727
Richard Smithd62306a2011-11-10 06:34:14 +00002728 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002729 const RecordDecl *RD = getParent();
2730 const FieldDecl *LastFD = 0;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00002731 bool IsMsStruct = RD->isMsStruct(getASTContext());
Richard Smithd62306a2011-11-10 06:34:14 +00002732
2733 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2734 I != E; ++I, ++Index) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00002735 I->CachedFieldIndex = Index + 1;
John McCall4e819612011-01-20 07:57:12 +00002736
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002737 if (IsMsStruct) {
2738 // Zero-length bitfields following non-bitfield members are ignored.
David Blaikie40ed2972012-06-06 20:45:41 +00002739 if (getASTContext().ZeroBitfieldFollowsNonBitfield(*I, LastFD)) {
Richard Smithd62306a2011-11-10 06:34:14 +00002740 --Index;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002741 continue;
2742 }
David Blaikie40ed2972012-06-06 20:45:41 +00002743 LastFD = *I;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002744 }
John McCall4e819612011-01-20 07:57:12 +00002745 }
2746
Richard Smithd62306a2011-11-10 06:34:14 +00002747 assert(CachedFieldIndex && "failed to find field in parent");
2748 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00002749}
2750
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002751SourceRange FieldDecl::getSourceRange() const {
Abramo Bagnaraff371ac2011-08-05 08:02:55 +00002752 if (const Expr *E = InitializerOrBitWidth.getPointer())
2753 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00002754 return DeclaratorDecl::getSourceRange();
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002755}
2756
Abramo Bagnarab1cdde72012-07-02 20:35:48 +00002757void FieldDecl::setBitWidth(Expr *Width) {
2758 assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
2759 "bit width or initializer already set");
2760 InitializerOrBitWidth.setPointer(Width);
2761}
2762
Richard Smith938f40b2011-06-11 17:19:42 +00002763void FieldDecl::setInClassInitializer(Expr *Init) {
Richard Smith2b013182012-06-10 03:12:00 +00002764 assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
Richard Smith938f40b2011-06-11 17:19:42 +00002765 "bit width or initializer already set");
2766 InitializerOrBitWidth.setPointer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00002767}
2768
Sebastian Redl833ef452010-01-26 22:01:41 +00002769//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002770// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00002771//===----------------------------------------------------------------------===//
2772
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002773SourceLocation TagDecl::getOuterLocStart() const {
2774 return getTemplateOrInnerLocStart(this);
2775}
2776
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002777SourceRange TagDecl::getSourceRange() const {
2778 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002779 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002780}
2781
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002782TagDecl* TagDecl::getCanonicalDecl() {
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002783 return getFirstDeclaration();
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002784}
2785
Richard Smithdda56e42011-04-15 14:24:37 +00002786void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2787 TypedefNameDeclOrQualifier = TDD;
Douglas Gregora72a4e32010-05-19 18:39:18 +00002788 if (TypeForDecl)
Rafael Espindola19de5612013-01-12 06:42:30 +00002789 const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
2790 ClearLinkageCache();
Douglas Gregora72a4e32010-05-19 18:39:18 +00002791}
2792
Douglas Gregordee1be82009-01-17 00:42:38 +00002793void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002794 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00002795
David Blaikie095deba2012-11-14 01:52:05 +00002796 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
John McCall67da35c2010-02-04 22:26:26 +00002797 struct CXXRecordDecl::DefinitionData *Data =
2798 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
John McCall93cc7322010-03-26 21:56:38 +00002799 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2800 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00002801 }
Douglas Gregordee1be82009-01-17 00:42:38 +00002802}
2803
2804void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00002805 assert((!isa<CXXRecordDecl>(this) ||
2806 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2807 "definition completed but not started");
2808
John McCallf937c022011-10-07 06:10:15 +00002809 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002810 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00002811
2812 if (ASTMutationListener *L = getASTMutationListener())
2813 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00002814}
2815
John McCallf937c022011-10-07 06:10:15 +00002816TagDecl *TagDecl::getDefinition() const {
2817 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002818 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002819
2820 // If it's possible for us to have an out-of-date definition, check now.
2821 if (MayHaveOutOfDateDef) {
2822 if (IdentifierInfo *II = getIdentifier()) {
2823 if (II->isOutOfDate()) {
2824 updateOutOfDate(*II);
2825 }
2826 }
2827 }
2828
Andrew Trickba266ee2010-10-19 21:54:32 +00002829 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2830 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00002831
2832 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002833 R != REnd; ++R)
John McCallf937c022011-10-07 06:10:15 +00002834 if (R->isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002835 return *R;
Mike Stump11289f42009-09-09 15:08:12 +00002836
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002837 return 0;
Ted Kremenek21475702008-09-05 17:16:31 +00002838}
2839
Douglas Gregor14454802011-02-25 02:25:35 +00002840void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2841 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00002842 // Make sure the extended qualifier info is allocated.
2843 if (!hasExtInfo())
Richard Smithdda56e42011-04-15 14:24:37 +00002844 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00002845 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00002846 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002847 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00002848 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00002849 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00002850 if (getExtInfo()->NumTemplParamLists == 0) {
2851 getASTContext().Deallocate(getExtInfo());
Richard Smithdda56e42011-04-15 14:24:37 +00002852 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002853 }
2854 else
2855 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00002856 }
2857 }
2858}
2859
Abramo Bagnara60804e12011-03-18 15:16:37 +00002860void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2861 unsigned NumTPLists,
2862 TemplateParameterList **TPLists) {
2863 assert(NumTPLists > 0);
2864 // Make sure the extended decl info is allocated.
2865 if (!hasExtInfo())
2866 // Allocate external info struct.
Richard Smithdda56e42011-04-15 14:24:37 +00002867 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002868 // Set the template parameter lists info.
2869 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2870}
2871
Ted Kremenek21475702008-09-05 17:16:31 +00002872//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002873// EnumDecl Implementation
2874//===----------------------------------------------------------------------===//
2875
David Blaikie68e081d2011-12-20 02:48:34 +00002876void EnumDecl::anchor() { }
2877
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002878EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2879 SourceLocation StartLoc, SourceLocation IdLoc,
2880 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002881 EnumDecl *PrevDecl, bool IsScoped,
2882 bool IsScopedUsingClassTag, bool IsFixed) {
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002883 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002884 IsScoped, IsScopedUsingClassTag, IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002885 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00002886 C.getTypeDeclType(Enum, PrevDecl);
2887 return Enum;
2888}
2889
Douglas Gregor72172e92012-01-05 21:55:30 +00002890EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2891 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002892 EnumDecl *Enum = new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(),
2893 0, 0, false, false, false);
2894 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
2895 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00002896}
2897
Douglas Gregord5058122010-02-11 01:19:42 +00002898void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00002899 QualType NewPromotionType,
2900 unsigned NumPositiveBits,
2901 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00002902 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00002903 if (!IntegerType)
2904 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00002905 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00002906 setNumPositiveBits(NumPositiveBits);
2907 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00002908 TagDecl::completeDefinition();
2909}
2910
Richard Smith7d137e32012-03-23 03:33:32 +00002911TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
2912 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2913 return MSI->getTemplateSpecializationKind();
2914
2915 return TSK_Undeclared;
2916}
2917
2918void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2919 SourceLocation PointOfInstantiation) {
2920 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
2921 assert(MSI && "Not an instantiated member enumeration?");
2922 MSI->setTemplateSpecializationKind(TSK);
2923 if (TSK != TSK_ExplicitSpecialization &&
2924 PointOfInstantiation.isValid() &&
2925 MSI->getPointOfInstantiation().isInvalid())
2926 MSI->setPointOfInstantiation(PointOfInstantiation);
2927}
2928
Richard Smith4b38ded2012-03-14 23:13:10 +00002929EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
2930 if (SpecializationInfo)
2931 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
2932
2933 return 0;
2934}
2935
2936void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
2937 TemplateSpecializationKind TSK) {
2938 assert(!SpecializationInfo && "Member enum is already a specialization");
2939 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
2940}
2941
Sebastian Redl833ef452010-01-26 22:01:41 +00002942//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002943// RecordDecl Implementation
2944//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00002945
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002946RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2947 SourceLocation StartLoc, SourceLocation IdLoc,
2948 IdentifierInfo *Id, RecordDecl *PrevDecl)
2949 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00002950 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002951 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002952 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00002953 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002954 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00002955 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00002956}
2957
Jay Foad39c79802011-01-12 09:06:06 +00002958RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002959 SourceLocation StartLoc, SourceLocation IdLoc,
2960 IdentifierInfo *Id, RecordDecl* PrevDecl) {
2961 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
2962 PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002963 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
2964
Ted Kremenek21475702008-09-05 17:16:31 +00002965 C.getTypeDeclType(R, PrevDecl);
2966 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00002967}
2968
Douglas Gregor72172e92012-01-05 21:55:30 +00002969RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
2970 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002971 RecordDecl *R = new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
2972 SourceLocation(), 0, 0);
2973 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
2974 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00002975}
2976
Douglas Gregordfcad112009-03-25 15:59:44 +00002977bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00002978 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00002979 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
2980}
2981
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002982RecordDecl::field_iterator RecordDecl::field_begin() const {
2983 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
2984 LoadFieldsFromExternalStorage();
2985
2986 return field_iterator(decl_iterator(FirstDecl));
2987}
2988
Douglas Gregorb11aad82011-02-19 18:51:44 +00002989/// completeDefinition - Notes that the definition of this type is now
2990/// complete.
2991void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00002992 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00002993 TagDecl::completeDefinition();
2994}
2995
Eli Friedman9ee2d0472012-10-12 23:29:20 +00002996/// isMsStruct - Get whether or not this record uses ms_struct layout.
2997/// This which can be turned on with an attribute, pragma, or the
2998/// -mms-bitfields command-line option.
2999bool RecordDecl::isMsStruct(const ASTContext &C) const {
3000 return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3001}
3002
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003003static bool isFieldOrIndirectField(Decl::Kind K) {
3004 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3005}
3006
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003007void RecordDecl::LoadFieldsFromExternalStorage() const {
3008 ExternalASTSource *Source = getASTContext().getExternalSource();
3009 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3010
3011 // Notify that we have a RecordDecl doing some initialization.
3012 ExternalASTSource::Deserializing TheFields(Source);
3013
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003014 SmallVector<Decl*, 64> Decls;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003015 LoadedFieldsFromExternalStorage = true;
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003016 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3017 Decls)) {
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003018 case ELR_Success:
3019 break;
3020
3021 case ELR_AlreadyLoaded:
3022 case ELR_Failure:
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003023 return;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003024 }
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003025
3026#ifndef NDEBUG
3027 // Check that all decls we got were FieldDecls.
3028 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003029 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003030#endif
3031
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003032 if (Decls.empty())
3033 return;
3034
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003035 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
3036 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003037}
3038
Steve Naroff415d3d52008-10-08 17:01:13 +00003039//===----------------------------------------------------------------------===//
3040// BlockDecl Implementation
3041//===----------------------------------------------------------------------===//
3042
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003043void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Steve Naroffc4b30e52009-03-13 16:56:44 +00003044 assert(ParamInfo == 0 && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00003045
Steve Naroffc4b30e52009-03-13 16:56:44 +00003046 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003047 if (!NewParamInfo.empty()) {
3048 NumParams = NewParamInfo.size();
3049 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3050 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003051 }
3052}
3053
John McCall351762c2011-02-07 10:33:21 +00003054void BlockDecl::setCaptures(ASTContext &Context,
3055 const Capture *begin,
3056 const Capture *end,
3057 bool capturesCXXThis) {
John McCallc63de662011-02-02 13:00:07 +00003058 CapturesCXXThis = capturesCXXThis;
3059
3060 if (begin == end) {
John McCall351762c2011-02-07 10:33:21 +00003061 NumCaptures = 0;
3062 Captures = 0;
John McCallc63de662011-02-02 13:00:07 +00003063 return;
3064 }
3065
John McCall351762c2011-02-07 10:33:21 +00003066 NumCaptures = end - begin;
3067
3068 // Avoid new Capture[] because we don't want to provide a default
3069 // constructor.
3070 size_t allocationSize = NumCaptures * sizeof(Capture);
3071 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3072 memcpy(buffer, begin, allocationSize);
3073 Captures = static_cast<Capture*>(buffer);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003074}
Sebastian Redl833ef452010-01-26 22:01:41 +00003075
John McCallce45f882011-06-15 22:51:16 +00003076bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3077 for (capture_const_iterator
3078 i = capture_begin(), e = capture_end(); i != e; ++i)
3079 // Only auto vars can be captured, so no redeclaration worries.
3080 if (i->getVariable() == variable)
3081 return true;
3082
3083 return false;
3084}
3085
Douglas Gregor70226da2010-12-21 16:27:07 +00003086SourceRange BlockDecl::getSourceRange() const {
3087 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3088}
Sebastian Redl833ef452010-01-26 22:01:41 +00003089
3090//===----------------------------------------------------------------------===//
3091// Other Decl Allocation/Deallocation Method Implementations
3092//===----------------------------------------------------------------------===//
3093
David Blaikie68e081d2011-12-20 02:48:34 +00003094void TranslationUnitDecl::anchor() { }
3095
Sebastian Redl833ef452010-01-26 22:01:41 +00003096TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
3097 return new (C) TranslationUnitDecl(C);
3098}
3099
David Blaikie68e081d2011-12-20 02:48:34 +00003100void LabelDecl::anchor() { }
3101
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003102LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003103 SourceLocation IdentL, IdentifierInfo *II) {
3104 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
3105}
3106
3107LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3108 SourceLocation IdentL, IdentifierInfo *II,
3109 SourceLocation GnuLabelL) {
3110 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
3111 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003112}
3113
Douglas Gregor72172e92012-01-05 21:55:30 +00003114LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3115 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
3116 return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00003117}
3118
David Blaikie68e081d2011-12-20 02:48:34 +00003119void ValueDecl::anchor() { }
3120
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003121bool ValueDecl::isWeak() const {
3122 for (attr_iterator I = attr_begin(), E = attr_end(); I != E; ++I)
3123 if (isa<WeakAttr>(*I) || isa<WeakRefAttr>(*I))
3124 return true;
3125
3126 return isWeakImported();
3127}
3128
David Blaikie68e081d2011-12-20 02:48:34 +00003129void ImplicitParamDecl::anchor() { }
3130
Sebastian Redl833ef452010-01-26 22:01:41 +00003131ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003132 SourceLocation IdLoc,
3133 IdentifierInfo *Id,
3134 QualType Type) {
3135 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00003136}
3137
Douglas Gregor72172e92012-01-05 21:55:30 +00003138ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
3139 unsigned ID) {
3140 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
3141 return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
3142}
3143
Sebastian Redl833ef452010-01-26 22:01:41 +00003144FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003145 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003146 const DeclarationNameInfo &NameInfo,
3147 QualType T, TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003148 StorageClass SC, StorageClass SCAsWritten,
Douglas Gregorff76cb92010-12-09 16:59:22 +00003149 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00003150 bool hasWrittenPrototype,
3151 bool isConstexprSpecified) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003152 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
3153 T, TInfo, SC, SCAsWritten,
Richard Smitha77a0a62011-08-15 21:04:07 +00003154 isInlineSpecified,
3155 isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00003156 New->HasWrittenPrototype = hasWrittenPrototype;
3157 return New;
3158}
3159
Douglas Gregor72172e92012-01-05 21:55:30 +00003160FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3161 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
3162 return new (Mem) FunctionDecl(Function, 0, SourceLocation(),
3163 DeclarationNameInfo(), QualType(), 0,
3164 SC_None, SC_None, false, false);
3165}
3166
Sebastian Redl833ef452010-01-26 22:01:41 +00003167BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3168 return new (C) BlockDecl(DC, L);
3169}
3170
Douglas Gregor72172e92012-01-05 21:55:30 +00003171BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3172 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
3173 return new (Mem) BlockDecl(0, SourceLocation());
3174}
3175
Sebastian Redl833ef452010-01-26 22:01:41 +00003176EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3177 SourceLocation L,
3178 IdentifierInfo *Id, QualType T,
3179 Expr *E, const llvm::APSInt &V) {
3180 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
3181}
3182
Douglas Gregor72172e92012-01-05 21:55:30 +00003183EnumConstantDecl *
3184EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3185 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
3186 return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
3187 llvm::APSInt());
3188}
3189
David Blaikie68e081d2011-12-20 02:48:34 +00003190void IndirectFieldDecl::anchor() { }
3191
Benjamin Kramer39593702010-11-21 14:11:41 +00003192IndirectFieldDecl *
3193IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3194 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3195 unsigned CHS) {
Francois Pichet783dd6e2010-11-21 06:08:52 +00003196 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
3197}
3198
Douglas Gregor72172e92012-01-05 21:55:30 +00003199IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3200 unsigned ID) {
3201 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
3202 return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
3203 QualType(), 0, 0);
3204}
3205
Douglas Gregorbe996932010-09-01 20:41:53 +00003206SourceRange EnumConstantDecl::getSourceRange() const {
3207 SourceLocation End = getLocation();
3208 if (Init)
3209 End = Init->getLocEnd();
3210 return SourceRange(getLocation(), End);
3211}
3212
David Blaikie68e081d2011-12-20 02:48:34 +00003213void TypeDecl::anchor() { }
3214
Sebastian Redl833ef452010-01-26 22:01:41 +00003215TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003216 SourceLocation StartLoc, SourceLocation IdLoc,
3217 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
3218 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00003219}
3220
David Blaikie68e081d2011-12-20 02:48:34 +00003221void TypedefNameDecl::anchor() { }
3222
Douglas Gregor72172e92012-01-05 21:55:30 +00003223TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3224 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
3225 return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3226}
3227
Richard Smithdda56e42011-04-15 14:24:37 +00003228TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3229 SourceLocation StartLoc,
3230 SourceLocation IdLoc, IdentifierInfo *Id,
3231 TypeSourceInfo *TInfo) {
3232 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
3233}
3234
Douglas Gregor72172e92012-01-05 21:55:30 +00003235TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3236 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
3237 return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3238}
3239
Abramo Bagnaraea947882011-03-08 16:41:52 +00003240SourceRange TypedefDecl::getSourceRange() const {
3241 SourceLocation RangeEnd = getLocation();
3242 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3243 if (typeIsPostfix(TInfo->getType()))
3244 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3245 }
3246 return SourceRange(getLocStart(), RangeEnd);
3247}
3248
Richard Smithdda56e42011-04-15 14:24:37 +00003249SourceRange TypeAliasDecl::getSourceRange() const {
3250 SourceLocation RangeEnd = getLocStart();
3251 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3252 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3253 return SourceRange(getLocStart(), RangeEnd);
3254}
3255
David Blaikie68e081d2011-12-20 02:48:34 +00003256void FileScopeAsmDecl::anchor() { }
3257
Sebastian Redl833ef452010-01-26 22:01:41 +00003258FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00003259 StringLiteral *Str,
3260 SourceLocation AsmLoc,
3261 SourceLocation RParenLoc) {
3262 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00003263}
Douglas Gregorba345522011-12-02 23:23:56 +00003264
Douglas Gregor72172e92012-01-05 21:55:30 +00003265FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
3266 unsigned ID) {
3267 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
3268 return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
3269}
3270
Douglas Gregorba345522011-12-02 23:23:56 +00003271//===----------------------------------------------------------------------===//
3272// ImportDecl Implementation
3273//===----------------------------------------------------------------------===//
3274
3275/// \brief Retrieve the number of module identifiers needed to name the given
3276/// module.
3277static unsigned getNumModuleIdentifiers(Module *Mod) {
3278 unsigned Result = 1;
3279 while (Mod->Parent) {
3280 Mod = Mod->Parent;
3281 ++Result;
3282 }
3283 return Result;
3284}
3285
Douglas Gregor22d09742012-01-03 18:04:46 +00003286ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003287 Module *Imported,
3288 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00003289 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003290 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003291{
3292 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3293 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3294 memcpy(StoredLocs, IdentifierLocs.data(),
3295 IdentifierLocs.size() * sizeof(SourceLocation));
3296}
3297
Douglas Gregor22d09742012-01-03 18:04:46 +00003298ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003299 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00003300 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003301 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003302{
3303 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3304}
3305
3306ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003307 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00003308 ArrayRef<SourceLocation> IdentifierLocs) {
3309 void *Mem = C.Allocate(sizeof(ImportDecl) +
3310 IdentifierLocs.size() * sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00003311 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00003312}
3313
3314ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003315 SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003316 Module *Imported,
3317 SourceLocation EndLoc) {
3318 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00003319 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00003320 Import->setImplicit();
3321 return Import;
3322}
3323
Douglas Gregor72172e92012-01-05 21:55:30 +00003324ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3325 unsigned NumLocations) {
3326 void *Mem = AllocateDeserializedDecl(C, ID,
3327 (sizeof(ImportDecl) +
3328 NumLocations * sizeof(SourceLocation)));
Douglas Gregorba345522011-12-02 23:23:56 +00003329 return new (Mem) ImportDecl(EmptyShell());
3330}
3331
3332ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3333 if (!ImportedAndComplete.getInt())
3334 return ArrayRef<SourceLocation>();
3335
3336 const SourceLocation *StoredLocs
3337 = reinterpret_cast<const SourceLocation *>(this + 1);
3338 return ArrayRef<SourceLocation>(StoredLocs,
3339 getNumModuleIdentifiers(getImportedModule()));
3340}
3341
3342SourceRange ImportDecl::getSourceRange() const {
3343 if (!ImportedAndComplete.getInt())
3344 return SourceRange(getLocation(),
3345 *reinterpret_cast<const SourceLocation *>(this + 1));
3346
3347 return SourceRange(getLocation(), getIdentifierLocs().back());
3348}