blob: c2e1a848c138eedff237637fddc7cbe6168b89a4 [file] [log] [blame]
Chris Lattnera11999d2006-10-15 22:34:45 +00001//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera11999d2006-10-15 22:34:45 +00007//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidis63018842008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Chris Lattnera11999d2006-10-15 22:34:45 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
Chris Lattnera7b32872008-03-15 06:12:44 +000015#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000021#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000023#include "clang/AST/PrettyPrinter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000024#include "clang/AST/Stmt.h"
25#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000027#include "clang/Basic/IdentifierTable.h"
Douglas Gregorba345522011-12-02 23:23:56 +000028#include "clang/Basic/Module.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000029#include "clang/Basic/Specifiers.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000030#include "clang/Basic/TargetInfo.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000031#include "llvm/Support/ErrorHandling.h"
David Blaikie9c70e042011-09-21 18:16:56 +000032#include <algorithm>
33
Chris Lattner6d9a6852006-10-25 05:11:20 +000034using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000035
Richard Smith0b87e072013-10-07 08:02:11 +000036Decl *clang::getPrimaryMergedDecl(Decl *D) {
37 return D->getASTContext().getPrimaryMergedDecl(D);
38}
39
Chris Lattner88f70d62008-03-15 05:43:15 +000040//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000041// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000042//===----------------------------------------------------------------------===//
43
John McCalldf25c432013-02-16 00:17:33 +000044// Visibility rules aren't rigorously externally specified, but here
45// are the basic principles behind what we implement:
46//
47// 1. An explicit visibility attribute is generally a direct expression
48// of the user's intent and should be honored. Only the innermost
49// visibility attribute applies. If no visibility attribute applies,
50// global visibility settings are considered.
51//
52// 2. There is one caveat to the above: on or in a template pattern,
53// an explicit visibility attribute is just a default rule, and
54// visibility can be decreased by the visibility of template
55// arguments. But this, too, has an exception: an attribute on an
56// explicit specialization or instantiation causes all the visibility
57// restrictions of the template arguments to be ignored.
58//
59// 3. A variable that does not otherwise have explicit visibility can
60// be restricted by the visibility of its type.
61//
62// 4. A visibility restriction is explicit if it comes from an
63// attribute (or something like it), not a global visibility setting.
64// When emitting a reference to an external symbol, visibility
65// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +000066//
67// 5. When computing the visibility of a non-type, including a
68// non-type member of a class, only non-type visibility restrictions
69// are considered: the 'visibility' attribute, global value-visibility
70// settings, and a few special cases like __private_extern.
71//
72// 6. When computing the visibility of a type, including a type member
73// of a class, only type visibility restrictions are considered:
74// the 'type_visibility' attribute and global type-visibility settings.
75// However, a 'visibility' attribute counts as a 'type_visibility'
76// attribute on any declaration that only has the former.
77//
78// The visibility of a "secondary" entity, like a template argument,
79// is computed using the kind of that entity, not the kind of the
80// primary entity for which we are computing visibility. For example,
81// the visibility of a specialization of either of these templates:
82// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
83// template <class T, bool (&compare)(T, X)> class matcher;
84// is restricted according to the type visibility of the argument 'T',
85// the type visibility of 'bool(&)(T,X)', and the value visibility of
86// the argument function 'compare'. That 'has_match' is a value
87// and 'matcher' is a type only matters when looking for attributes
88// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +000089
John McCall5f46c482013-02-21 23:42:58 +000090const unsigned IgnoreExplicitVisibilityBit = 2;
Rafael Espindola9551d3b2013-05-28 19:43:11 +000091const unsigned IgnoreAllVisibilityBit = 4;
John McCall5f46c482013-02-21 23:42:58 +000092
John McCalldf25c432013-02-16 00:17:33 +000093/// Kinds of LV computation. The linkage side of the computation is
94/// always the same, but different things can change how visibility is
95/// computed.
96enum LVComputationKind {
John McCall5f46c482013-02-21 23:42:58 +000097 /// Do an LV computation for, ultimately, a type.
98 /// Visibility may be restricted by type visibility settings and
99 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000100 LVForType = NamedDecl::VisibilityForType,
John McCalldf25c432013-02-16 00:17:33 +0000101
John McCall5f46c482013-02-21 23:42:58 +0000102 /// Do an LV computation for, ultimately, a non-type declaration.
103 /// Visibility may be restricted by value visibility settings and
104 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000105 LVForValue = NamedDecl::VisibilityForValue,
106
John McCall5f46c482013-02-21 23:42:58 +0000107 /// Do an LV computation for, ultimately, a type that already has
108 /// some sort of explicit visibility. Visibility may only be
109 /// restricted by the visibility of template arguments.
110 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
John McCalld041a9b2013-02-20 01:54:26 +0000111
John McCall5f46c482013-02-21 23:42:58 +0000112 /// Do an LV computation for, ultimately, a non-type declaration
113 /// that already has some sort of explicit visibility. Visibility
114 /// may only be restricted by the visibility of template arguments.
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000115 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
116
117 /// Do an LV computation when we only care about the linkage.
118 LVForLinkageOnly =
119 LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
John McCalldf25c432013-02-16 00:17:33 +0000120};
121
John McCalld041a9b2013-02-20 01:54:26 +0000122/// Does this computation kind permit us to consider additional
123/// visibility settings from attributes and the like?
124static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000125 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
John McCalld041a9b2013-02-20 01:54:26 +0000126}
127
128/// Given an LVComputationKind, return one of the same type/value sort
129/// that records that it already has explicit visibility.
130static LVComputationKind
131withExplicitVisibilityAlready(LVComputationKind oldKind) {
132 LVComputationKind newKind =
John McCall5f46c482013-02-21 23:42:58 +0000133 static_cast<LVComputationKind>(unsigned(oldKind) |
134 IgnoreExplicitVisibilityBit);
John McCalld041a9b2013-02-20 01:54:26 +0000135 assert(oldKind != LVForType || newKind == LVForExplicitType);
136 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
137 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
138 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
139 return newKind;
140}
141
David Blaikie05785d12013-02-20 22:23:23 +0000142static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
143 LVComputationKind kind) {
John McCalld041a9b2013-02-20 01:54:26 +0000144 assert(!hasExplicitVisibilityAlready(kind) &&
145 "asking for explicit visibility when we shouldn't be");
146 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
147}
148
John McCalldf25c432013-02-16 00:17:33 +0000149/// Is the given declaration a "type" or a "value" for the purposes of
150/// visibility computation?
151static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000152 return isa<TypeDecl>(D) ||
153 isa<ClassTemplateDecl>(D) ||
154 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000155}
156
John McCall5f46c482013-02-21 23:42:58 +0000157/// Does the given declaration have member specialization information,
158/// and if so, is it an explicit specialization?
159template <class T> static typename
Benjamin Kramered2f4762014-03-07 14:30:23 +0000160std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-02-21 23:42:58 +0000161isExplicitMemberSpecialization(const T *D) {
162 if (const MemberSpecializationInfo *member =
163 D->getMemberSpecializationInfo()) {
164 return member->isExplicitSpecialization();
165 }
166 return false;
167}
168
169/// For templates, this question is easier: a member template can't be
170/// explicitly instantiated, so there's a single bit indicating whether
171/// or not this is an explicit member specialization.
172static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
173 return D->isMemberSpecialization();
174}
175
John McCalld041a9b2013-02-20 01:54:26 +0000176/// Given a visibility attribute, return the explicit visibility
177/// associated with it.
178template <class T>
179static Visibility getVisibilityFromAttr(const T *attr) {
180 switch (attr->getVisibility()) {
181 case T::Default:
182 return DefaultVisibility;
183 case T::Hidden:
184 return HiddenVisibility;
185 case T::Protected:
186 return ProtectedVisibility;
187 }
188 llvm_unreachable("bad visibility kind");
189}
190
John McCalldf25c432013-02-16 00:17:33 +0000191/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000192static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000193 NamedDecl::ExplicitVisibilityKind kind) {
194 // If we're ultimately computing the visibility of a type, look for
195 // a 'type_visibility' attribute before looking for 'visibility'.
196 if (kind == NamedDecl::VisibilityForType) {
197 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
198 return getVisibilityFromAttr(A);
199 }
200 }
201
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000202 // If this declaration has an explicit visibility attribute, use it.
203 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000204 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000205 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000206
207 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
208 // implies visibility(default).
Douglas Gregore8bbc122011-09-02 00:18:52 +0000209 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000210 for (const auto *A : D->specific_attrs<AvailabilityAttr>())
211 if (A->getPlatform()->getName().equals("macosx"))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000212 return DefaultVisibility;
213 }
214
David Blaikie7a30dc52013-02-21 01:47:18 +0000215 return None;
John McCall457a04e2010-10-22 21:05:15 +0000216}
217
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000218static LinkageInfo
219getLVForType(const Type &T, LVComputationKind computation) {
220 if (computation == LVForLinkageOnly)
221 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
222 return T.getLinkageAndVisibility();
223}
224
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000225/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000226/// template parameter list. For visibility purposes, template
227/// parameters are part of the signature of a template.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000228static LinkageInfo
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000229getLVForTemplateParameterList(const TemplateParameterList *params,
230 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000231 LinkageInfo LV;
232 for (TemplateParameterList::const_iterator P = params->begin(),
233 PEnd = params->end();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000234 P != PEnd; ++P) {
John McCalldf25c432013-02-16 00:17:33 +0000235
236 // Template type parameters are the most common and never
237 // contribute to visibility, pack or not.
238 if (isa<TemplateTypeParmDecl>(*P))
239 continue;
240
241 // Non-type template parameters can be restricted by the value type, e.g.
242 // template <enum X> class A { ... };
243 // We have to be careful here, though, because we can be dealing with
244 // dependent types.
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000245 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
John McCalldf25c432013-02-16 00:17:33 +0000246 // Handle the non-pack case first.
247 if (!NTTP->isExpandedParameterPack()) {
248 if (!NTTP->getType()->isDependentType()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000249 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000250 }
251 continue;
252 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000253
John McCalldf25c432013-02-16 00:17:33 +0000254 // Look at all the types in an expanded pack.
255 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
256 QualType type = NTTP->getExpansionType(i);
257 if (!type->isDependentType())
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000258 LV.merge(type->getLinkageAndVisibility());
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000259 }
John McCalldf25c432013-02-16 00:17:33 +0000260 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000261 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000262
John McCalldf25c432013-02-16 00:17:33 +0000263 // Template template parameters can be restricted by their
264 // template parameters, recursively.
265 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
266
267 // Handle the non-pack case first.
268 if (!TTP->isExpandedParameterPack()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000269 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
270 computation));
John McCalldf25c432013-02-16 00:17:33 +0000271 continue;
272 }
273
274 // Look at all expansions in an expanded pack.
275 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
276 i != n; ++i) {
277 LV.merge(getLVForTemplateParameterList(
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000278 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000279 }
280 }
281
John McCall457a04e2010-10-22 21:05:15 +0000282 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000283}
284
Rafael Espindola19de5612013-01-12 06:42:30 +0000285/// getLVForDecl - Get the linkage and visibility for the given declaration.
John McCalldf25c432013-02-16 00:17:33 +0000286static LinkageInfo getLVForDecl(const NamedDecl *D,
287 LVComputationKind computation);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000288
Eli Friedman7e346a82013-07-01 20:22:57 +0000289static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
290 const Decl *Ret = NULL;
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000291 const DeclContext *DC = D->getDeclContext();
292 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman7e346a82013-07-01 20:22:57 +0000293 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
294 Ret = cast<Decl>(DC);
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000295 DC = DC->getParent();
296 }
297 return Ret;
298}
299
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000300/// \brief Get the most restrictive linkage for the types and
301/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000302///
303/// Note that we don't take an LVComputationKind because we always
304/// want to honor the visibility of template arguments in the same way.
305static LinkageInfo
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000306getLVForTemplateArgumentList(ArrayRef<TemplateArgument> args,
307 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000308 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000309
John McCalldf25c432013-02-16 00:17:33 +0000310 for (unsigned i = 0, e = args.size(); i != e; ++i) {
311 const TemplateArgument &arg = args[i];
312 switch (arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000313 case TemplateArgument::Null:
314 case TemplateArgument::Integral:
315 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000316 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000317
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000318 case TemplateArgument::Type:
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000319 LV.merge(getLVForType(*arg.getAsType(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000320 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000321
322 case TemplateArgument::Declaration:
John McCalldf25c432013-02-16 00:17:33 +0000323 if (NamedDecl *ND = dyn_cast<NamedDecl>(arg.getAsDecl())) {
324 assert(!usesTypeVisibility(ND));
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000325 LV.merge(getLVForDecl(ND, computation));
John McCalldf25c432013-02-16 00:17:33 +0000326 }
327 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +0000328
329 case TemplateArgument::NullPtr:
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000330 LV.merge(arg.getNullPtrType()->getLinkageAndVisibility());
John McCalldf25c432013-02-16 00:17:33 +0000331 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000332
333 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000334 case TemplateArgument::TemplateExpansion:
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000335 if (TemplateDecl *Template
John McCalldf25c432013-02-16 00:17:33 +0000336 = arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000337 LV.merge(getLVForDecl(Template, computation));
John McCalldf25c432013-02-16 00:17:33 +0000338 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000339
340 case TemplateArgument::Pack:
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000341 LV.merge(getLVForTemplateArgumentList(arg.getPackAsArray(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000342 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000343 }
John McCalldf25c432013-02-16 00:17:33 +0000344 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000345 }
346
John McCall457a04e2010-10-22 21:05:15 +0000347 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000348}
349
Rafael Espindola2f869a32012-01-14 00:30:36 +0000350static LinkageInfo
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000351getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
352 LVComputationKind computation) {
353 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall8823c652010-08-13 08:35:10 +0000354}
355
John McCall5f46c482013-02-21 23:42:58 +0000356static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
357 const FunctionTemplateSpecializationInfo *specInfo) {
358 // Include visibility from the template parameters and arguments
359 // only if this is not an explicit instantiation or specialization
360 // with direct explicit visibility. (Implicit instantiations won't
361 // have a direct attribute.)
362 if (!specInfo->isExplicitInstantiationOrSpecialization())
363 return true;
364
365 return !fn->hasAttr<VisibilityAttr>();
366}
367
John McCalldf25c432013-02-16 00:17:33 +0000368/// Merge in template-related linkage and visibility for the given
369/// function template specialization.
370///
371/// We don't need a computation kind here because we can assume
372/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000373///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000374/// \param[out] LV the computation to use for the parent
John McCall5f46c482013-02-21 23:42:58 +0000375static void
376mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000377 const FunctionTemplateSpecializationInfo *specInfo,
378 LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000379 bool considerVisibility =
380 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000381
382 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000383 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000384 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000385 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000386 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
387
388 // Merge information from the template arguments.
389 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000390 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCalldf25c432013-02-16 00:17:33 +0000391 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000392}
393
John McCall5f46c482013-02-21 23:42:58 +0000394/// Does the given declaration have a direct visibility attribute
395/// that would match the given rules?
396static bool hasDirectVisibilityAttribute(const NamedDecl *D,
397 LVComputationKind computation) {
398 switch (computation) {
399 case LVForType:
400 case LVForExplicitType:
401 if (D->hasAttr<TypeVisibilityAttr>())
402 return true;
403 // fallthrough
404 case LVForValue:
405 case LVForExplicitValue:
406 if (D->hasAttr<VisibilityAttr>())
407 return true;
408 return false;
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000409 case LVForLinkageOnly:
410 return false;
John McCall5f46c482013-02-21 23:42:58 +0000411 }
412 llvm_unreachable("bad visibility computation kind");
413}
414
John McCalld041a9b2013-02-20 01:54:26 +0000415/// Should we consider visibility associated with the template
416/// arguments and parameters of the given class template specialization?
417static bool shouldConsiderTemplateVisibility(
418 const ClassTemplateSpecializationDecl *spec,
419 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000420 // Include visibility from the template parameters and arguments
421 // only if this is not an explicit instantiation or specialization
422 // with direct explicit visibility (and note that implicit
423 // instantiations won't have a direct attribute).
424 //
425 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000426 // for an explicit specialization when computing the visibility of a
427 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000428 //
429 // This is a bit complex; let's unpack it.
430 //
431 // An explicit class specialization is an independent, top-level
432 // declaration. As such, if it or any of its members has an
433 // explicit visibility attribute, that must directly express the
434 // user's intent, and we should honor it. The same logic applies to
435 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000436
437 // Fast path: if this is not an explicit instantiation or
438 // specialization, we always want to consider template-related
439 // visibility restrictions.
440 if (!spec->isExplicitInstantiationOrSpecialization())
441 return true;
442
443 // This is the 'member thereof' check.
444 if (spec->isExplicitSpecialization() &&
445 hasExplicitVisibilityAlready(computation))
446 return false;
447
John McCall5f46c482013-02-21 23:42:58 +0000448 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000449}
450
451/// Merge in template-related linkage and visibility for the given
452/// class template specialization.
453static void mergeTemplateLV(LinkageInfo &LV,
454 const ClassTemplateSpecializationDecl *spec,
455 LVComputationKind computation) {
456 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000457
458 // Merge information from the template parameters, but ignore
459 // visibility if we're only considering template arguments.
460
John McCalld041a9b2013-02-20 01:54:26 +0000461 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000462 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000463 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000464 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000465 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000466
467 // Merge information from the template arguments. We ignore
468 // template-argument visibility if we've got an explicit
469 // instantiation with a visibility attribute.
470 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000471 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000472 if (considerVisibility)
473 LV.mergeVisibility(argsLV);
474 LV.mergeExternalVisibility(argsLV);
John McCallb8c604a2011-06-27 23:06:04 +0000475}
476
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000477static bool useInlineVisibilityHidden(const NamedDecl *D) {
478 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000479 const LangOptions &Opts = D->getASTContext().getLangOpts();
480 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000481 return false;
482
483 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
484 if (!FD)
485 return false;
486
487 TemplateSpecializationKind TSK = TSK_Undeclared;
488 if (FunctionTemplateSpecializationInfo *spec
489 = FD->getTemplateSpecializationInfo()) {
490 TSK = spec->getTemplateSpecializationKind();
491 } else if (MemberSpecializationInfo *MSI =
492 FD->getMemberSpecializationInfo()) {
493 TSK = MSI->getTemplateSpecializationKind();
494 }
495
496 const FunctionDecl *Def = 0;
497 // InlineVisibilityHidden only applies to definitions, and
498 // isInlined() only gives meaningful answers on definitions
499 // anyway.
500 return TSK != TSK_ExplicitInstantiationDeclaration &&
501 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000502 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000503}
504
Rafael Espindola593537a2013-05-05 20:15:21 +0000505template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000506 const T *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +0000507 return First->isInExternCContext();
Rafael Espindolaf4187652013-02-14 01:18:37 +0000508}
509
Richard Smith03c05032014-02-17 23:34:47 +0000510static bool isSingleLineLanguageLinkage(const Decl &D) {
Rafael Espindola327be3c2013-04-26 01:30:23 +0000511 if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Richard Smith03c05032014-02-17 23:34:47 +0000512 if (!SD->hasBraces())
Rafael Espindola327be3c2013-04-26 01:30:23 +0000513 return true;
514 return false;
515}
516
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000517static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
John McCalldf25c432013-02-16 00:17:33 +0000518 LVComputationKind computation) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000519 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000520 "Not a name having namespace scope");
521 ASTContext &Context = D->getASTContext();
522
523 // C++ [basic.link]p3:
524 // A name having namespace scope (3.3.6) has internal linkage if it
525 // is the name of
526 // - an object, reference, function or function template that is
527 // explicitly declared static; or,
528 // (This bullet corresponds to C99 6.2.2p3.)
529 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
530 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000531 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000532 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000533
Richard Smithdc0ef452012-10-19 06:37:48 +0000534 // - a non-volatile object or reference that is explicitly declared const
535 // or constexpr and neither explicitly declared extern nor previously
536 // declared to have external linkage; or (there is no equivalent in C99)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000537 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000538 Var->getType().isConstQualified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000539 !Var->getType().isVolatileQualified()) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000540 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000541 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000542 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000543
544 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000545 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000546 !isSingleLineLanguageLinkage(*Var))
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000547 return LinkageInfo::internal();
548 }
549
550 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
551 PrevVar = PrevVar->getPreviousDecl()) {
552 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
553 Var->getStorageClass() == SC_None)
554 return PrevVar->getLinkageAndVisibility();
555 // Explicitly declared static.
556 if (PrevVar->getStorageClass() == SC_Static)
557 return LinkageInfo::internal();
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000558 }
Alp Tokera2794f92014-01-22 07:29:52 +0000559 } else if (const FunctionDecl *Function = D->getAsFunction()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000560 // C++ [temp]p4:
561 // A non-member function template can have internal linkage; any
562 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000563
564 // Explicitly declared static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000565 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000566 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000567 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000568 // - a data member of an anonymous union.
569 assert(!isa<IndirectFieldDecl>(D) && "Didn't expect an IndirectFieldDecl!");
570 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000571
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000572 if (D->isInAnonymousNamespace()) {
573 const VarDecl *Var = dyn_cast<VarDecl>(D);
574 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
Rafael Espindola593537a2013-05-05 20:15:21 +0000575 if ((!Var || !isFirstInExternCContext(Var)) &&
576 (!Func || !isFirstInExternCContext(Func)))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000577 return LinkageInfo::uniqueExternal();
578 }
John McCallb7139c42010-10-28 04:18:25 +0000579
John McCall457a04e2010-10-22 21:05:15 +0000580 // Set up the defaults.
581
582 // C99 6.2.2p5:
583 // If the declaration of an identifier for an object has file
584 // scope and no storage-class specifier, its linkage is
585 // external.
John McCallc273f242010-10-30 11:50:40 +0000586 LinkageInfo LV;
587
John McCalld041a9b2013-02-20 01:54:26 +0000588 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000589 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000590 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000591 } else {
592 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000593 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000594 for (const DeclContext *DC = D->getDeclContext();
595 !isa<TranslationUnitDecl>(DC);
596 DC = DC->getParent()) {
597 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
598 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000599 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000600 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000601 break;
602 }
603 }
604 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000605
John McCalldf25c432013-02-16 00:17:33 +0000606 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000607 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000608 // Use global type/value visibility as appropriate.
609 Visibility globalVisibility;
610 if (computation == LVForValue) {
611 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
612 } else {
613 assert(computation == LVForType);
614 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
615 }
616 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000617
618 // If we're paying attention to global visibility, apply
619 // -finline-visibility-hidden if this is an inline method.
620 if (useInlineVisibilityHidden(D))
621 LV.mergeVisibility(HiddenVisibility, true);
622 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000623 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000624
Douglas Gregorf73b2822009-11-25 22:24:25 +0000625 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000626
Douglas Gregorf73b2822009-11-25 22:24:25 +0000627 // A name having namespace scope has external linkage if it is the
628 // name of
629 //
630 // - an object or reference, unless it has internal linkage; or
631 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000632 // GCC applies the following optimization to variables and static
633 // data members, but not to functions:
634 //
John McCall457a04e2010-10-22 21:05:15 +0000635 // Modify the variable's LV by the LV of its type unless this is
636 // C or extern "C". This follows from [basic.link]p9:
637 // A type without linkage shall not be used as the type of a
638 // variable or function with external linkage unless
639 // - the entity has C language linkage, or
640 // - the entity is declared within an unnamed namespace, or
641 // - the entity is not used or is defined in the same
642 // translation unit.
643 // and [basic.link]p10:
644 // ...the types specified by all declarations referring to a
645 // given variable or function shall be identical...
646 // C does not have an equivalent rule.
647 //
John McCall5fe84122010-10-26 04:59:26 +0000648 // Ignore this if we've got an explicit attribute; the user
649 // probably knows what they're doing.
650 //
John McCall457a04e2010-10-22 21:05:15 +0000651 // Note that we don't want to make the variable non-external
652 // because of this, but unique-external linkage suits us.
Rafael Espindola593537a2013-05-05 20:15:21 +0000653 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000654 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Rafael Espindola4a5da442013-02-27 02:56:45 +0000655 if (TypeLV.getLinkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000656 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000657 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000658 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000659 }
660
John McCall23032652010-11-02 18:38:13 +0000661 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000662 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000663
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000664 // Note that Sema::MergeVarDecl already takes care of implementing
665 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
666 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000667
Douglas Gregorf73b2822009-11-25 22:24:25 +0000668 // - a function, unless it has internal linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000669 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000670 // In theory, we can modify the function's LV by the LV of its
671 // type unless it has C linkage (see comment above about variables
672 // for justification). In practice, GCC doesn't do this, so it's
673 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000674
John McCall23032652010-11-02 18:38:13 +0000675 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000676 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000677
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000678 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
679 // merging storage classes and visibility attributes, so we don't have to
680 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000681
John McCallf768aa72011-02-10 06:50:24 +0000682 // In C++, then if the type of the function uses a type with
683 // unique-external linkage, it's not legally usable from outside
684 // this translation unit. However, we should use the C linkage
685 // rules instead for extern "C" declarations.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000686 if (Context.getLangOpts().CPlusPlus &&
Richard Smith50f4afc2013-05-12 23:17:59 +0000687 !Function->isInExternCContext()) {
688 // Only look at the type-as-written. If this function has an auto-deduced
689 // return type, we can't compute the linkage of that type because it could
690 // require looking at the linkage of this function, and we don't need this
691 // for correctness because the type is not part of the function's
692 // signature.
Faisal Valid2598e92013-10-08 04:15:04 +0000693 // FIXME: This is a hack. We should be able to solve this circularity and
694 // the one in getLVForClassMember for Functions some other way.
Richard Smith50f4afc2013-05-12 23:17:59 +0000695 QualType TypeAsWritten = Function->getType();
696 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
697 TypeAsWritten = TSI->getType();
698 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
699 return LinkageInfo::uniqueExternal();
700 }
John McCallf768aa72011-02-10 06:50:24 +0000701
John McCall5f46c482013-02-21 23:42:58 +0000702 // Consider LV from the template and the template arguments.
703 // We're at file scope, so we do not need to worry about nested
704 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000705 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000706 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000707 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000708 }
709
Douglas Gregorf73b2822009-11-25 22:24:25 +0000710 // - a named class (Clause 9), or an unnamed class defined in a
711 // typedef declaration in which the class has the typedef name
712 // for linkage purposes (7.1.3); or
713 // - a named enumeration (7.2), or an unnamed enumeration
714 // defined in a typedef declaration in which the enumeration
715 // has the typedef name for linkage purposes (7.1.3); or
John McCall457a04e2010-10-22 21:05:15 +0000716 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
717 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000718 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000719 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000720
John McCall457a04e2010-10-22 21:05:15 +0000721 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000722 // linkage of the template and template arguments. We're at file
723 // scope, so we do not need to worry about nested specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000724 if (const ClassTemplateSpecializationDecl *spec
John McCall457a04e2010-10-22 21:05:15 +0000725 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000726 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000727 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000728
729 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000730 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000731 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000732 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000733 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000734 return LinkageInfo::none();
735 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000736
737 // - a template, unless it is a function template that has
738 // internal linkage (Clause 14);
John McCall8bc6d5b2011-03-04 10:39:25 +0000739 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000740 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000741 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000742 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000743 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
744
Douglas Gregorf73b2822009-11-25 22:24:25 +0000745 // - a namespace (7.3), unless it is declared within an unnamed
746 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000747 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
748 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000749
John McCall457a04e2010-10-22 21:05:15 +0000750 // By extension, we assign external linkage to Objective-C
751 // interfaces.
752 } else if (isa<ObjCInterfaceDecl>(D)) {
753 // fallout
754
755 // Everything not covered here has no linkage.
756 } else {
John McCallc273f242010-10-30 11:50:40 +0000757 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000758 }
759
760 // If we ended up with non-external linkage, visibility should
761 // always be default.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000762 if (LV.getLinkage() != ExternalLinkage)
763 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000764
John McCall457a04e2010-10-22 21:05:15 +0000765 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000766}
767
John McCalldf25c432013-02-16 00:17:33 +0000768static LinkageInfo getLVForClassMember(const NamedDecl *D,
769 LVComputationKind computation) {
John McCall457a04e2010-10-22 21:05:15 +0000770 // Only certain class members have linkage. Note that fields don't
771 // really have linkage, but it's convenient to say they do for the
772 // purposes of calculating linkage of pointer-to-data-member
773 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000774 //
775 // Templates also don't officially have linkage, but since we ignore
776 // the C++ standard and look at template arguments when determining
777 // linkage and visibility of a template specialization, we might hit
778 // a template template argument that way. If we do, we need to
779 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000780 if (!(isa<CXXMethodDecl>(D) ||
781 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000782 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000783 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000784 isa<TagDecl>(D) ||
785 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000786 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000787
John McCall07072662010-11-02 01:45:15 +0000788 LinkageInfo LV;
789
John McCall07072662010-11-02 01:45:15 +0000790 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000791 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000792 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000793 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000794 // If we're paying attention to global visibility, apply
795 // -finline-visibility-hidden if this is an inline method.
796 //
797 // Note that we do this before merging information about
798 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000799 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000800 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000801 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000802
803 // If this class member has an explicit visibility attribute, the only
804 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000805 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000806 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000807 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000808 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000809
John McCall5f46c482013-02-21 23:42:58 +0000810 LinkageInfo classLV =
811 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
John McCall8823c652010-08-13 08:35:10 +0000812 // If the class already has unique-external linkage, we can't improve.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000813 if (classLV.getLinkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000814 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000815
Rafael Espindolae6190db2013-05-28 02:22:10 +0000816 if (!isExternallyVisible(classLV.getLinkage()))
817 return LinkageInfo::none();
818
819
John McCall5f46c482013-02-21 23:42:58 +0000820 // Otherwise, don't merge in classLV yet, because in certain cases
821 // we need to completely ignore the visibility from it.
822
823 // Specifically, if this decl exists and has an explicit attribute.
824 const NamedDecl *explicitSpecSuppressor = 0;
825
John McCall8823c652010-08-13 08:35:10 +0000826 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000827 // If the type of the function uses a type with unique-external
828 // linkage, it's not legally usable from outside this translation unit.
Faisal Valid2598e92013-10-08 04:15:04 +0000829 // But only look at the type-as-written. If this function has an auto-deduced
830 // return type, we can't compute the linkage of that type because it could
831 // require looking at the linkage of this function, and we don't need this
832 // for correctness because the type is not part of the function's
833 // signature.
834 // FIXME: This is a hack. We should be able to solve this circularity and the
835 // one in getLVForNamespaceScopeDecl for Functions some other way.
836 {
837 QualType TypeAsWritten = MD->getType();
838 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
839 TypeAsWritten = TSI->getType();
840 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
841 return LinkageInfo::uniqueExternal();
842 }
John McCall457a04e2010-10-22 21:05:15 +0000843 // If this is a method template specialization, use the linkage for
844 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000845 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000846 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000847 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000848 if (spec->isExplicitSpecialization()) {
849 explicitSpecSuppressor = MD;
850 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
851 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
852 }
853 } else if (isExplicitMemberSpecialization(MD)) {
854 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000855 }
John McCall457a04e2010-10-22 21:05:15 +0000856
John McCall37bb6c92010-10-29 22:22:43 +0000857 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCallb8c604a2011-06-27 23:06:04 +0000858 if (const ClassTemplateSpecializationDecl *spec
John McCall37bb6c92010-10-29 22:22:43 +0000859 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000860 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000861 if (spec->isExplicitSpecialization()) {
862 explicitSpecSuppressor = spec;
863 } else {
864 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
865 if (isExplicitMemberSpecialization(temp)) {
866 explicitSpecSuppressor = temp->getTemplatedDecl();
867 }
868 }
869 } else if (isExplicitMemberSpecialization(RD)) {
870 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000871 }
872
John McCall37bb6c92010-10-29 22:22:43 +0000873 // Static data members.
874 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCall36cd5cc2010-10-30 09:18:49 +0000875 // Modify the variable's linkage by its type, but ignore the
876 // type's visibility unless it's a definition.
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000877 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000878 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
879 LV.mergeVisibility(typeLV);
880 LV.mergeExternalVisibility(typeLV);
John McCall5f46c482013-02-21 23:42:58 +0000881
882 if (isExplicitMemberSpecialization(VD)) {
883 explicitSpecSuppressor = VD;
884 }
John McCalldf25c432013-02-16 00:17:33 +0000885
886 // Template members.
887 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
888 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +0000889 (!LV.isVisibilityExplicit() &&
890 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000891 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000892 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000893 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000894 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +0000895
896 if (const RedeclarableTemplateDecl *redeclTemp =
897 dyn_cast<RedeclarableTemplateDecl>(temp)) {
898 if (isExplicitMemberSpecialization(redeclTemp)) {
899 explicitSpecSuppressor = temp->getTemplatedDecl();
900 }
901 }
John McCall37bb6c92010-10-29 22:22:43 +0000902 }
903
John McCall5f46c482013-02-21 23:42:58 +0000904 // We should never be looking for an attribute directly on a template.
905 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
906
907 // If this member is an explicit member specialization, and it has
908 // an explicit attribute, ignore visibility from the parent.
909 bool considerClassVisibility = true;
910 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +0000911 // optimization: hasDVA() is true only with explicit visibility.
912 LV.isVisibilityExplicit() &&
913 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +0000914 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
915 considerClassVisibility = false;
916 }
917
918 // Finally, merge in information from the class.
919 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +0000920 return LV;
John McCall8823c652010-08-13 08:35:10 +0000921}
922
David Blaikie68e081d2011-12-20 02:48:34 +0000923void NamedDecl::anchor() { }
924
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000925static LinkageInfo computeLVForDecl(const NamedDecl *D,
926 LVComputationKind computation);
927
Rafael Espindola0e0d0092013-03-14 03:07:35 +0000928bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +0000929 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +0000930 return true;
John McCalld396b972011-02-08 19:01:05 +0000931
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000932 return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
Rafael Espindola50df3a02013-05-25 17:16:20 +0000933 getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +0000934}
935
Rafael Espindola3ae00052013-05-13 00:12:11 +0000936Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +0000937 // We don't care about visibility here, so ask for the cheapest
938 // possible visibility analysis.
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000939 return getLVForDecl(this, LVForLinkageOnly).getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +0000940}
941
John McCallc273f242010-10-30 11:50:40 +0000942LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCalldf25c432013-02-16 00:17:33 +0000943 LVComputationKind computation =
944 (usesTypeVisibility(this) ? LVForType : LVForValue);
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000945 return getLVForDecl(this, computation);
John McCall033caa52010-10-29 00:29:13 +0000946}
Ted Kremenek926d8602010-04-20 23:15:35 +0000947
Rafael Espindola9ad61122013-11-26 16:09:08 +0000948static Optional<Visibility>
949getExplicitVisibilityAux(const NamedDecl *ND,
950 NamedDecl::ExplicitVisibilityKind kind,
951 bool IsMostRecent) {
952 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
953
Rafael Espindola3a52c442013-02-26 19:33:14 +0000954 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +0000955 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +0000956 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000957
Rafael Espindola3a52c442013-02-26 19:33:14 +0000958 // If this is a member class of a specialization of a class template
959 // and the corresponding decl has explicit visibility, use that.
Rafael Espindola9ad61122013-11-26 16:09:08 +0000960 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +0000961 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
962 if (InstantiatedFrom)
963 return getVisibilityOf(InstantiatedFrom, kind);
964 }
965
966 // If there wasn't explicit visibility there, and this is a
967 // specialization of a class template, check for visibility
968 // on the pattern.
969 if (const ClassTemplateSpecializationDecl *spec
Rafael Espindola9ad61122013-11-26 16:09:08 +0000970 = dyn_cast<ClassTemplateSpecializationDecl>(ND))
Rafael Espindola3a52c442013-02-26 19:33:14 +0000971 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
972 kind);
973
974 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +0000975 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +0000976 const NamedDecl *MostRecent = ND->getMostRecentDecl();
977 if (MostRecent != ND)
978 return getExplicitVisibilityAux(MostRecent, kind, true);
979 }
Rafael Espindola3a52c442013-02-26 19:33:14 +0000980
Rafael Espindola9ad61122013-11-26 16:09:08 +0000981 if (const VarDecl *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +0000982 if (Var->isStaticDataMember()) {
983 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
984 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +0000985 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +0000986 }
987
David Blaikie7a30dc52013-02-21 01:47:18 +0000988 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +0000989 }
Rafael Espindola3a52c442013-02-26 19:33:14 +0000990 // Also handle function template specializations.
Rafael Espindola9ad61122013-11-26 16:09:08 +0000991 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000992 // If the function is a specialization of a template with an
993 // explicit visibility attribute, use that.
994 if (FunctionTemplateSpecializationInfo *templateInfo
995 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +0000996 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
997 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000998
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000999 // If the function is a member of a specialization of a class template
1000 // and the corresponding decl has explicit visibility, use that.
1001 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1002 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001003 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001004
David Blaikie7a30dc52013-02-21 01:47:18 +00001005 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001006 }
1007
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001008 // The visibility of a template is stored in the templated decl.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001009 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001010 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001011
David Blaikie7a30dc52013-02-21 01:47:18 +00001012 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001013}
1014
Rafael Espindola9ad61122013-11-26 16:09:08 +00001015Optional<Visibility>
1016NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1017 return getExplicitVisibilityAux(this, kind, false);
1018}
1019
Eli Friedman7e346a82013-07-01 20:22:57 +00001020static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
1021 LVComputationKind computation) {
1022 // This lambda has its linkage/visibility determined by its owner.
1023 if (ContextDecl) {
1024 if (isa<ParmVarDecl>(ContextDecl))
1025 DC = ContextDecl->getDeclContext()->getRedeclContext();
1026 else
1027 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1028 }
Faisal Vali98b8e182013-09-29 20:27:06 +00001029
Eli Friedman7e346a82013-07-01 20:22:57 +00001030 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
1031 return getLVForDecl(ND, computation);
Faisal Vali98b8e182013-09-29 20:27:06 +00001032
Eli Friedman7e346a82013-07-01 20:22:57 +00001033 return LinkageInfo::external();
1034}
1035
John McCalldf25c432013-02-16 00:17:33 +00001036static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1037 LVComputationKind computation) {
1038 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1039 if (Function->isInAnonymousNamespace() &&
Rafael Espindola593537a2013-05-05 20:15:21 +00001040 !Function->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001041 return LinkageInfo::uniqueExternal();
1042
1043 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001044 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCalldf25c432013-02-16 00:17:33 +00001045 return LinkageInfo::internal();
1046
1047 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001048 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001049 if (Optional<Visibility> Vis =
1050 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001051 LV.mergeVisibility(*Vis, true);
1052 }
1053
1054 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1055 // merging storage classes and visibility attributes, so we don't have to
1056 // look at previous decls in here.
1057
1058 return LV;
1059 }
1060
1061 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001062 if (Var->hasExternalStorage()) {
Rafael Espindola593537a2013-05-05 20:15:21 +00001063 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001064 return LinkageInfo::uniqueExternal();
1065
John McCalldf25c432013-02-16 00:17:33 +00001066 LinkageInfo LV;
1067 if (Var->getStorageClass() == SC_PrivateExtern)
1068 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001069 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001070 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001071 LV.mergeVisibility(*Vis, true);
1072 }
1073
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001074 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1075 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1076 if (PrevLV.getLinkage())
1077 LV.setLinkage(PrevLV.getLinkage());
1078 LV.mergeVisibility(PrevLV);
1079 }
1080
John McCalldf25c432013-02-16 00:17:33 +00001081 return LV;
1082 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001083
1084 if (!Var->isStaticLocal())
1085 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001086 }
1087
Rafael Espindolaa4184182013-06-17 20:04:51 +00001088 ASTContext &Context = D->getASTContext();
1089 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001090 return LinkageInfo::none();
1091
Eli Friedman7e346a82013-07-01 20:22:57 +00001092 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1093 if (!OuterD)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001094 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001095
Eli Friedman7e346a82013-07-01 20:22:57 +00001096 LinkageInfo LV;
1097 if (const BlockDecl *BD = dyn_cast<BlockDecl>(OuterD)) {
1098 if (!BD->getBlockManglingNumber())
1099 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001100
Eli Friedman7e346a82013-07-01 20:22:57 +00001101 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1102 BD->getBlockManglingContextDecl(), computation);
1103 } else {
1104 const FunctionDecl *FD = cast<FunctionDecl>(OuterD);
1105 if (!FD->isInlined() &&
1106 FD->getTemplateSpecializationKind() == TSK_Undeclared)
1107 return LinkageInfo::none();
1108
1109 LV = getLVForDecl(FD, computation);
1110 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001111 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001112 return LinkageInfo::none();
1113 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1114 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001115}
1116
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001117static inline const CXXRecordDecl*
1118getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1119 const CXXRecordDecl *Ret = Record;
1120 while (Record && Record->isLambda()) {
1121 Ret = Record;
1122 if (!Record->getParent()) break;
1123 // Get the Containing Class of this Lambda Class
1124 Record = dyn_cast_or_null<CXXRecordDecl>(
1125 Record->getParent()->getParent());
1126 }
1127 return Ret;
1128}
1129
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001130static LinkageInfo computeLVForDecl(const NamedDecl *D,
1131 LVComputationKind computation) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001132 // Objective-C: treat all Objective-C declarations as having external
1133 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001134 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001135 default:
1136 break;
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001137 case Decl::ParmVar:
1138 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001139 case Decl::TemplateTemplateParm: // count these as external
1140 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001141 case Decl::ObjCAtDefsField:
1142 case Decl::ObjCCategory:
1143 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001144 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001145 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001146 case Decl::ObjCMethod:
1147 case Decl::ObjCProperty:
1148 case Decl::ObjCPropertyImpl:
1149 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +00001150 return LinkageInfo::external();
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001151
1152 case Decl::CXXRecord: {
1153 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1154 if (Record->isLambda()) {
1155 if (!Record->getLambdaManglingNumber()) {
1156 // This lambda has no mangling number, so it's internal.
1157 return LinkageInfo::internal();
1158 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001159
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001160 // This lambda has its linkage/visibility determined:
1161 // - either by the outermost lambda if that lambda has no mangling
1162 // number.
1163 // - or by the parent of the outer most lambda
1164 // This prevents infinite recursion in settings such as nested lambdas
1165 // used in NSDMI's, for e.g.
1166 // struct L {
1167 // int t{};
1168 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1169 // };
1170 const CXXRecordDecl *OuterMostLambda =
1171 getOutermostEnclosingLambda(Record);
1172 if (!OuterMostLambda->getLambdaManglingNumber())
1173 return LinkageInfo::internal();
1174
1175 return getLVForClosure(
1176 OuterMostLambda->getDeclContext()->getRedeclContext(),
1177 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001178 }
1179
1180 break;
1181 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001182 }
1183
Douglas Gregorf73b2822009-11-25 22:24:25 +00001184 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001185 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCalldf25c432013-02-16 00:17:33 +00001186 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001187
1188 // C++ [basic.link]p5:
1189 // In addition, a member function, static data member, a named
1190 // class or enumeration of class scope, or an unnamed class or
1191 // enumeration defined in a class-scope typedef declaration such
1192 // that the class or enumeration has the typedef name for linkage
1193 // purposes (7.1.3), has external linkage if the name of the class
1194 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001195 if (D->getDeclContext()->isRecord())
John McCalldf25c432013-02-16 00:17:33 +00001196 return getLVForClassMember(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001197
1198 // C++ [basic.link]p6:
1199 // The name of a function declared in block scope and the name of
1200 // an object declared by a block scope extern declaration have
1201 // linkage. If there is a visible declaration of an entity with
1202 // linkage having the same name and type, ignoring entities
1203 // declared outside the innermost enclosing namespace scope, the
1204 // block scope declaration declares that same entity and receives
1205 // the linkage of the previous declaration. If there is more than
1206 // one such matching entity, the program is ill-formed. Otherwise,
1207 // if no matching entity is found, the block scope entity receives
1208 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001209 if (D->getDeclContext()->isFunctionOrMethod())
1210 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001211
1212 // C++ [basic.link]p6:
1213 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001214 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001215}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001216
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001217namespace clang {
1218class LinkageComputer {
1219public:
1220 static LinkageInfo getLVForDecl(const NamedDecl *D,
1221 LVComputationKind computation) {
1222 if (computation == LVForLinkageOnly && D->hasCachedLinkage())
1223 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1224
1225 LinkageInfo LV = computeLVForDecl(D, computation);
1226 if (D->hasCachedLinkage())
1227 assert(D->getCachedLinkage() == LV.getLinkage());
1228
1229 D->setCachedLinkage(LV.getLinkage());
1230
1231#ifndef NDEBUG
1232 // In C (because of gnu inline) and in c++ with microsoft extensions an
1233 // static can follow an extern, so we can have two decls with different
1234 // linkages.
1235 const LangOptions &Opts = D->getASTContext().getLangOpts();
1236 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1237 return LV;
1238
1239 // We have just computed the linkage for this decl. By induction we know
1240 // that all other computed linkages match, check that the one we just
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001241 // computed also does.
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001242 NamedDecl *Old = NULL;
Aaron Ballman86c93902014-03-06 23:45:36 +00001243 for (auto I : D->redecls()) {
1244 NamedDecl *T = cast<NamedDecl>(I);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001245 if (T == D)
1246 continue;
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001247 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001248 Old = T;
1249 break;
1250 }
1251 }
1252 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1253#endif
1254
1255 return LV;
1256 }
1257};
1258}
1259
1260static LinkageInfo getLVForDecl(const NamedDecl *D,
1261 LVComputationKind computation) {
1262 return clang::LinkageComputer::getLVForDecl(D, computation);
1263}
1264
Douglas Gregor2ada0482009-02-04 17:27:36 +00001265std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001266 std::string QualName;
1267 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001268 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001269 return OS.str();
1270}
1271
1272void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1273 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1274}
1275
1276void NamedDecl::printQualifiedName(raw_ostream &OS,
1277 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001278 const DeclContext *Ctx = getDeclContext();
1279
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001280 if (Ctx->isFunctionOrMethod()) {
1281 printName(OS);
1282 return;
1283 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001284
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001285 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001286 ContextsTy Contexts;
1287
1288 // Collect contexts.
1289 while (Ctx && isa<NamedDecl>(Ctx)) {
1290 Contexts.push_back(Ctx);
1291 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001292 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001293
1294 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1295 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00001296 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001297 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001298 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001299 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00001300 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1301 TemplateArgs.data(),
1302 TemplateArgs.size(),
1303 P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001304 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Sam Weinig07d211e2009-12-24 23:15:03 +00001305 if (ND->isAnonymousNamespace())
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001306 OS << "<anonymous namespace>";
Sam Weinig07d211e2009-12-24 23:15:03 +00001307 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001308 OS << *ND;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001309 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1310 if (!RD->getIdentifier())
1311 OS << "<anonymous " << RD->getKindName() << '>';
1312 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001313 OS << *RD;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001314 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Sam Weinigb999f682009-12-28 03:19:38 +00001315 const FunctionProtoType *FT = 0;
1316 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001317 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001318
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001319 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001320 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001321 unsigned NumParams = FD->getNumParams();
1322 for (unsigned i = 0; i < NumParams; ++i) {
1323 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001324 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001325 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001326 }
1327
1328 if (FT->isVariadic()) {
1329 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001330 OS << ", ";
1331 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001332 }
1333 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001334 OS << ')';
1335 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001336 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001337 }
1338 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001339 }
1340
John McCalla2a3f7d2010-03-16 21:48:18 +00001341 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001342 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001343 else
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001344 OS << "<anonymous>";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001345}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001346
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001347void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1348 const PrintingPolicy &Policy,
1349 bool Qualified) const {
1350 if (Qualified)
1351 printQualifiedName(OS, Policy);
1352 else
1353 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001354}
1355
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001356bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001357 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1358
Douglas Gregor889ceb72009-02-03 19:21:40 +00001359 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1360 // We want to keep it, unless it nominates same namespace.
1361 if (getKind() == Decl::UsingDirective) {
Douglas Gregor12441b32011-02-25 16:33:46 +00001362 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1363 ->getOriginalNamespace() ==
1364 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1365 ->getOriginalNamespace();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001366 }
Mike Stump11289f42009-09-09 15:08:12 +00001367
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001368 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1369 // For function declarations, we keep track of redeclarations.
Douglas Gregorec9fd132012-01-14 16:38:05 +00001370 return FD->getPreviousDecl() == OldD;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001371
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001372 // For function templates, the underlying function declarations are linked.
1373 if (const FunctionTemplateDecl *FunctionTemplate
1374 = dyn_cast<FunctionTemplateDecl>(this))
1375 if (const FunctionTemplateDecl *OldFunctionTemplate
1376 = dyn_cast<FunctionTemplateDecl>(OldD))
1377 return FunctionTemplate->getTemplatedDecl()
1378 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001379
Steve Naroffc4173fa2009-02-22 19:35:57 +00001380 // For method declarations, we keep track of redeclarations.
1381 if (isa<ObjCMethodDecl>(this))
1382 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001383
Richard Smithbaf3ca52014-03-17 21:46:03 +00001384 // FIXME: Is this correct if one of the decls comes from an inline namespace?
John McCall9f3059a2009-10-09 21:13:30 +00001385 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1386 return true;
1387
John McCall3f746822009-11-17 05:59:44 +00001388 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1389 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1390 cast<UsingShadowDecl>(OldD)->getTargetDecl();
1391
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001392 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1393 ASTContext &Context = getASTContext();
1394 return Context.getCanonicalNestedNameSpecifier(
1395 cast<UsingDecl>(this)->getQualifier()) ==
1396 Context.getCanonicalNestedNameSpecifier(
1397 cast<UsingDecl>(OldD)->getQualifier());
1398 }
Argyrios Kyrtzidis4b520072010-11-04 08:48:52 +00001399
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001400 if (isa<UnresolvedUsingValueDecl>(this) &&
1401 isa<UnresolvedUsingValueDecl>(OldD)) {
1402 ASTContext &Context = getASTContext();
1403 return Context.getCanonicalNestedNameSpecifier(
1404 cast<UnresolvedUsingValueDecl>(this)->getQualifier()) ==
1405 Context.getCanonicalNestedNameSpecifier(
1406 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1407 }
1408
Douglas Gregorb59643b2012-01-03 23:26:26 +00001409 // A typedef of an Objective-C class type can replace an Objective-C class
1410 // declaration or definition, and vice versa.
Richard Smithbaf3ca52014-03-17 21:46:03 +00001411 // FIXME: Is this correct if one of the decls comes from an inline namespace?
Douglas Gregorb59643b2012-01-03 23:26:26 +00001412 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1413 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1414 return true;
Richard Smithbaf3ca52014-03-17 21:46:03 +00001415
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001416 // For non-function declarations, if the declarations are of the
Richard Smithbaf3ca52014-03-17 21:46:03 +00001417 // same kind and have the same parent then this must be a redeclaration,
1418 // or semantic analysis would not have given us the new declaration.
1419 // Note that inline namespaces can give us two declarations with the same
1420 // name and kind in the same scope but different contexts.
1421 return this->getKind() == OldD->getKind() &&
1422 this->getDeclContext()->getRedeclContext()->Equals(
1423 OldD->getDeclContext()->getRedeclContext());
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001424}
1425
Douglas Gregoreddf4332009-02-24 20:03:32 +00001426bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001427 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001428}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001429
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001430NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001431 NamedDecl *ND = this;
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001432 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1433 ND = UD->getTargetDecl();
1434
1435 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1436 return AD->getClassInterface();
1437
1438 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001439}
1440
John McCalla8ae2222010-04-06 21:38:20 +00001441bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001442 if (!isCXXClassMember())
1443 return false;
1444
John McCalla8ae2222010-04-06 21:38:20 +00001445 const NamedDecl *D = this;
1446 if (isa<UsingShadowDecl>(D))
1447 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1448
John McCall5e77d762013-04-16 07:28:30 +00001449 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001450 return true;
Alp Tokera2794f92014-01-22 07:29:52 +00001451 if (const CXXMethodDecl *MD =
1452 dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1453 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001454 return false;
1455}
1456
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001457//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001458// DeclaratorDecl Implementation
1459//===----------------------------------------------------------------------===//
1460
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001461template <typename DeclT>
1462static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1463 if (decl->getNumTemplateParameterLists() > 0)
1464 return decl->getTemplateParameterList(0)->getTemplateLoc();
1465 else
1466 return decl->getInnerLocStart();
1467}
1468
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001469SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001470 TypeSourceInfo *TSI = getTypeSourceInfo();
1471 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001472 return SourceLocation();
1473}
1474
Douglas Gregor14454802011-02-25 02:25:35 +00001475void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1476 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001477 // Make sure the extended decl info is allocated.
1478 if (!hasExtInfo()) {
1479 // Save (non-extended) type source info pointer.
1480 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1481 // Allocate external info struct.
1482 DeclInfo = new (getASTContext()) ExtInfo;
1483 // Restore savedTInfo into (extended) decl info.
1484 getExtInfo()->TInfo = savedTInfo;
1485 }
1486 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001487 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001488 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001489 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001490 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001491 if (getExtInfo()->NumTemplParamLists == 0) {
1492 // Save type source info pointer.
1493 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1494 // Deallocate the extended decl info.
1495 getASTContext().Deallocate(getExtInfo());
1496 // Restore savedTInfo into (non-extended) decl info.
1497 DeclInfo = savedTInfo;
1498 }
1499 else
1500 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001501 }
1502 }
1503}
1504
Abramo Bagnara60804e12011-03-18 15:16:37 +00001505void
1506DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1507 unsigned NumTPLists,
1508 TemplateParameterList **TPLists) {
1509 assert(NumTPLists > 0);
1510 // Make sure the extended decl info is allocated.
1511 if (!hasExtInfo()) {
1512 // Save (non-extended) type source info pointer.
1513 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1514 // Allocate external info struct.
1515 DeclInfo = new (getASTContext()) ExtInfo;
1516 // Restore savedTInfo into (extended) decl info.
1517 getExtInfo()->TInfo = savedTInfo;
1518 }
1519 // Set the template parameter lists info.
1520 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1521}
1522
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001523SourceLocation DeclaratorDecl::getOuterLocStart() const {
1524 return getTemplateOrInnerLocStart(this);
1525}
1526
Abramo Bagnaraea947882011-03-08 16:41:52 +00001527namespace {
1528
1529// Helper function: returns true if QT is or contains a type
1530// having a postfix component.
1531bool typeIsPostfix(clang::QualType QT) {
1532 while (true) {
1533 const Type* T = QT.getTypePtr();
1534 switch (T->getTypeClass()) {
1535 default:
1536 return false;
1537 case Type::Pointer:
1538 QT = cast<PointerType>(T)->getPointeeType();
1539 break;
1540 case Type::BlockPointer:
1541 QT = cast<BlockPointerType>(T)->getPointeeType();
1542 break;
1543 case Type::MemberPointer:
1544 QT = cast<MemberPointerType>(T)->getPointeeType();
1545 break;
1546 case Type::LValueReference:
1547 case Type::RValueReference:
1548 QT = cast<ReferenceType>(T)->getPointeeType();
1549 break;
1550 case Type::PackExpansion:
1551 QT = cast<PackExpansionType>(T)->getPattern();
1552 break;
1553 case Type::Paren:
1554 case Type::ConstantArray:
1555 case Type::DependentSizedArray:
1556 case Type::IncompleteArray:
1557 case Type::VariableArray:
1558 case Type::FunctionProto:
1559 case Type::FunctionNoProto:
1560 return true;
1561 }
1562 }
1563}
1564
1565} // namespace
1566
1567SourceRange DeclaratorDecl::getSourceRange() const {
1568 SourceLocation RangeEnd = getLocation();
1569 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001570 // If the declaration has no name or the type extends past the name take the
1571 // end location of the type.
1572 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001573 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1574 }
1575 return SourceRange(getOuterLocStart(), RangeEnd);
1576}
1577
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001578void
Douglas Gregor20527e22010-06-15 17:44:38 +00001579QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1580 unsigned NumTPLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001581 TemplateParameterList **TPLists) {
1582 assert((NumTPLists == 0 || TPLists != 0) &&
1583 "Empty array of template parameters with positive size!");
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001584
1585 // Free previous template parameters (if any).
1586 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001587 Context.Deallocate(TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001588 TemplParamLists = 0;
1589 NumTemplParamLists = 0;
1590 }
1591 // Set info on matched template parameter lists (if any).
1592 if (NumTPLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001593 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001594 NumTemplParamLists = NumTPLists;
1595 for (unsigned i = NumTPLists; i-- > 0; )
1596 TemplParamLists[i] = TPLists[i];
1597 }
1598}
1599
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001600//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001601// VarDecl Implementation
1602//===----------------------------------------------------------------------===//
1603
Sebastian Redl833ef452010-01-26 22:01:41 +00001604const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1605 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001606 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001607 case SC_Auto: return "auto";
1608 case SC_Extern: return "extern";
1609 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1610 case SC_PrivateExtern: return "__private_extern__";
1611 case SC_Register: return "register";
1612 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001613 }
1614
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001615 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001616}
1617
Larisse Voufo39a1e502013-08-06 01:03:05 +00001618VarDecl::VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1619 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1620 TypeSourceInfo *TInfo, StorageClass SC)
1621 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), Init() {
Benjamin Kramera939c232014-03-15 18:54:13 +00001622 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1623 "VarDeclBitfields too large!");
1624 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1625 "ParmVarDeclBitfields too large!");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001626 AllBits = 0;
1627 VarDeclBits.SClass = SC;
1628 // Everything else is implicitly initialized to false.
1629}
1630
Abramo Bagnaradff19302011-03-08 08:55:46 +00001631VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1632 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001633 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001634 StorageClass S) {
Richard Smithf7981722013-11-22 09:01:48 +00001635 return new (C, DC) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001636}
1637
Douglas Gregor72172e92012-01-05 21:55:30 +00001638VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00001639 return new (C, ID) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1640 QualType(), 0, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001641}
1642
Douglas Gregorbf62d642010-12-06 18:36:25 +00001643void VarDecl::setStorageClass(StorageClass SC) {
1644 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001645 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001646}
1647
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001648SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001649 if (const Expr *Init = getInit()) {
1650 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001651 // If Init is implicit, ignore its source range and fallback on
1652 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1653 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001654 return SourceRange(getOuterLocStart(), InitEnd);
1655 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001656 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001657}
1658
Rafael Espindola88510672013-01-04 21:18:45 +00001659template<typename T>
Rafael Espindolaf4187652013-02-14 01:18:37 +00001660static LanguageLinkage getLanguageLinkageTemplate(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001661 // C++ [dcl.link]p1: All function types, function names with external linkage,
1662 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001663 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001664 return NoLanguageLinkage;
1665
1666 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001667 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001668 ASTContext &Context = D.getASTContext();
1669 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001670 return CLanguageLinkage;
1671
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001672 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1673 // language linkage of the names of class members and the function type of
1674 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001675 const DeclContext *DC = D.getDeclContext();
1676 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001677 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001678
1679 // If the first decl is in an extern "C" context, any other redeclaration
1680 // will have C language linkage. If the first one is not in an extern "C"
1681 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00001682 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00001683 return CLanguageLinkage;
1684 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001685}
1686
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001687template<typename T>
1688static bool isExternCTemplate(const T &D) {
1689 // Since the context is ignored for class members, they can only have C++
1690 // language linkage or no language linkage.
1691 const DeclContext *DC = D.getDeclContext();
1692 if (DC->isRecord()) {
1693 assert(D.getASTContext().getLangOpts().CPlusPlus);
1694 return false;
1695 }
1696
1697 return D.getLanguageLinkage() == CLanguageLinkage;
1698}
1699
Rafael Espindolaf4187652013-02-14 01:18:37 +00001700LanguageLinkage VarDecl::getLanguageLinkage() const {
1701 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001702}
1703
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001704bool VarDecl::isExternC() const {
1705 return isExternCTemplate(*this);
1706}
1707
Rafael Espindola593537a2013-05-05 20:15:21 +00001708bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001709 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001710}
1711
1712bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001713 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001714}
1715
Rafael Espindola8db352d2013-10-17 15:37:26 +00001716VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00001717
Daniel Dunbar9d355812012-03-09 01:51:51 +00001718VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1719 ASTContext &C) const
1720{
Sebastian Redl35351a92010-01-31 22:27:38 +00001721 // C++ [basic.def]p2:
1722 // A declaration is a definition unless [...] it contains the 'extern'
1723 // specifier or a linkage-specification and neither an initializer [...],
1724 // it declares a static data member in a class declaration [...].
Richard Smith8809a0c2013-09-27 20:14:12 +00001725 // C++1y [temp.expl.spec]p15:
1726 // An explicit specialization of a static data member or an explicit
1727 // specialization of a static data member template is a definition if the
1728 // declaration includes an initializer; otherwise, it is a declaration.
1729 //
1730 // FIXME: How do you declare (but not define) a partial specialization of
1731 // a static data member template outside the containing class?
Sebastian Redl35351a92010-01-31 22:27:38 +00001732 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00001733 if (isOutOfLine() &&
1734 (hasInit() ||
1735 // If the first declaration is out-of-line, this may be an
1736 // instantiation of an out-of-line partial specialization of a variable
1737 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00001738 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00001739 ? getTemplateSpecializationKind() == TSK_Undeclared
1740 : getTemplateSpecializationKind() !=
1741 TSK_ExplicitSpecialization) ||
1742 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00001743 return Definition;
1744 else
1745 return DeclarationOnly;
1746 }
1747 // C99 6.7p5:
1748 // A definition of an identifier is a declaration for that identifier that
1749 // [...] causes storage to be reserved for that object.
1750 // Note: that applies for all non-file-scope objects.
1751 // C99 6.9.2p1:
1752 // If the declaration of an identifier for an object has file scope and an
1753 // initializer, the declaration is an external definition for the identifier
1754 if (hasInit())
1755 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00001756
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001757 if (hasAttr<AliasAttr>())
1758 return Definition;
1759
Richard Smith8809a0c2013-09-27 20:14:12 +00001760 // A variable template specialization (other than a static data member
1761 // template or an explicit specialization) is a declaration until we
1762 // instantiate its initializer.
1763 if (isa<VarTemplateSpecializationDecl>(this) &&
1764 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1765 return DeclarationOnly;
1766
Sebastian Redl35351a92010-01-31 22:27:38 +00001767 if (hasExternalStorage())
1768 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00001769
Rafael Espindolabff59562013-04-25 12:11:36 +00001770 // [dcl.link] p7:
1771 // A declaration directly contained in a linkage-specification is treated
1772 // as if it contains the extern specifier for the purpose of determining
1773 // the linkage of the declared name and whether it is a definition.
Richard Smith03c05032014-02-17 23:34:47 +00001774 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00001775 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00001776
Sebastian Redl35351a92010-01-31 22:27:38 +00001777 // C99 6.9.2p2:
1778 // A declaration of an object that has file scope without an initializer,
1779 // and without a storage class specifier or the scs 'static', constitutes
1780 // a tentative definition.
1781 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001782 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00001783 return TentativeDefinition;
1784
1785 // What's left is (in C, block-scope) declarations without initializers or
1786 // external storage. These are definitions.
1787 return Definition;
1788}
1789
Sebastian Redl35351a92010-01-31 22:27:38 +00001790VarDecl *VarDecl::getActingDefinition() {
1791 DefinitionKind Kind = isThisDeclarationADefinition();
1792 if (Kind != TentativeDefinition)
1793 return 0;
1794
Chris Lattner48eb14d2010-06-14 18:31:46 +00001795 VarDecl *LastTentative = 0;
Rafael Espindola8db352d2013-10-17 15:37:26 +00001796 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001797 for (auto I : First->redecls()) {
1798 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00001799 if (Kind == Definition)
1800 return 0;
1801 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00001802 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00001803 }
1804 return LastTentative;
1805}
1806
Daniel Dunbar9d355812012-03-09 01:51:51 +00001807VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001808 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001809 for (auto I : First->redecls()) {
1810 if (I->isThisDeclarationADefinition(C) == Definition)
1811 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00001812 }
1813 return 0;
1814}
1815
Daniel Dunbar9d355812012-03-09 01:51:51 +00001816VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00001817 DefinitionKind Kind = DeclarationOnly;
1818
Rafael Espindola8db352d2013-10-17 15:37:26 +00001819 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001820 for (auto I : First->redecls()) {
1821 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001822 if (Kind == Definition)
1823 break;
1824 }
John McCall37bb6c92010-10-29 22:22:43 +00001825
1826 return Kind;
1827}
1828
Sebastian Redl5ca79842010-02-01 20:16:42 +00001829const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00001830 for (auto I : redecls()) {
1831 if (auto Expr = I->getInit()) {
1832 D = I;
1833 return Expr;
1834 }
Sebastian Redl833ef452010-01-26 22:01:41 +00001835 }
1836 return 0;
1837}
1838
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001839bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00001840 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001841 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001842
1843 if (!isStaticDataMember())
1844 return false;
1845
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001846 // If this static data member was instantiated from a static data member of
1847 // a class template, check whether that static data member was defined
1848 // out-of-line.
1849 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1850 return VD->isOutOfLine();
1851
1852 return false;
1853}
1854
Douglas Gregor1d957a32009-10-27 18:42:08 +00001855VarDecl *VarDecl::getOutOfLineDefinition() {
1856 if (!isStaticDataMember())
1857 return 0;
1858
Aaron Ballman86c93902014-03-06 23:45:36 +00001859 for (auto RD : redecls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00001860 if (RD->getLexicalDeclContext()->isFileContext())
Aaron Ballman86c93902014-03-06 23:45:36 +00001861 return RD;
Douglas Gregor1d957a32009-10-27 18:42:08 +00001862 }
1863
1864 return 0;
1865}
1866
Douglas Gregord5058122010-02-11 01:19:42 +00001867void VarDecl::setInit(Expr *I) {
Sebastian Redl833ef452010-01-26 22:01:41 +00001868 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1869 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00001870 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00001871 }
1872
1873 Init = I;
1874}
1875
Daniel Dunbar9d355812012-03-09 01:51:51 +00001876bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001877 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00001878
Richard Smith35ecb362012-03-02 04:14:40 +00001879 if (!Lang.CPlusPlus)
1880 return false;
1881
1882 // In C++11, any variable of reference type can be used in a constant
1883 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001884 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00001885 return true;
1886
1887 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00001888 // not require the variable to be non-volatile, but we consider this to be a
1889 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00001890 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00001891 return false;
1892
1893 // In C++, const, non-volatile variables of integral or enumeration types
1894 // can be used in constant expressions.
1895 if (getType()->isIntegralOrEnumerationType())
1896 return true;
1897
Richard Smith35ecb362012-03-02 04:14:40 +00001898 // Additionally, in C++11, non-volatile constexpr variables can be used in
1899 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001900 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00001901}
1902
Richard Smithd0b4dd62011-12-19 06:19:21 +00001903/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1904/// form, which contains extra information on the evaluated value of the
1905/// initializer.
1906EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1907 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1908 if (!Eval) {
1909 Stmt *S = Init.get<Stmt *>();
Manuel Klimeka7328992013-06-03 13:51:33 +00001910 // Note: EvaluatedStmt contains an APValue, which usually holds
1911 // resources not allocated from the ASTContext. We need to do some
1912 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
1913 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00001914 Eval = new (getASTContext()) EvaluatedStmt;
1915 Eval->Value = S;
1916 Init = Eval;
1917 }
1918 return Eval;
1919}
1920
Richard Smithdafff942012-01-14 04:30:29 +00001921APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001922 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00001923 return evaluateValue(Notes);
1924}
1925
Manuel Klimeka7328992013-06-03 13:51:33 +00001926namespace {
1927// Destroy an APValue that was allocated in an ASTContext.
1928void DestroyAPValue(void* UntypedValue) {
1929 static_cast<APValue*>(UntypedValue)->~APValue();
1930}
1931} // namespace
1932
Richard Smithdafff942012-01-14 04:30:29 +00001933APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001934 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001935 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1936
1937 // We only produce notes indicating why an initializer is non-constant the
1938 // first time it is evaluated. FIXME: The notes won't always be emitted the
1939 // first time we try evaluation, so might not be produced at all.
1940 if (Eval->WasEvaluated)
Richard Smithdafff942012-01-14 04:30:29 +00001941 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001942
1943 const Expr *Init = cast<Expr>(Eval->Value);
1944 assert(!Init->isValueDependent());
1945
1946 if (Eval->IsEvaluating) {
1947 // FIXME: Produce a diagnostic for self-initialization.
1948 Eval->CheckedICE = true;
1949 Eval->IsICE = false;
Richard Smithdafff942012-01-14 04:30:29 +00001950 return 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001951 }
1952
1953 Eval->IsEvaluating = true;
1954
1955 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1956 this, Notes);
1957
Manuel Klimeka7328992013-06-03 13:51:33 +00001958 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
1959 // or that it's empty (so that there's nothing to clean up) if evaluation
1960 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00001961 if (!Result)
1962 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00001963 else if (Eval->Evaluated.needsCleanup())
1964 getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001965
1966 Eval->IsEvaluating = false;
1967 Eval->WasEvaluated = true;
1968
1969 // In C++11, we have determined whether the initializer was a constant
1970 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001971 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001972 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00001973 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00001974 }
1975
Richard Smithdafff942012-01-14 04:30:29 +00001976 return Result ? &Eval->Evaluated : 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001977}
1978
1979bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00001980 // Initializers of weak variables are never ICEs.
1981 if (isWeak())
1982 return false;
1983
Richard Smithd0b4dd62011-12-19 06:19:21 +00001984 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1985 if (Eval->CheckedICE)
1986 // We have already checked whether this subexpression is an
1987 // integral constant expression.
1988 return Eval->IsICE;
1989
1990 const Expr *Init = cast<Expr>(Eval->Value);
1991 assert(!Init->isValueDependent());
1992
1993 // In C++11, evaluate the initializer to check whether it's a constant
1994 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001995 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001996 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001997 evaluateValue(Notes);
1998 return Eval->IsICE;
1999 }
2000
2001 // It's an ICE whether or not the definition we found is
2002 // out-of-line. See DR 721 and the discussion in Clang PR
2003 // 6206 for details.
2004
2005 if (Eval->CheckingICE)
2006 return false;
2007 Eval->CheckingICE = true;
2008
2009 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2010 Eval->CheckingICE = false;
2011 Eval->CheckedICE = true;
2012 return Eval->IsICE;
2013}
2014
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002015VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002016 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002017 return cast<VarDecl>(MSI->getInstantiatedFrom());
2018
2019 return 0;
2020}
2021
Douglas Gregor3c74d412009-10-14 20:14:33 +00002022TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002023 if (const VarTemplateSpecializationDecl *Spec =
2024 dyn_cast<VarTemplateSpecializationDecl>(this))
2025 return Spec->getSpecializationKind();
2026
Sebastian Redl35351a92010-01-31 22:27:38 +00002027 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002028 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002029
Douglas Gregor86d142a2009-10-08 07:24:58 +00002030 return TSK_Undeclared;
2031}
2032
Richard Smith8809a0c2013-09-27 20:14:12 +00002033SourceLocation VarDecl::getPointOfInstantiation() const {
2034 if (const VarTemplateSpecializationDecl *Spec =
2035 dyn_cast<VarTemplateSpecializationDecl>(this))
2036 return Spec->getPointOfInstantiation();
2037
2038 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2039 return MSI->getPointOfInstantiation();
2040
2041 return SourceLocation();
2042}
2043
Larisse Voufo39a1e502013-08-06 01:03:05 +00002044VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2045 return getASTContext().getTemplateOrSpecializationInfo(this)
2046 .dyn_cast<VarTemplateDecl *>();
2047}
2048
2049void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2050 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2051}
2052
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002053MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002054 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002055 // FIXME: Remove ?
2056 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2057 return getASTContext().getTemplateOrSpecializationInfo(this)
2058 .dyn_cast<MemberSpecializationInfo *>();
Richard Smithb71782b2013-08-01 04:12:04 +00002059 return 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002060}
2061
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002062void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2063 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002064 assert((isa<VarTemplateSpecializationDecl>(this) ||
2065 getMemberSpecializationInfo()) &&
2066 "not a variable or static data member template specialization");
2067
Larisse Voufo39a1e502013-08-06 01:03:05 +00002068 if (VarTemplateSpecializationDecl *Spec =
2069 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2070 Spec->setSpecializationKind(TSK);
2071 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2072 Spec->getPointOfInstantiation().isInvalid())
2073 Spec->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002074 }
2075
2076 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2077 MSI->setTemplateSpecializationKind(TSK);
2078 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2079 MSI->getPointOfInstantiation().isInvalid())
2080 MSI->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002081 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002082}
2083
2084void
2085VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2086 TemplateSpecializationKind TSK) {
2087 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2088 "Previous template or instantiation?");
2089 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002090}
2091
Sebastian Redl833ef452010-01-26 22:01:41 +00002092//===----------------------------------------------------------------------===//
2093// ParmVarDecl Implementation
2094//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002095
Sebastian Redl833ef452010-01-26 22:01:41 +00002096ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002097 SourceLocation StartLoc,
2098 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002099 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002100 StorageClass S, Expr *DefArg) {
Richard Smithf7981722013-11-22 09:01:48 +00002101 return new (C, DC) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
2102 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002103}
2104
Reid Kleckner8a365022013-06-24 17:51:48 +00002105QualType ParmVarDecl::getOriginalType() const {
2106 TypeSourceInfo *TSI = getTypeSourceInfo();
2107 QualType T = TSI ? TSI->getType() : getType();
2108 if (const DecayedType *DT = dyn_cast<DecayedType>(T))
2109 return DT->getOriginalType();
2110 return T;
2111}
2112
Douglas Gregor72172e92012-01-05 21:55:30 +00002113ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00002114 return new (C, ID) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
2115 0, QualType(), 0, SC_None, 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00002116}
2117
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002118SourceRange ParmVarDecl::getSourceRange() const {
2119 if (!hasInheritedDefaultArg()) {
2120 SourceRange ArgRange = getDefaultArgRange();
2121 if (ArgRange.isValid())
2122 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2123 }
2124
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002125 // DeclaratorDecl considers the range of postfix types as overlapping with the
2126 // declaration name, but this is not the case with parameters in ObjC methods.
2127 if (isa<ObjCMethodDecl>(getDeclContext()))
2128 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2129
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002130 return DeclaratorDecl::getSourceRange();
2131}
2132
Sebastian Redl833ef452010-01-26 22:01:41 +00002133Expr *ParmVarDecl::getDefaultArg() {
2134 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2135 assert(!hasUninstantiatedDefaultArg() &&
2136 "Default argument is not yet instantiated!");
2137
2138 Expr *Arg = getInit();
John McCall5d413782010-12-06 08:20:24 +00002139 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002140 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002141
Sebastian Redl833ef452010-01-26 22:01:41 +00002142 return Arg;
2143}
2144
Sebastian Redl833ef452010-01-26 22:01:41 +00002145SourceRange ParmVarDecl::getDefaultArgRange() const {
2146 if (const Expr *E = getInit())
2147 return E->getSourceRange();
2148
2149 if (hasUninstantiatedDefaultArg())
2150 return getUninstantiatedDefaultArg()->getSourceRange();
2151
2152 return SourceRange();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002153}
2154
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00002155bool ParmVarDecl::isParameterPack() const {
2156 return isa<PackExpansionType>(getType());
2157}
2158
Ted Kremenek540017e2011-10-06 05:00:56 +00002159void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2160 getASTContext().setParameterIndex(this, parameterIndex);
2161 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2162}
2163
2164unsigned ParmVarDecl::getParameterIndexLarge() const {
2165 return getASTContext().getParameterIndex(this);
2166}
2167
Nuno Lopes394ec982008-12-17 23:39:55 +00002168//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002169// FunctionDecl Implementation
2170//===----------------------------------------------------------------------===//
2171
Benjamin Kramer9170e912013-02-22 15:46:01 +00002172void FunctionDecl::getNameForDiagnostic(
2173 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2174 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002175 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2176 if (TemplateArgs)
Benjamin Kramer9170e912013-02-22 15:46:01 +00002177 TemplateSpecializationType::PrintTemplateArgumentList(
2178 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002179}
2180
Ted Kremenek186a0742010-04-29 16:49:01 +00002181bool FunctionDecl::isVariadic() const {
2182 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
2183 return FT->isVariadic();
2184 return false;
2185}
2186
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002187bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002188 for (auto I : redecls()) {
Francois Pichet1c229c02011-04-22 22:18:13 +00002189 if (I->Body || I->IsLateTemplateParsed) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002190 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002191 return true;
2192 }
2193 }
2194
2195 return false;
2196}
2197
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002198bool FunctionDecl::hasTrivialBody() const
2199{
2200 Stmt *S = getBody();
2201 if (!S) {
2202 // Since we don't have a body for this function, we don't know if it's
2203 // trivial or not.
2204 return false;
2205 }
2206
2207 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2208 return true;
2209 return false;
2210}
2211
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002212bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002213 for (auto I : redecls()) {
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002214 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
2215 I->hasAttr<AliasAttr>()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002216 Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002217 return true;
2218 }
2219 }
2220
2221 return false;
2222}
2223
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002224Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002225 if (!hasBody(Definition))
2226 return 0;
2227
2228 if (Definition->Body)
2229 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002230
2231 return 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002232}
2233
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002234void FunctionDecl::setBody(Stmt *B) {
2235 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002236 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002237 EndRangeLoc = B->getLocEnd();
2238}
2239
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002240void FunctionDecl::setPure(bool P) {
2241 IsPure = P;
2242 if (P)
2243 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2244 Parent->markedVirtualFunctionPure();
2245}
2246
Richard Smith8d0dc312013-07-21 23:12:18 +00002247template<std::size_t Len>
2248static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2249 IdentifierInfo *II = ND->getIdentifier();
2250 return II && II->isStr(Str);
2251}
2252
Douglas Gregor16618f22009-09-12 00:17:51 +00002253bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002254 const TranslationUnitDecl *tunit =
2255 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2256 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002257 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002258 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002259}
2260
David Majnemerc729b0b2013-09-16 22:44:20 +00002261bool FunctionDecl::isMSVCRTEntryPoint() const {
2262 const TranslationUnitDecl *TUnit =
2263 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2264 if (!TUnit)
2265 return false;
2266
2267 // Even though we aren't really targeting MSVCRT if we are freestanding,
2268 // semantic analysis for these functions remains the same.
2269
2270 // MSVCRT entry points only exist on MSVCRT targets.
2271 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2272 return false;
2273
2274 // Nameless functions like constructors cannot be entry points.
2275 if (!getIdentifier())
2276 return false;
2277
2278 return llvm::StringSwitch<bool>(getName())
2279 .Cases("main", // an ANSI console app
2280 "wmain", // a Unicode console App
2281 "WinMain", // an ANSI GUI app
2282 "wWinMain", // a Unicode GUI app
2283 "DllMain", // a DLL
2284 true)
2285 .Default(false);
2286}
2287
John McCall53ffd372011-05-15 17:49:20 +00002288bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2289 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2290 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2291 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2292 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2293 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2294
Richard Smithf6004412014-01-19 23:25:37 +00002295 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2296 return false;
John McCall53ffd372011-05-15 17:49:20 +00002297
2298 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002299 if (proto->getNumParams() != 2 || proto->isVariadic())
2300 return false;
John McCall53ffd372011-05-15 17:49:20 +00002301
2302 ASTContext &Context =
2303 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2304 ->getASTContext();
2305
2306 // The result type and first argument type are constant across all
2307 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002308 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002309}
2310
Richard Smith8d0dc312013-07-21 23:12:18 +00002311static bool isNamespaceStd(const DeclContext *DC) {
2312 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC->getRedeclContext());
2313 return ND && isNamed(ND, "std") &&
2314 ND->getParent()->getRedeclContext()->isTranslationUnit();
2315}
2316
2317bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2318 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2319 return false;
2320 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2321 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2322 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2323 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2324 return false;
2325
2326 if (isa<CXXRecordDecl>(getDeclContext()))
2327 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002328
2329 // This can only fail for an invalid 'operator new' declaration.
2330 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2331 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002332
2333 const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002334 if (FPT->getNumParams() > 2 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002335 return false;
2336
2337 // If this is a single-parameter function, it must be a replaceable global
2338 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002339 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002340 return true;
2341
2342 // Otherwise, we're looking for a second parameter whose type is
Richard Smith1cdec012013-09-29 04:40:38 +00002343 // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
Alp Toker9cacbab2014-01-20 20:26:09 +00002344 QualType Ty = FPT->getParamType(1);
Richard Smith1cdec012013-09-29 04:40:38 +00002345 ASTContext &Ctx = getASTContext();
Richard Smithb47c36f2013-11-05 09:12:18 +00002346 if (Ctx.getLangOpts().SizedDeallocation &&
2347 Ctx.hasSameType(Ty, Ctx.getSizeType()))
Richard Smith1cdec012013-09-29 04:40:38 +00002348 return true;
Richard Smith8d0dc312013-07-21 23:12:18 +00002349 if (!Ty->isReferenceType())
2350 return false;
2351 Ty = Ty->getPointeeType();
2352 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2353 return false;
2354 // FIXME: Recognise nothrow_t in an inline namespace inside std?
2355 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2356 return RD && isNamed(RD, "nothrow_t") && isNamespaceStd(RD->getDeclContext());
2357}
2358
Richard Smithb47c36f2013-11-05 09:12:18 +00002359FunctionDecl *
2360FunctionDecl::getCorrespondingUnsizedGlobalDeallocationFunction() const {
2361 ASTContext &Ctx = getASTContext();
2362 if (!Ctx.getLangOpts().SizedDeallocation)
2363 return 0;
2364
2365 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2366 return 0;
2367 if (getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2368 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2369 return 0;
2370 if (isa<CXXRecordDecl>(getDeclContext()))
2371 return 0;
Richard Smithf6004412014-01-19 23:25:37 +00002372
2373 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2374 return 0;
Richard Smithb47c36f2013-11-05 09:12:18 +00002375
2376 if (getNumParams() != 2 || isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00002377 !Ctx.hasSameType(getType()->castAs<FunctionProtoType>()->getParamType(1),
Richard Smithb47c36f2013-11-05 09:12:18 +00002378 Ctx.getSizeType()))
2379 return 0;
2380
2381 // This is a sized deallocation function. Find the corresponding unsized
2382 // deallocation function.
2383 lookup_const_result R = getDeclContext()->lookup(getDeclName());
2384 for (lookup_const_result::iterator RI = R.begin(), RE = R.end(); RI != RE;
2385 ++RI)
2386 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*RI))
2387 if (FD->getNumParams() == 1 && !FD->isVariadic())
2388 return FD;
2389 return 0;
2390}
2391
Rafael Espindolaf4187652013-02-14 01:18:37 +00002392LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Rafael Espindolaf4187652013-02-14 01:18:37 +00002393 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002394}
2395
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002396bool FunctionDecl::isExternC() const {
2397 return isExternCTemplate(*this);
2398}
2399
Rafael Espindola593537a2013-05-05 20:15:21 +00002400bool FunctionDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002401 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002402}
2403
2404bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002405 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002406}
2407
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002408bool FunctionDecl::isGlobal() const {
2409 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2410 return Method->isStatic();
2411
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002412 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002413 return false;
2414
Mike Stump11289f42009-09-09 15:08:12 +00002415 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002416 DC->isNamespace();
2417 DC = DC->getParent()) {
2418 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2419 if (!Namespace->getDeclName())
2420 return false;
2421 break;
2422 }
2423 }
2424
2425 return true;
2426}
2427
Richard Smith10876ef2013-01-17 01:30:42 +00002428bool FunctionDecl::isNoReturn() const {
2429 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
Richard Smithdebc59d2013-01-30 05:45:05 +00002430 hasAttr<C11NoReturnAttr>() ||
Richard Smith10876ef2013-01-17 01:30:42 +00002431 getType()->getAs<FunctionType>()->getNoReturnAttr();
2432}
2433
Sebastian Redl833ef452010-01-26 22:01:41 +00002434void
2435FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002436 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002437
2438 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2439 FunctionTemplateDecl *PrevFunTmpl
2440 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
2441 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00002442 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002443 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002444
Axel Naumannfbc7b982011-11-08 18:21:06 +00002445 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002446 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002447}
2448
2449const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002450 return getFirstDecl();
Sebastian Redl833ef452010-01-26 22:01:41 +00002451}
2452
Rafael Espindola8db352d2013-10-17 15:37:26 +00002453FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002454
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002455/// \brief Returns a value indicating whether this function
2456/// corresponds to a builtin function.
2457///
2458/// The function corresponds to a built-in function if it is
2459/// declared at translation scope or within an extern "C" block and
2460/// its name matches with the name of a builtin. The returned value
2461/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002462/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002463/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002464unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002465 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002466 return 0;
2467
2468 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002469 if (!BuiltinID)
2470 return 0;
2471
2472 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00002473 if (Context.getLangOpts().CPlusPlus) {
2474 const LinkageSpecDecl *LinkageDecl = dyn_cast<LinkageSpecDecl>(
2475 getFirstDecl()->getDeclContext());
2476 // In C++, the first declaration of a builtin is always inside an implicit
2477 // extern "C".
2478 // FIXME: A recognised library function may not be directly in an extern "C"
2479 // declaration, for instance "extern "C" { namespace std { decl } }".
2480 if (!LinkageDecl || LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
2481 return 0;
2482 }
2483
2484 // If the function is marked "overloadable", it has a different mangled name
2485 // and is not the C library function.
Aaron Ballman9ead1242013-12-19 02:39:40 +00002486 if (hasAttr<OverloadableAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00002487 return 0;
2488
Douglas Gregore711f702009-02-14 18:57:46 +00002489 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2490 return BuiltinID;
2491
2492 // This function has the name of a known C library
2493 // function. Determine whether it actually refers to the C library
2494 // function or whether it just has the same name.
2495
Douglas Gregora908e7f2009-02-17 03:23:10 +00002496 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002497 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002498 return 0;
2499
Warren Hunt445d83e2013-11-01 23:46:51 +00002500 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002501}
2502
2503
Chris Lattner47c0d002009-04-25 06:03:53 +00002504/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002505/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002506/// after it has been created.
2507unsigned FunctionDecl::getNumParams() const {
Reid Kleckner0503a872013-12-05 01:23:43 +00002508 const FunctionProtoType *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002509 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002510}
2511
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002512void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002513 ArrayRef<ParmVarDecl *> NewParamInfo) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002514 assert(ParamInfo == 0 && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002515 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002516
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002517 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002518 if (!NewParamInfo.empty()) {
2519 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2520 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002521 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002522}
Chris Lattner41943152007-01-25 04:52:46 +00002523
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002524void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
James Molloy6f8780b2012-02-29 10:24:19 +00002525 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2526
2527 if (!NewDecls.empty()) {
2528 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2529 std::copy(NewDecls.begin(), NewDecls.end(), A);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002530 DeclsInPrototypeScope = ArrayRef<NamedDecl *>(A, NewDecls.size());
James Molloy6f8780b2012-02-29 10:24:19 +00002531 }
2532}
2533
Chris Lattner58258242008-04-10 02:22:51 +00002534/// getMinRequiredArguments - Returns the minimum number of arguments
2535/// needed to call this function. This may be fewer than the number of
2536/// function parameters, if some of the parameters have default
Richard Smith91151782014-04-01 19:18:16 +00002537/// arguments (in C++) or are parameter packs (C++11).
Chris Lattner58258242008-04-10 02:22:51 +00002538unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002539 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002540 return getNumParams();
Chris Lattner58258242008-04-10 02:22:51 +00002541
Richard Smith91151782014-04-01 19:18:16 +00002542 unsigned NumRequiredArgs = 0;
2543 for (auto *Param : params())
2544 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2545 ++NumRequiredArgs;
Chris Lattner58258242008-04-10 02:22:51 +00002546 return NumRequiredArgs;
2547}
2548
Eli Friedman1b125c32012-02-07 03:50:18 +00002549static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2550 // Only consider file-scope declarations in this test.
2551 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2552 return false;
2553
2554 // Only consider explicit declarations; the presence of a builtin for a
2555 // libcall shouldn't affect whether a definition is externally visible.
2556 if (Redecl->isImplicit())
2557 return false;
2558
2559 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2560 return true; // Not an inline definition
2561
2562 return false;
2563}
2564
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002565/// \brief For a function declaration in C or C++, determine whether this
2566/// declaration causes the definition to be externally visible.
2567///
Eli Friedman1b125c32012-02-07 03:50:18 +00002568/// Specifically, this determines if adding the current declaration to the set
2569/// of redeclarations of the given functions causes
2570/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002571bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2572 assert(!doesThisDeclarationHaveABody() &&
2573 "Must have a declaration without a body.");
2574
2575 ASTContext &Context = getASTContext();
2576
David Blaikiebbafb8a2012-03-11 07:00:24 +00002577 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002578 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2579 // an externally visible definition.
2580 //
2581 // FIXME: What happens if gnu_inline gets added on after the first
2582 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002583 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002584 return false;
2585
2586 const FunctionDecl *Prev = this;
2587 bool FoundBody = false;
2588 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002589 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002590
2591 if (Prev->Body) {
2592 // If it's not the case that both 'inline' and 'extern' are
2593 // specified on the definition, then it is always externally visible.
2594 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002595 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002596 return false;
2597 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002598 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002599 return false;
2600 }
2601 }
2602 return FoundBody;
2603 }
2604
David Blaikiebbafb8a2012-03-11 07:00:24 +00002605 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002606 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002607
2608 // C99 6.7.4p6:
2609 // [...] If all of the file scope declarations for a function in a
2610 // translation unit include the inline function specifier without extern,
2611 // then the definition in that translation unit is an inline definition.
2612 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002613 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002614 const FunctionDecl *Prev = this;
2615 bool FoundBody = false;
2616 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002617 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002618 if (RedeclForcesDefC99(Prev))
2619 return false;
2620 }
2621 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002622}
2623
Richard Smithf3814ad2013-01-25 00:08:28 +00002624/// \brief For an inline function definition in C, or for a gnu_inline function
2625/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002626///
2627/// Inline function definitions are always available for inlining optimizations.
2628/// However, depending on the language dialect, declaration specifiers, and
2629/// attributes, the definition of an inline function may or may not be
2630/// "externally" visible to other translation units in the program.
2631///
2632/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00002633/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00002634/// inline definition becomes externally visible (C99 6.7.4p6).
2635///
2636/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2637/// definition, we use the GNU semantics for inline, which are nearly the
2638/// opposite of C99 semantics. In particular, "inline" by itself will create
2639/// an externally visible symbol, but "extern inline" will not create an
2640/// externally visible symbol.
2641bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002642 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002643 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00002644 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00002645
David Blaikiebbafb8a2012-03-11 07:00:24 +00002646 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002647 // Note: If you change the logic here, please change
2648 // doesDeclarationForceExternallyVisibleDefinition as well.
2649 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00002650 // If it's not the case that both 'inline' and 'extern' are
2651 // specified on the definition, then this inline definition is
2652 // externally visible.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002653 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00002654 return true;
2655
2656 // If any declaration is 'inline' but not 'extern', then this definition
2657 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00002658 for (auto Redecl : redecls()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00002659 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002660 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00002661 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00002662 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00002663
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002664 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002665 }
Eli Friedman1b125c32012-02-07 03:50:18 +00002666
Richard Smithf3814ad2013-01-25 00:08:28 +00002667 // The rest of this function is C-only.
2668 assert(!Context.getLangOpts().CPlusPlus &&
2669 "should not use C inline rules in C++");
2670
Douglas Gregor299d76e2009-09-13 07:46:26 +00002671 // C99 6.7.4p6:
2672 // [...] If all of the file scope declarations for a function in a
2673 // translation unit include the inline function specifier without extern,
2674 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00002675 for (auto Redecl : redecls()) {
2676 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00002677 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002678 }
2679
2680 // C99 6.7.4p6:
2681 // An inline definition does not provide an external definition for the
2682 // function, and does not forbid an external definition in another
2683 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002684 return false;
2685}
2686
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002687/// getOverloadedOperator - Which C++ overloaded operator this
2688/// function represents, if any.
2689OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00002690 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2691 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002692 else
2693 return OO_None;
2694}
2695
Alexis Huntc88db062010-01-13 09:01:02 +00002696/// getLiteralIdentifier - The literal suffix identifier this function
2697/// represents, if any.
2698const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2699 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2700 return getDeclName().getCXXLiteralIdentifier();
2701 else
2702 return 0;
2703}
2704
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002705FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2706 if (TemplateOrSpecialization.isNull())
2707 return TK_NonTemplate;
2708 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2709 return TK_FunctionTemplate;
2710 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2711 return TK_MemberSpecialization;
2712 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2713 return TK_FunctionTemplateSpecialization;
2714 if (TemplateOrSpecialization.is
2715 <DependentFunctionTemplateSpecializationInfo*>())
2716 return TK_DependentFunctionTemplateSpecialization;
2717
David Blaikie83d382b2011-09-23 05:06:16 +00002718 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002719}
2720
Douglas Gregord801b062009-10-07 23:56:10 +00002721FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002722 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00002723 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2724
2725 return 0;
2726}
2727
2728void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002729FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2730 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00002731 TemplateSpecializationKind TSK) {
2732 assert(TemplateOrSpecialization.isNull() &&
2733 "Member function is already a specialization");
2734 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002735 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00002736 TemplateOrSpecialization = Info;
2737}
2738
Douglas Gregorafca3b42009-10-27 20:53:28 +00002739bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00002740 // If the function is invalid, it can't be implicitly instantiated.
2741 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00002742 return false;
2743
2744 switch (getTemplateSpecializationKind()) {
2745 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00002746 case TSK_ExplicitInstantiationDefinition:
2747 return false;
2748
2749 case TSK_ImplicitInstantiation:
2750 return true;
2751
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002752 // It is possible to instantiate TSK_ExplicitSpecialization kind
2753 // if the FunctionDecl has a class scope specialization pattern.
2754 case TSK_ExplicitSpecialization:
2755 return getClassScopeSpecializationPattern() != 0;
2756
Douglas Gregorafca3b42009-10-27 20:53:28 +00002757 case TSK_ExplicitInstantiationDeclaration:
2758 // Handled below.
2759 break;
2760 }
2761
2762 // Find the actual template from which we will instantiate.
2763 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002764 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00002765 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002766 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00002767
2768 // C++0x [temp.explicit]p9:
2769 // Except for inline functions, other explicit instantiation declarations
2770 // have the effect of suppressing the implicit instantiation of the entity
2771 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002772 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00002773 return true;
2774
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002775 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00002776}
2777
2778bool FunctionDecl::isTemplateInstantiation() const {
2779 switch (getTemplateSpecializationKind()) {
2780 case TSK_Undeclared:
2781 case TSK_ExplicitSpecialization:
2782 return false;
2783 case TSK_ImplicitInstantiation:
2784 case TSK_ExplicitInstantiationDeclaration:
2785 case TSK_ExplicitInstantiationDefinition:
2786 return true;
2787 }
2788 llvm_unreachable("All TSK values handled.");
2789}
Douglas Gregorafca3b42009-10-27 20:53:28 +00002790
2791FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002792 // Handle class scope explicit specialization special case.
2793 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2794 return getClassScopeSpecializationPattern();
2795
Douglas Gregorafca3b42009-10-27 20:53:28 +00002796 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2797 while (Primary->getInstantiatedFromMemberTemplate()) {
2798 // If we have hit a point where the user provided a specialization of
2799 // this template, we're done looking.
2800 if (Primary->isMemberSpecialization())
2801 break;
2802
2803 Primary = Primary->getInstantiatedFromMemberTemplate();
2804 }
2805
2806 return Primary->getTemplatedDecl();
2807 }
2808
2809 return getInstantiatedFromMemberFunction();
2810}
2811
Douglas Gregor70d83e22009-06-29 17:30:29 +00002812FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00002813 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002814 = TemplateOrSpecialization
2815 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00002816 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00002817 }
2818 return 0;
2819}
2820
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002821FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2822 return getASTContext().getClassScopeSpecializationPattern(this);
2823}
2824
Douglas Gregor70d83e22009-06-29 17:30:29 +00002825const TemplateArgumentList *
2826FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00002827 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00002828 = TemplateOrSpecialization
2829 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00002830 return Info->TemplateArguments;
2831 }
2832 return 0;
2833}
2834
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00002835const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002836FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2837 if (FunctionTemplateSpecializationInfo *Info
2838 = TemplateOrSpecialization
2839 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2840 return Info->TemplateArgumentsAsWritten;
2841 }
2842 return 0;
2843}
2844
Mike Stump11289f42009-09-09 15:08:12 +00002845void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002846FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2847 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002848 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002849 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002850 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00002851 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2852 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002853 assert(TSK != TSK_Undeclared &&
2854 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00002855 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002856 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002857 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00002858 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2859 TemplateArgs,
2860 TemplateArgsAsWritten,
2861 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002862 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00002863 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002864}
2865
John McCallb9c78482010-04-08 09:05:18 +00002866void
2867FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2868 const UnresolvedSetImpl &Templates,
2869 const TemplateArgumentListInfo &TemplateArgs) {
2870 assert(TemplateOrSpecialization.isNull());
2871 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2872 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall900d9802010-04-13 22:18:28 +00002873 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallb9c78482010-04-08 09:05:18 +00002874 void *Buffer = Context.Allocate(Size);
2875 DependentFunctionTemplateSpecializationInfo *Info =
2876 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2877 TemplateArgs);
2878 TemplateOrSpecialization = Info;
2879}
2880
2881DependentFunctionTemplateSpecializationInfo::
2882DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2883 const TemplateArgumentListInfo &TArgs)
2884 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2885
2886 d.NumTemplates = Ts.size();
2887 d.NumArgs = TArgs.size();
2888
2889 FunctionTemplateDecl **TsArray =
2890 const_cast<FunctionTemplateDecl**>(getTemplates());
2891 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2892 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2893
2894 TemplateArgumentLoc *ArgsArray =
2895 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2896 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2897 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2898}
2899
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002900TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00002901 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002902 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00002903 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00002904 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00002905 if (FTSInfo)
2906 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00002907
Douglas Gregord801b062009-10-07 23:56:10 +00002908 MemberSpecializationInfo *MSInfo
2909 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2910 if (MSInfo)
2911 return MSInfo->getTemplateSpecializationKind();
2912
2913 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002914}
2915
Mike Stump11289f42009-09-09 15:08:12 +00002916void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002917FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2918 SourceLocation PointOfInstantiation) {
2919 if (FunctionTemplateSpecializationInfo *FTSInfo
2920 = TemplateOrSpecialization.dyn_cast<
2921 FunctionTemplateSpecializationInfo*>()) {
2922 FTSInfo->setTemplateSpecializationKind(TSK);
2923 if (TSK != TSK_ExplicitSpecialization &&
2924 PointOfInstantiation.isValid() &&
2925 FTSInfo->getPointOfInstantiation().isInvalid())
2926 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2927 } else if (MemberSpecializationInfo *MSInfo
2928 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2929 MSInfo->setTemplateSpecializationKind(TSK);
2930 if (TSK != TSK_ExplicitSpecialization &&
2931 PointOfInstantiation.isValid() &&
2932 MSInfo->getPointOfInstantiation().isInvalid())
2933 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2934 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002935 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002936}
2937
2938SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00002939 if (FunctionTemplateSpecializationInfo *FTSInfo
2940 = TemplateOrSpecialization.dyn_cast<
2941 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002942 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00002943 else if (MemberSpecializationInfo *MSInfo
2944 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002945 return MSInfo->getPointOfInstantiation();
2946
2947 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00002948}
2949
Douglas Gregor6411b922009-09-11 20:15:17 +00002950bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002951 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00002952 return true;
2953
2954 // If this function was instantiated from a member function of a
2955 // class template, check whether that member function was defined out-of-line.
2956 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2957 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002958 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002959 return Definition->isOutOfLine();
2960 }
2961
2962 // If this function was instantiated from a function template,
2963 // check whether that function template was defined out-of-line.
2964 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2965 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002966 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002967 return Definition->isOutOfLine();
2968 }
2969
2970 return false;
2971}
2972
Abramo Bagnaraea947882011-03-08 16:41:52 +00002973SourceRange FunctionDecl::getSourceRange() const {
2974 return SourceRange(getOuterLocStart(), EndRangeLoc);
2975}
2976
Anna Zaks28db7ce2012-01-18 02:45:01 +00002977unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00002978 IdentifierInfo *FnInfo = getIdentifier();
2979
2980 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00002981 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002982
2983 // Builtin handling.
2984 switch (getBuiltinID()) {
2985 case Builtin::BI__builtin_memset:
2986 case Builtin::BI__builtin___memset_chk:
2987 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00002988 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00002989
2990 case Builtin::BI__builtin_memcpy:
2991 case Builtin::BI__builtin___memcpy_chk:
2992 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00002993 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002994
2995 case Builtin::BI__builtin_memmove:
2996 case Builtin::BI__builtin___memmove_chk:
2997 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00002998 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00002999
3000 case Builtin::BIstrlcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003001 return Builtin::BIstrlcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003002 case Builtin::BIstrlcat:
Anna Zaks22122702012-01-17 00:37:07 +00003003 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003004
3005 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003006 case Builtin::BImemcmp:
3007 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003008
3009 case Builtin::BI__builtin_strncpy:
3010 case Builtin::BI__builtin___strncpy_chk:
3011 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003012 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003013
3014 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003015 case Builtin::BIstrncmp:
3016 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003017
3018 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003019 case Builtin::BIstrncasecmp:
3020 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003021
3022 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003023 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003024 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003025 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003026
3027 case Builtin::BI__builtin_strndup:
3028 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003029 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003030
Anna Zaks314cd092012-02-01 19:08:57 +00003031 case Builtin::BI__builtin_strlen:
3032 case Builtin::BIstrlen:
3033 return Builtin::BIstrlen;
3034
Anna Zaks201d4892012-01-13 21:52:01 +00003035 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003036 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003037 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003038 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003039 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003040 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003041 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003042 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003043 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003044 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003045 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003046 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003047 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003048 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003049 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003050 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003051 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003052 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003053 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003054 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003055 else if (FnInfo->isStr("strlen"))
3056 return Builtin::BIstrlen;
Anna Zaks201d4892012-01-13 21:52:01 +00003057 }
3058 break;
3059 }
Anna Zaks22122702012-01-17 00:37:07 +00003060 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003061}
3062
Chris Lattner59a25942008-03-31 00:36:02 +00003063//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003064// FieldDecl Implementation
3065//===----------------------------------------------------------------------===//
3066
Jay Foad39c79802011-01-12 09:06:06 +00003067FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003068 SourceLocation StartLoc, SourceLocation IdLoc,
3069 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003070 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003071 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003072 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3073 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003074}
3075
Douglas Gregor72172e92012-01-05 21:55:30 +00003076FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003077 return new (C, ID) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
3078 0, QualType(), 0, 0, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00003079}
3080
Sebastian Redl833ef452010-01-26 22:01:41 +00003081bool FieldDecl::isAnonymousStructOrUnion() const {
3082 if (!isImplicit() || getDeclName())
3083 return false;
3084
3085 if (const RecordType *Record = getType()->getAs<RecordType>())
3086 return Record->getDecl()->isAnonymousStructOrUnion();
3087
3088 return false;
3089}
3090
Richard Smithcaf33902011-10-10 18:28:20 +00003091unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3092 assert(isBitField() && "not a bitfield");
3093 Expr *BitWidth = InitializerOrBitWidth.getPointer();
3094 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3095}
3096
John McCall4e819612011-01-20 07:57:12 +00003097unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00003098 const FieldDecl *Canonical = getCanonicalDecl();
3099 if (Canonical != this)
3100 return Canonical->getFieldIndex();
3101
John McCall4e819612011-01-20 07:57:12 +00003102 if (CachedFieldIndex) return CachedFieldIndex - 1;
3103
Richard Smithd62306a2011-11-10 06:34:14 +00003104 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00003105 const RecordDecl *RD = getParent();
Richard Smithd62306a2011-11-10 06:34:14 +00003106
3107 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
Eli Friedman2782dac2013-06-26 20:50:34 +00003108 I != E; ++I, ++Index)
Richard Smith0b87e072013-10-07 08:02:11 +00003109 I->getCanonicalDecl()->CachedFieldIndex = Index + 1;
John McCall4e819612011-01-20 07:57:12 +00003110
Richard Smithd62306a2011-11-10 06:34:14 +00003111 assert(CachedFieldIndex && "failed to find field in parent");
3112 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00003113}
3114
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003115SourceRange FieldDecl::getSourceRange() const {
Abramo Bagnaraff371ac2011-08-05 08:02:55 +00003116 if (const Expr *E = InitializerOrBitWidth.getPointer())
3117 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00003118 return DeclaratorDecl::getSourceRange();
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003119}
3120
Abramo Bagnarab1cdde72012-07-02 20:35:48 +00003121void FieldDecl::setBitWidth(Expr *Width) {
3122 assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
3123 "bit width or initializer already set");
3124 InitializerOrBitWidth.setPointer(Width);
3125}
3126
Richard Smith938f40b2011-06-11 17:19:42 +00003127void FieldDecl::setInClassInitializer(Expr *Init) {
Richard Smith2b013182012-06-10 03:12:00 +00003128 assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
Richard Smith938f40b2011-06-11 17:19:42 +00003129 "bit width or initializer already set");
3130 InitializerOrBitWidth.setPointer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003131}
3132
Sebastian Redl833ef452010-01-26 22:01:41 +00003133//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003134// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00003135//===----------------------------------------------------------------------===//
3136
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003137SourceLocation TagDecl::getOuterLocStart() const {
3138 return getTemplateOrInnerLocStart(this);
3139}
3140
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003141SourceRange TagDecl::getSourceRange() const {
3142 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003143 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003144}
3145
Rafael Espindola8db352d2013-10-17 15:37:26 +00003146TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00003147
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00003148void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer50ce8352013-09-17 23:57:10 +00003149 NamedDeclOrQualifier = TDD;
Douglas Gregora72a4e32010-05-19 18:39:18 +00003150 if (TypeForDecl)
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003151 assert(TypeForDecl->isLinkageValid());
3152 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00003153}
3154
Douglas Gregordee1be82009-01-17 00:42:38 +00003155void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003156 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00003157
David Blaikie095deba2012-11-14 01:52:05 +00003158 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
John McCall67da35c2010-02-04 22:26:26 +00003159 struct CXXRecordDecl::DefinitionData *Data =
3160 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00003161 for (auto I : redecls())
3162 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00003163 }
Douglas Gregordee1be82009-01-17 00:42:38 +00003164}
3165
3166void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00003167 assert((!isa<CXXRecordDecl>(this) ||
3168 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3169 "definition completed but not started");
3170
John McCallf937c022011-10-07 06:10:15 +00003171 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003172 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00003173
3174 if (ASTMutationListener *L = getASTMutationListener())
3175 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00003176}
3177
John McCallf937c022011-10-07 06:10:15 +00003178TagDecl *TagDecl::getDefinition() const {
3179 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003180 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003181
3182 // If it's possible for us to have an out-of-date definition, check now.
3183 if (MayHaveOutOfDateDef) {
3184 if (IdentifierInfo *II = getIdentifier()) {
3185 if (II->isOutOfDate()) {
3186 updateOutOfDate(*II);
3187 }
3188 }
3189 }
3190
Andrew Trickba266ee2010-10-19 21:54:32 +00003191 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
3192 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003193
Aaron Ballman86c93902014-03-06 23:45:36 +00003194 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00003195 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00003196 return R;
Mike Stump11289f42009-09-09 15:08:12 +00003197
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003198 return 0;
Ted Kremenek21475702008-09-05 17:16:31 +00003199}
3200
Douglas Gregor14454802011-02-25 02:25:35 +00003201void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3202 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00003203 // Make sure the extended qualifier info is allocated.
3204 if (!hasExtInfo())
David Majnemer50ce8352013-09-17 23:57:10 +00003205 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00003206 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00003207 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003208 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00003209 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00003210 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00003211 if (getExtInfo()->NumTemplParamLists == 0) {
3212 getASTContext().Deallocate(getExtInfo());
David Majnemer50ce8352013-09-17 23:57:10 +00003213 NamedDeclOrQualifier = (TypedefNameDecl*) 0;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003214 }
3215 else
3216 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00003217 }
3218 }
3219}
3220
Abramo Bagnara60804e12011-03-18 15:16:37 +00003221void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
3222 unsigned NumTPLists,
3223 TemplateParameterList **TPLists) {
3224 assert(NumTPLists > 0);
3225 // Make sure the extended decl info is allocated.
3226 if (!hasExtInfo())
3227 // Allocate external info struct.
David Majnemer50ce8352013-09-17 23:57:10 +00003228 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003229 // Set the template parameter lists info.
3230 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
3231}
3232
Ted Kremenek21475702008-09-05 17:16:31 +00003233//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003234// EnumDecl Implementation
3235//===----------------------------------------------------------------------===//
3236
David Blaikie68e081d2011-12-20 02:48:34 +00003237void EnumDecl::anchor() { }
3238
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003239EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3240 SourceLocation StartLoc, SourceLocation IdLoc,
3241 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00003242 EnumDecl *PrevDecl, bool IsScoped,
3243 bool IsScopedUsingClassTag, bool IsFixed) {
Richard Smithf7981722013-11-22 09:01:48 +00003244 EnumDecl *Enum = new (C, DC) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
3245 IsScoped, IsScopedUsingClassTag,
3246 IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003247 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00003248 C.getTypeDeclType(Enum, PrevDecl);
3249 return Enum;
3250}
3251
Douglas Gregor72172e92012-01-05 21:55:30 +00003252EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003253 EnumDecl *Enum = new (C, ID) EnumDecl(0, SourceLocation(), SourceLocation(),
3254 0, 0, false, false, false);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003255 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3256 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003257}
3258
Alp Tokerb9fa5122014-01-06 11:31:18 +00003259SourceRange EnumDecl::getIntegerTypeRange() const {
3260 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3261 return TI->getTypeLoc().getSourceRange();
3262 return SourceRange();
3263}
3264
Douglas Gregord5058122010-02-11 01:19:42 +00003265void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00003266 QualType NewPromotionType,
3267 unsigned NumPositiveBits,
3268 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00003269 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00003270 if (!IntegerType)
3271 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00003272 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00003273 setNumPositiveBits(NumPositiveBits);
3274 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00003275 TagDecl::completeDefinition();
3276}
3277
Richard Smith7d137e32012-03-23 03:33:32 +00003278TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3279 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3280 return MSI->getTemplateSpecializationKind();
3281
3282 return TSK_Undeclared;
3283}
3284
3285void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3286 SourceLocation PointOfInstantiation) {
3287 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3288 assert(MSI && "Not an instantiated member enumeration?");
3289 MSI->setTemplateSpecializationKind(TSK);
3290 if (TSK != TSK_ExplicitSpecialization &&
3291 PointOfInstantiation.isValid() &&
3292 MSI->getPointOfInstantiation().isInvalid())
3293 MSI->setPointOfInstantiation(PointOfInstantiation);
3294}
3295
Richard Smith4b38ded2012-03-14 23:13:10 +00003296EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3297 if (SpecializationInfo)
3298 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3299
3300 return 0;
3301}
3302
3303void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3304 TemplateSpecializationKind TSK) {
3305 assert(!SpecializationInfo && "Member enum is already a specialization");
3306 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3307}
3308
Sebastian Redl833ef452010-01-26 22:01:41 +00003309//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003310// RecordDecl Implementation
3311//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003312
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003313RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
3314 SourceLocation StartLoc, SourceLocation IdLoc,
3315 IdentifierInfo *Id, RecordDecl *PrevDecl)
3316 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003317 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003318 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003319 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00003320 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003321 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00003322 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003323}
3324
Jay Foad39c79802011-01-12 09:06:06 +00003325RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003326 SourceLocation StartLoc, SourceLocation IdLoc,
3327 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smithf7981722013-11-22 09:01:48 +00003328 RecordDecl* R = new (C, DC) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
3329 PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003330 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3331
Ted Kremenek21475702008-09-05 17:16:31 +00003332 C.getTypeDeclType(R, PrevDecl);
3333 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003334}
3335
Douglas Gregor72172e92012-01-05 21:55:30 +00003336RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003337 RecordDecl *R = new (C, ID) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
3338 SourceLocation(), 0, 0);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003339 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3340 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003341}
3342
Douglas Gregordfcad112009-03-25 15:59:44 +00003343bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003344 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003345 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3346}
3347
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003348RecordDecl::field_iterator RecordDecl::field_begin() const {
3349 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3350 LoadFieldsFromExternalStorage();
3351
3352 return field_iterator(decl_iterator(FirstDecl));
3353}
3354
Douglas Gregorb11aad82011-02-19 18:51:44 +00003355/// completeDefinition - Notes that the definition of this type is now
3356/// complete.
3357void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003358 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003359 TagDecl::completeDefinition();
3360}
3361
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003362/// isMsStruct - Get whether or not this record uses ms_struct layout.
3363/// This which can be turned on with an attribute, pragma, or the
3364/// -mms-bitfields command-line option.
3365bool RecordDecl::isMsStruct(const ASTContext &C) const {
3366 return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3367}
3368
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003369static bool isFieldOrIndirectField(Decl::Kind K) {
3370 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3371}
3372
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003373void RecordDecl::LoadFieldsFromExternalStorage() const {
3374 ExternalASTSource *Source = getASTContext().getExternalSource();
3375 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3376
3377 // Notify that we have a RecordDecl doing some initialization.
3378 ExternalASTSource::Deserializing TheFields(Source);
3379
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003380 SmallVector<Decl*, 64> Decls;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003381 LoadedFieldsFromExternalStorage = true;
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003382 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3383 Decls)) {
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003384 case ELR_Success:
3385 break;
3386
3387 case ELR_AlreadyLoaded:
3388 case ELR_Failure:
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003389 return;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003390 }
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003391
3392#ifndef NDEBUG
3393 // Check that all decls we got were FieldDecls.
3394 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003395 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003396#endif
3397
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003398 if (Decls.empty())
3399 return;
3400
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003401 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003402 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003403}
3404
Steve Naroff415d3d52008-10-08 17:01:13 +00003405//===----------------------------------------------------------------------===//
3406// BlockDecl Implementation
3407//===----------------------------------------------------------------------===//
3408
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003409void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Steve Naroffc4b30e52009-03-13 16:56:44 +00003410 assert(ParamInfo == 0 && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00003411
Steve Naroffc4b30e52009-03-13 16:56:44 +00003412 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003413 if (!NewParamInfo.empty()) {
3414 NumParams = NewParamInfo.size();
3415 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3416 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003417 }
3418}
3419
John McCall351762c2011-02-07 10:33:21 +00003420void BlockDecl::setCaptures(ASTContext &Context,
3421 const Capture *begin,
3422 const Capture *end,
3423 bool capturesCXXThis) {
John McCallc63de662011-02-02 13:00:07 +00003424 CapturesCXXThis = capturesCXXThis;
3425
3426 if (begin == end) {
John McCall351762c2011-02-07 10:33:21 +00003427 NumCaptures = 0;
3428 Captures = 0;
John McCallc63de662011-02-02 13:00:07 +00003429 return;
3430 }
3431
John McCall351762c2011-02-07 10:33:21 +00003432 NumCaptures = end - begin;
3433
3434 // Avoid new Capture[] because we don't want to provide a default
3435 // constructor.
3436 size_t allocationSize = NumCaptures * sizeof(Capture);
3437 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3438 memcpy(buffer, begin, allocationSize);
3439 Captures = static_cast<Capture*>(buffer);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003440}
Sebastian Redl833ef452010-01-26 22:01:41 +00003441
John McCallce45f882011-06-15 22:51:16 +00003442bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00003443 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00003444 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00003445 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00003446 return true;
3447
3448 return false;
3449}
3450
Douglas Gregor70226da2010-12-21 16:27:07 +00003451SourceRange BlockDecl::getSourceRange() const {
3452 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3453}
Sebastian Redl833ef452010-01-26 22:01:41 +00003454
3455//===----------------------------------------------------------------------===//
3456// Other Decl Allocation/Deallocation Method Implementations
3457//===----------------------------------------------------------------------===//
3458
David Blaikie68e081d2011-12-20 02:48:34 +00003459void TranslationUnitDecl::anchor() { }
3460
Sebastian Redl833ef452010-01-26 22:01:41 +00003461TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Richard Smithf7981722013-11-22 09:01:48 +00003462 return new (C, (DeclContext*)0) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00003463}
3464
David Blaikie68e081d2011-12-20 02:48:34 +00003465void LabelDecl::anchor() { }
3466
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003467LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003468 SourceLocation IdentL, IdentifierInfo *II) {
Richard Smithf7981722013-11-22 09:01:48 +00003469 return new (C, DC) LabelDecl(DC, IdentL, II, 0, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003470}
3471
3472LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3473 SourceLocation IdentL, IdentifierInfo *II,
3474 SourceLocation GnuLabelL) {
3475 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Richard Smithf7981722013-11-22 09:01:48 +00003476 return new (C, DC) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003477}
3478
Douglas Gregor72172e92012-01-05 21:55:30 +00003479LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003480 return new (C, ID) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00003481}
3482
David Blaikie68e081d2011-12-20 02:48:34 +00003483void ValueDecl::anchor() { }
3484
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003485bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00003486 for (const auto *I : attrs())
3487 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003488 return true;
3489
3490 return isWeakImported();
3491}
3492
David Blaikie68e081d2011-12-20 02:48:34 +00003493void ImplicitParamDecl::anchor() { }
3494
Sebastian Redl833ef452010-01-26 22:01:41 +00003495ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003496 SourceLocation IdLoc,
3497 IdentifierInfo *Id,
3498 QualType Type) {
Richard Smithf7981722013-11-22 09:01:48 +00003499 return new (C, DC) ImplicitParamDecl(DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00003500}
3501
Richard Smithf7981722013-11-22 09:01:48 +00003502ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00003503 unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003504 return new (C, ID) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
Douglas Gregor72172e92012-01-05 21:55:30 +00003505}
3506
Sebastian Redl833ef452010-01-26 22:01:41 +00003507FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003508 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003509 const DeclarationNameInfo &NameInfo,
3510 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003511 StorageClass SC,
Richard Smithf7981722013-11-22 09:01:48 +00003512 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00003513 bool hasWrittenPrototype,
3514 bool isConstexprSpecified) {
Richard Smithf7981722013-11-22 09:01:48 +00003515 FunctionDecl *New =
3516 new (C, DC) FunctionDecl(Function, DC, StartLoc, NameInfo, T, TInfo, SC,
3517 isInlineSpecified, isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00003518 New->HasWrittenPrototype = hasWrittenPrototype;
3519 return New;
3520}
3521
Douglas Gregor72172e92012-01-05 21:55:30 +00003522FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003523 return new (C, ID) FunctionDecl(Function, 0, SourceLocation(),
3524 DeclarationNameInfo(), QualType(), 0,
3525 SC_None, false, false);
Douglas Gregor72172e92012-01-05 21:55:30 +00003526}
3527
Sebastian Redl833ef452010-01-26 22:01:41 +00003528BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00003529 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00003530}
3531
Douglas Gregor72172e92012-01-05 21:55:30 +00003532BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003533 return new (C, ID) BlockDecl(0, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00003534}
3535
Ben Langmuir37943a72013-05-03 19:00:33 +00003536CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
3537 unsigned NumParams) {
Richard Smithf7981722013-11-22 09:01:48 +00003538 return new (C, DC, NumParams * sizeof(ImplicitParamDecl *))
3539 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003540}
3541
Ben Langmuirce914fc2013-05-03 19:20:19 +00003542CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00003543 unsigned NumParams) {
3544 return new (C, ID, NumParams * sizeof(ImplicitParamDecl *))
3545 CapturedDecl(0, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00003546}
3547
Sebastian Redl833ef452010-01-26 22:01:41 +00003548EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3549 SourceLocation L,
3550 IdentifierInfo *Id, QualType T,
3551 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00003552 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00003553}
3554
Douglas Gregor72172e92012-01-05 21:55:30 +00003555EnumConstantDecl *
3556EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003557 return new (C, ID) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
3558 llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00003559}
3560
David Blaikie68e081d2011-12-20 02:48:34 +00003561void IndirectFieldDecl::anchor() { }
3562
Benjamin Kramer39593702010-11-21 14:11:41 +00003563IndirectFieldDecl *
3564IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3565 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3566 unsigned CHS) {
Richard Smithf7981722013-11-22 09:01:48 +00003567 return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003568}
3569
Douglas Gregor72172e92012-01-05 21:55:30 +00003570IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3571 unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003572 return new (C, ID) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
3573 QualType(), 0, 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00003574}
3575
Douglas Gregorbe996932010-09-01 20:41:53 +00003576SourceRange EnumConstantDecl::getSourceRange() const {
3577 SourceLocation End = getLocation();
3578 if (Init)
3579 End = Init->getLocEnd();
3580 return SourceRange(getLocation(), End);
3581}
3582
David Blaikie68e081d2011-12-20 02:48:34 +00003583void TypeDecl::anchor() { }
3584
Sebastian Redl833ef452010-01-26 22:01:41 +00003585TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003586 SourceLocation StartLoc, SourceLocation IdLoc,
3587 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smithf7981722013-11-22 09:01:48 +00003588 return new (C, DC) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00003589}
3590
David Blaikie68e081d2011-12-20 02:48:34 +00003591void TypedefNameDecl::anchor() { }
3592
Douglas Gregor72172e92012-01-05 21:55:30 +00003593TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003594 return new (C, ID) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00003595}
3596
Richard Smithdda56e42011-04-15 14:24:37 +00003597TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3598 SourceLocation StartLoc,
3599 SourceLocation IdLoc, IdentifierInfo *Id,
3600 TypeSourceInfo *TInfo) {
Richard Smithf7981722013-11-22 09:01:48 +00003601 return new (C, DC) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00003602}
3603
Douglas Gregor72172e92012-01-05 21:55:30 +00003604TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003605 return new (C, ID) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00003606}
3607
Abramo Bagnaraea947882011-03-08 16:41:52 +00003608SourceRange TypedefDecl::getSourceRange() const {
3609 SourceLocation RangeEnd = getLocation();
3610 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3611 if (typeIsPostfix(TInfo->getType()))
3612 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3613 }
3614 return SourceRange(getLocStart(), RangeEnd);
3615}
3616
Richard Smithdda56e42011-04-15 14:24:37 +00003617SourceRange TypeAliasDecl::getSourceRange() const {
3618 SourceLocation RangeEnd = getLocStart();
3619 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3620 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3621 return SourceRange(getLocStart(), RangeEnd);
3622}
3623
David Blaikie68e081d2011-12-20 02:48:34 +00003624void FileScopeAsmDecl::anchor() { }
3625
Sebastian Redl833ef452010-01-26 22:01:41 +00003626FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00003627 StringLiteral *Str,
3628 SourceLocation AsmLoc,
3629 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00003630 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00003631}
Douglas Gregorba345522011-12-02 23:23:56 +00003632
Richard Smithf7981722013-11-22 09:01:48 +00003633FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00003634 unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003635 return new (C, ID) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00003636}
3637
Michael Han84324352013-02-22 17:15:32 +00003638void EmptyDecl::anchor() {}
3639
3640EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00003641 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00003642}
3643
3644EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003645 return new (C, ID) EmptyDecl(0, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00003646}
3647
Douglas Gregorba345522011-12-02 23:23:56 +00003648//===----------------------------------------------------------------------===//
3649// ImportDecl Implementation
3650//===----------------------------------------------------------------------===//
3651
3652/// \brief Retrieve the number of module identifiers needed to name the given
3653/// module.
3654static unsigned getNumModuleIdentifiers(Module *Mod) {
3655 unsigned Result = 1;
3656 while (Mod->Parent) {
3657 Mod = Mod->Parent;
3658 ++Result;
3659 }
3660 return Result;
3661}
3662
Douglas Gregor22d09742012-01-03 18:04:46 +00003663ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003664 Module *Imported,
3665 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00003666 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003667 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003668{
3669 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3670 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3671 memcpy(StoredLocs, IdentifierLocs.data(),
3672 IdentifierLocs.size() * sizeof(SourceLocation));
3673}
3674
Douglas Gregor22d09742012-01-03 18:04:46 +00003675ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003676 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00003677 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003678 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003679{
3680 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3681}
3682
Richard Smithf7981722013-11-22 09:01:48 +00003683ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003684 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00003685 ArrayRef<SourceLocation> IdentifierLocs) {
Richard Smithf7981722013-11-22 09:01:48 +00003686 return new (C, DC, IdentifierLocs.size() * sizeof(SourceLocation))
3687 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00003688}
3689
Richard Smithf7981722013-11-22 09:01:48 +00003690ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003691 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00003692 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00003693 SourceLocation EndLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00003694 ImportDecl *Import =
3695 new (C, DC, sizeof(SourceLocation)) ImportDecl(DC, StartLoc,
3696 Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00003697 Import->setImplicit();
3698 return Import;
3699}
3700
Douglas Gregor72172e92012-01-05 21:55:30 +00003701ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3702 unsigned NumLocations) {
Richard Smithf7981722013-11-22 09:01:48 +00003703 return new (C, ID, NumLocations * sizeof(SourceLocation))
3704 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00003705}
3706
3707ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3708 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003709 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00003710
3711 const SourceLocation *StoredLocs
3712 = reinterpret_cast<const SourceLocation *>(this + 1);
3713 return ArrayRef<SourceLocation>(StoredLocs,
3714 getNumModuleIdentifiers(getImportedModule()));
3715}
3716
3717SourceRange ImportDecl::getSourceRange() const {
3718 if (!ImportedAndComplete.getInt())
3719 return SourceRange(getLocation(),
3720 *reinterpret_cast<const SourceLocation *>(this + 1));
3721
3722 return SourceRange(getLocation(), getIdentifierLocs().back());
3723}