blob: 08a6490f1400c2305ab6862b855a0198b2d0ff67 [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"
Faisal Valib90b2112014-04-03 16:32:21 +000016#include "clang/AST/ASTLambda.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/Attr.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000022#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000024#include "clang/AST/PrettyPrinter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000025#include "clang/AST/Stmt.h"
26#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000027#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000028#include "clang/Basic/IdentifierTable.h"
Douglas Gregorba345522011-12-02 23:23:56 +000029#include "clang/Basic/Module.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000030#include "clang/Basic/Specifiers.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000031#include "clang/Basic/TargetInfo.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000032#include "llvm/Support/ErrorHandling.h"
David Blaikie9c70e042011-09-21 18:16:56 +000033#include <algorithm>
34
Chris Lattner6d9a6852006-10-25 05:11:20 +000035using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000036
Richard Smith0b87e072013-10-07 08:02:11 +000037Decl *clang::getPrimaryMergedDecl(Decl *D) {
38 return D->getASTContext().getPrimaryMergedDecl(D);
39}
40
Richard Smith73b21d82014-09-03 02:33:22 +000041// Defined here so that it can be inlined into its direct callers.
42bool Decl::isOutOfLine() const {
43 return !getLexicalDeclContext()->Equals(getDeclContext());
44}
45
Chris Lattner88f70d62008-03-15 05:43:15 +000046//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000047// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000048//===----------------------------------------------------------------------===//
49
John McCalldf25c432013-02-16 00:17:33 +000050// Visibility rules aren't rigorously externally specified, but here
51// are the basic principles behind what we implement:
52//
53// 1. An explicit visibility attribute is generally a direct expression
54// of the user's intent and should be honored. Only the innermost
55// visibility attribute applies. If no visibility attribute applies,
56// global visibility settings are considered.
57//
58// 2. There is one caveat to the above: on or in a template pattern,
59// an explicit visibility attribute is just a default rule, and
60// visibility can be decreased by the visibility of template
61// arguments. But this, too, has an exception: an attribute on an
62// explicit specialization or instantiation causes all the visibility
63// restrictions of the template arguments to be ignored.
64//
65// 3. A variable that does not otherwise have explicit visibility can
66// be restricted by the visibility of its type.
67//
68// 4. A visibility restriction is explicit if it comes from an
69// attribute (or something like it), not a global visibility setting.
70// When emitting a reference to an external symbol, visibility
71// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +000072//
73// 5. When computing the visibility of a non-type, including a
74// non-type member of a class, only non-type visibility restrictions
75// are considered: the 'visibility' attribute, global value-visibility
76// settings, and a few special cases like __private_extern.
77//
78// 6. When computing the visibility of a type, including a type member
79// of a class, only type visibility restrictions are considered:
80// the 'type_visibility' attribute and global type-visibility settings.
81// However, a 'visibility' attribute counts as a 'type_visibility'
82// attribute on any declaration that only has the former.
83//
84// The visibility of a "secondary" entity, like a template argument,
85// is computed using the kind of that entity, not the kind of the
86// primary entity for which we are computing visibility. For example,
87// the visibility of a specialization of either of these templates:
88// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
89// template <class T, bool (&compare)(T, X)> class matcher;
90// is restricted according to the type visibility of the argument 'T',
91// the type visibility of 'bool(&)(T,X)', and the value visibility of
92// the argument function 'compare'. That 'has_match' is a value
93// and 'matcher' is a type only matters when looking for attributes
94// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +000095
John McCall5f46c482013-02-21 23:42:58 +000096const unsigned IgnoreExplicitVisibilityBit = 2;
Rafael Espindola9551d3b2013-05-28 19:43:11 +000097const unsigned IgnoreAllVisibilityBit = 4;
John McCall5f46c482013-02-21 23:42:58 +000098
John McCalldf25c432013-02-16 00:17:33 +000099/// Kinds of LV computation. The linkage side of the computation is
100/// always the same, but different things can change how visibility is
101/// computed.
102enum LVComputationKind {
John McCall5f46c482013-02-21 23:42:58 +0000103 /// Do an LV computation for, ultimately, a type.
104 /// Visibility may be restricted by type visibility settings and
105 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000106 LVForType = NamedDecl::VisibilityForType,
John McCalldf25c432013-02-16 00:17:33 +0000107
John McCall5f46c482013-02-21 23:42:58 +0000108 /// Do an LV computation for, ultimately, a non-type declaration.
109 /// Visibility may be restricted by value visibility settings and
110 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000111 LVForValue = NamedDecl::VisibilityForValue,
112
John McCall5f46c482013-02-21 23:42:58 +0000113 /// Do an LV computation for, ultimately, a type that already has
114 /// some sort of explicit visibility. Visibility may only be
115 /// restricted by the visibility of template arguments.
116 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
John McCalld041a9b2013-02-20 01:54:26 +0000117
John McCall5f46c482013-02-21 23:42:58 +0000118 /// Do an LV computation for, ultimately, a non-type declaration
119 /// that already has some sort of explicit visibility. Visibility
120 /// may only be restricted by the visibility of template arguments.
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000121 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
122
123 /// Do an LV computation when we only care about the linkage.
124 LVForLinkageOnly =
125 LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
John McCalldf25c432013-02-16 00:17:33 +0000126};
127
John McCalld041a9b2013-02-20 01:54:26 +0000128/// Does this computation kind permit us to consider additional
129/// visibility settings from attributes and the like?
130static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000131 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
John McCalld041a9b2013-02-20 01:54:26 +0000132}
133
134/// Given an LVComputationKind, return one of the same type/value sort
135/// that records that it already has explicit visibility.
136static LVComputationKind
137withExplicitVisibilityAlready(LVComputationKind oldKind) {
138 LVComputationKind newKind =
John McCall5f46c482013-02-21 23:42:58 +0000139 static_cast<LVComputationKind>(unsigned(oldKind) |
140 IgnoreExplicitVisibilityBit);
John McCalld041a9b2013-02-20 01:54:26 +0000141 assert(oldKind != LVForType || newKind == LVForExplicitType);
142 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
143 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
144 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
145 return newKind;
146}
147
David Blaikie05785d12013-02-20 22:23:23 +0000148static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
149 LVComputationKind kind) {
John McCalld041a9b2013-02-20 01:54:26 +0000150 assert(!hasExplicitVisibilityAlready(kind) &&
151 "asking for explicit visibility when we shouldn't be");
152 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
153}
154
John McCalldf25c432013-02-16 00:17:33 +0000155/// Is the given declaration a "type" or a "value" for the purposes of
156/// visibility computation?
157static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000158 return isa<TypeDecl>(D) ||
159 isa<ClassTemplateDecl>(D) ||
160 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000161}
162
John McCall5f46c482013-02-21 23:42:58 +0000163/// Does the given declaration have member specialization information,
164/// and if so, is it an explicit specialization?
165template <class T> static typename
Benjamin Kramered2f4762014-03-07 14:30:23 +0000166std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-02-21 23:42:58 +0000167isExplicitMemberSpecialization(const T *D) {
168 if (const MemberSpecializationInfo *member =
169 D->getMemberSpecializationInfo()) {
170 return member->isExplicitSpecialization();
171 }
172 return false;
173}
174
175/// For templates, this question is easier: a member template can't be
176/// explicitly instantiated, so there's a single bit indicating whether
177/// or not this is an explicit member specialization.
178static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
179 return D->isMemberSpecialization();
180}
181
John McCalld041a9b2013-02-20 01:54:26 +0000182/// Given a visibility attribute, return the explicit visibility
183/// associated with it.
184template <class T>
185static Visibility getVisibilityFromAttr(const T *attr) {
186 switch (attr->getVisibility()) {
187 case T::Default:
188 return DefaultVisibility;
189 case T::Hidden:
190 return HiddenVisibility;
191 case T::Protected:
192 return ProtectedVisibility;
193 }
194 llvm_unreachable("bad visibility kind");
195}
196
John McCalldf25c432013-02-16 00:17:33 +0000197/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000198static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000199 NamedDecl::ExplicitVisibilityKind kind) {
200 // If we're ultimately computing the visibility of a type, look for
201 // a 'type_visibility' attribute before looking for 'visibility'.
202 if (kind == NamedDecl::VisibilityForType) {
203 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
204 return getVisibilityFromAttr(A);
205 }
206 }
207
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000208 // If this declaration has an explicit visibility attribute, use it.
209 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000210 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000211 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000212
213 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
214 // implies visibility(default).
Douglas Gregore8bbc122011-09-02 00:18:52 +0000215 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000216 for (const auto *A : D->specific_attrs<AvailabilityAttr>())
217 if (A->getPlatform()->getName().equals("macosx"))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000218 return DefaultVisibility;
219 }
220
David Blaikie7a30dc52013-02-21 01:47:18 +0000221 return None;
John McCall457a04e2010-10-22 21:05:15 +0000222}
223
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000224static LinkageInfo
225getLVForType(const Type &T, LVComputationKind computation) {
226 if (computation == LVForLinkageOnly)
227 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
228 return T.getLinkageAndVisibility();
229}
230
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000231/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000232/// template parameter list. For visibility purposes, template
233/// parameters are part of the signature of a template.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000234static LinkageInfo
David Majnemerc7b85c42014-04-23 05:16:48 +0000235getLVForTemplateParameterList(const TemplateParameterList *Params,
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000236 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000237 LinkageInfo LV;
David Majnemerc7b85c42014-04-23 05:16:48 +0000238 for (const NamedDecl *P : *Params) {
John McCalldf25c432013-02-16 00:17:33 +0000239 // Template type parameters are the most common and never
240 // contribute to visibility, pack or not.
David Majnemerc7b85c42014-04-23 05:16:48 +0000241 if (isa<TemplateTypeParmDecl>(P))
John McCalldf25c432013-02-16 00:17:33 +0000242 continue;
243
244 // Non-type template parameters can be restricted by the value type, e.g.
245 // template <enum X> class A { ... };
246 // We have to be careful here, though, because we can be dealing with
247 // dependent types.
David Majnemerc7b85c42014-04-23 05:16:48 +0000248 if (const NonTypeTemplateParmDecl *NTTP =
249 dyn_cast<NonTypeTemplateParmDecl>(P)) {
John McCalldf25c432013-02-16 00:17:33 +0000250 // Handle the non-pack case first.
251 if (!NTTP->isExpandedParameterPack()) {
252 if (!NTTP->getType()->isDependentType()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000253 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000254 }
255 continue;
256 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000257
John McCalldf25c432013-02-16 00:17:33 +0000258 // Look at all the types in an expanded pack.
259 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
260 QualType type = NTTP->getExpansionType(i);
261 if (!type->isDependentType())
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000262 LV.merge(type->getLinkageAndVisibility());
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000263 }
John McCalldf25c432013-02-16 00:17:33 +0000264 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000265 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000266
John McCalldf25c432013-02-16 00:17:33 +0000267 // Template template parameters can be restricted by their
268 // template parameters, recursively.
David Majnemerc7b85c42014-04-23 05:16:48 +0000269 const TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(P);
John McCalldf25c432013-02-16 00:17:33 +0000270
271 // Handle the non-pack case first.
272 if (!TTP->isExpandedParameterPack()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000273 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
274 computation));
John McCalldf25c432013-02-16 00:17:33 +0000275 continue;
276 }
277
278 // Look at all expansions in an expanded pack.
279 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
280 i != n; ++i) {
281 LV.merge(getLVForTemplateParameterList(
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000282 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000283 }
284 }
285
John McCall457a04e2010-10-22 21:05:15 +0000286 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000287}
288
Rafael Espindola19de5612013-01-12 06:42:30 +0000289/// getLVForDecl - Get the linkage and visibility for the given declaration.
John McCalldf25c432013-02-16 00:17:33 +0000290static LinkageInfo getLVForDecl(const NamedDecl *D,
291 LVComputationKind computation);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000292
Eli Friedman7e346a82013-07-01 20:22:57 +0000293static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
Craig Topper36250ad2014-05-12 05:36:57 +0000294 const Decl *Ret = nullptr;
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000295 const DeclContext *DC = D->getDeclContext();
296 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman7e346a82013-07-01 20:22:57 +0000297 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
298 Ret = cast<Decl>(DC);
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000299 DC = DC->getParent();
300 }
301 return Ret;
302}
303
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000304/// \brief Get the most restrictive linkage for the types and
305/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000306///
307/// Note that we don't take an LVComputationKind because we always
308/// want to honor the visibility of template arguments in the same way.
David Majnemerc7b85c42014-04-23 05:16:48 +0000309static LinkageInfo getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
310 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000311 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000312
David Majnemerc7b85c42014-04-23 05:16:48 +0000313 for (const TemplateArgument &Arg : Args) {
314 switch (Arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000315 case TemplateArgument::Null:
316 case TemplateArgument::Integral:
317 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000318 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000319
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000320 case TemplateArgument::Type:
David Majnemerc7b85c42014-04-23 05:16:48 +0000321 LV.merge(getLVForType(*Arg.getAsType(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000322 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000323
324 case TemplateArgument::Declaration:
David Majnemerc7b85c42014-04-23 05:16:48 +0000325 if (NamedDecl *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
John McCalldf25c432013-02-16 00:17:33 +0000326 assert(!usesTypeVisibility(ND));
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000327 LV.merge(getLVForDecl(ND, computation));
John McCalldf25c432013-02-16 00:17:33 +0000328 }
329 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +0000330
331 case TemplateArgument::NullPtr:
David Majnemerc7b85c42014-04-23 05:16:48 +0000332 LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility());
John McCalldf25c432013-02-16 00:17:33 +0000333 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000334
335 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000336 case TemplateArgument::TemplateExpansion:
David Majnemerc7b85c42014-04-23 05:16:48 +0000337 if (TemplateDecl *Template =
338 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000339 LV.merge(getLVForDecl(Template, computation));
John McCalldf25c432013-02-16 00:17:33 +0000340 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000341
342 case TemplateArgument::Pack:
David Majnemerc7b85c42014-04-23 05:16:48 +0000343 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000344 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000345 }
John McCalldf25c432013-02-16 00:17:33 +0000346 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000347 }
348
John McCall457a04e2010-10-22 21:05:15 +0000349 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000350}
351
Rafael Espindola2f869a32012-01-14 00:30:36 +0000352static LinkageInfo
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000353getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
354 LVComputationKind computation) {
355 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall8823c652010-08-13 08:35:10 +0000356}
357
John McCall5f46c482013-02-21 23:42:58 +0000358static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
359 const FunctionTemplateSpecializationInfo *specInfo) {
360 // Include visibility from the template parameters and arguments
361 // only if this is not an explicit instantiation or specialization
362 // with direct explicit visibility. (Implicit instantiations won't
363 // have a direct attribute.)
364 if (!specInfo->isExplicitInstantiationOrSpecialization())
365 return true;
366
367 return !fn->hasAttr<VisibilityAttr>();
368}
369
John McCalldf25c432013-02-16 00:17:33 +0000370/// Merge in template-related linkage and visibility for the given
371/// function template specialization.
372///
373/// We don't need a computation kind here because we can assume
374/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000375///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000376/// \param[out] LV the computation to use for the parent
John McCall5f46c482013-02-21 23:42:58 +0000377static void
378mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000379 const FunctionTemplateSpecializationInfo *specInfo,
380 LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000381 bool considerVisibility =
382 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000383
384 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000385 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000386 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000387 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000388 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
389
390 // Merge information from the template arguments.
391 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000392 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCalldf25c432013-02-16 00:17:33 +0000393 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000394}
395
John McCall5f46c482013-02-21 23:42:58 +0000396/// Does the given declaration have a direct visibility attribute
397/// that would match the given rules?
398static bool hasDirectVisibilityAttribute(const NamedDecl *D,
399 LVComputationKind computation) {
400 switch (computation) {
401 case LVForType:
402 case LVForExplicitType:
403 if (D->hasAttr<TypeVisibilityAttr>())
404 return true;
405 // fallthrough
406 case LVForValue:
407 case LVForExplicitValue:
408 if (D->hasAttr<VisibilityAttr>())
409 return true;
410 return false;
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000411 case LVForLinkageOnly:
412 return false;
John McCall5f46c482013-02-21 23:42:58 +0000413 }
414 llvm_unreachable("bad visibility computation kind");
415}
416
John McCalld041a9b2013-02-20 01:54:26 +0000417/// Should we consider visibility associated with the template
418/// arguments and parameters of the given class template specialization?
419static bool shouldConsiderTemplateVisibility(
420 const ClassTemplateSpecializationDecl *spec,
421 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000422 // Include visibility from the template parameters and arguments
423 // only if this is not an explicit instantiation or specialization
424 // with direct explicit visibility (and note that implicit
425 // instantiations won't have a direct attribute).
426 //
427 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000428 // for an explicit specialization when computing the visibility of a
429 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000430 //
431 // This is a bit complex; let's unpack it.
432 //
433 // An explicit class specialization is an independent, top-level
434 // declaration. As such, if it or any of its members has an
435 // explicit visibility attribute, that must directly express the
436 // user's intent, and we should honor it. The same logic applies to
437 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000438
439 // Fast path: if this is not an explicit instantiation or
440 // specialization, we always want to consider template-related
441 // visibility restrictions.
442 if (!spec->isExplicitInstantiationOrSpecialization())
443 return true;
444
445 // This is the 'member thereof' check.
446 if (spec->isExplicitSpecialization() &&
447 hasExplicitVisibilityAlready(computation))
448 return false;
449
John McCall5f46c482013-02-21 23:42:58 +0000450 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000451}
452
453/// Merge in template-related linkage and visibility for the given
454/// class template specialization.
455static void mergeTemplateLV(LinkageInfo &LV,
456 const ClassTemplateSpecializationDecl *spec,
457 LVComputationKind computation) {
458 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000459
460 // Merge information from the template parameters, but ignore
461 // visibility if we're only considering template arguments.
462
John McCalld041a9b2013-02-20 01:54:26 +0000463 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000464 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000465 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000466 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000467 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000468
469 // Merge information from the template arguments. We ignore
470 // template-argument visibility if we've got an explicit
471 // instantiation with a visibility attribute.
472 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000473 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000474 if (considerVisibility)
475 LV.mergeVisibility(argsLV);
476 LV.mergeExternalVisibility(argsLV);
John McCallb8c604a2011-06-27 23:06:04 +0000477}
478
Larisse Voufo5899e192014-07-02 23:08:34 +0000479/// Should we consider visibility associated with the template
480/// arguments and parameters of the given variable template
481/// specialization? As usual, follow class template specialization
482/// logic up to initialization.
483static bool shouldConsiderTemplateVisibility(
484 const VarTemplateSpecializationDecl *spec,
485 LVComputationKind computation) {
486 // Include visibility from the template parameters and arguments
487 // only if this is not an explicit instantiation or specialization
488 // with direct explicit visibility (and note that implicit
489 // instantiations won't have a direct attribute).
490 if (!spec->isExplicitInstantiationOrSpecialization())
491 return true;
492
493 // An explicit variable specialization is an independent, top-level
494 // declaration. As such, if it has an explicit visibility attribute,
495 // that must directly express the user's intent, and we should honor
496 // it.
497 if (spec->isExplicitSpecialization() &&
498 hasExplicitVisibilityAlready(computation))
499 return false;
500
501 return !hasDirectVisibilityAttribute(spec, computation);
502}
503
504/// Merge in template-related linkage and visibility for the given
505/// variable template specialization. As usual, follow class template
506/// specialization logic up to initialization.
507static void mergeTemplateLV(LinkageInfo &LV,
508 const VarTemplateSpecializationDecl *spec,
509 LVComputationKind computation) {
510 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
511
512 // Merge information from the template parameters, but ignore
513 // visibility if we're only considering template arguments.
514
515 VarTemplateDecl *temp = spec->getSpecializedTemplate();
516 LinkageInfo tempLV =
517 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
518 LV.mergeMaybeWithVisibility(tempLV,
519 considerVisibility && !hasExplicitVisibilityAlready(computation));
520
521 // Merge information from the template arguments. We ignore
522 // template-argument visibility if we've got an explicit
523 // instantiation with a visibility attribute.
524 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
525 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
526 if (considerVisibility)
527 LV.mergeVisibility(argsLV);
528 LV.mergeExternalVisibility(argsLV);
529}
530
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000531static bool useInlineVisibilityHidden(const NamedDecl *D) {
532 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000533 const LangOptions &Opts = D->getASTContext().getLangOpts();
534 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000535 return false;
536
537 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
538 if (!FD)
539 return false;
540
541 TemplateSpecializationKind TSK = TSK_Undeclared;
542 if (FunctionTemplateSpecializationInfo *spec
543 = FD->getTemplateSpecializationInfo()) {
544 TSK = spec->getTemplateSpecializationKind();
545 } else if (MemberSpecializationInfo *MSI =
546 FD->getMemberSpecializationInfo()) {
547 TSK = MSI->getTemplateSpecializationKind();
548 }
549
Craig Topper36250ad2014-05-12 05:36:57 +0000550 const FunctionDecl *Def = nullptr;
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000551 // InlineVisibilityHidden only applies to definitions, and
552 // isInlined() only gives meaningful answers on definitions
553 // anyway.
554 return TSK != TSK_ExplicitInstantiationDeclaration &&
555 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000556 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000557}
558
Rafael Espindola593537a2013-05-05 20:15:21 +0000559template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000560 const T *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +0000561 return First->isInExternCContext();
Rafael Espindolaf4187652013-02-14 01:18:37 +0000562}
563
Richard Smith03c05032014-02-17 23:34:47 +0000564static bool isSingleLineLanguageLinkage(const Decl &D) {
Rafael Espindola327be3c2013-04-26 01:30:23 +0000565 if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Richard Smith03c05032014-02-17 23:34:47 +0000566 if (!SD->hasBraces())
Rafael Espindola327be3c2013-04-26 01:30:23 +0000567 return true;
568 return false;
569}
570
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000571static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
John McCalldf25c432013-02-16 00:17:33 +0000572 LVComputationKind computation) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000573 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000574 "Not a name having namespace scope");
575 ASTContext &Context = D->getASTContext();
576
577 // C++ [basic.link]p3:
578 // A name having namespace scope (3.3.6) has internal linkage if it
579 // is the name of
580 // - an object, reference, function or function template that is
581 // explicitly declared static; or,
582 // (This bullet corresponds to C99 6.2.2p3.)
583 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
584 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000585 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000586 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000587
Richard Smithdc0ef452012-10-19 06:37:48 +0000588 // - a non-volatile object or reference that is explicitly declared const
589 // or constexpr and neither explicitly declared extern nor previously
590 // declared to have external linkage; or (there is no equivalent in C99)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000591 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000592 Var->getType().isConstQualified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000593 !Var->getType().isVolatileQualified()) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000594 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000595 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000596 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000597
598 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000599 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000600 !isSingleLineLanguageLinkage(*Var))
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000601 return LinkageInfo::internal();
602 }
603
604 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
605 PrevVar = PrevVar->getPreviousDecl()) {
606 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
607 Var->getStorageClass() == SC_None)
608 return PrevVar->getLinkageAndVisibility();
609 // Explicitly declared static.
610 if (PrevVar->getStorageClass() == SC_Static)
611 return LinkageInfo::internal();
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000612 }
Alp Tokera2794f92014-01-22 07:29:52 +0000613 } else if (const FunctionDecl *Function = D->getAsFunction()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000614 // C++ [temp]p4:
615 // A non-member function template can have internal linkage; any
616 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000617
618 // Explicitly declared static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000619 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000620 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000621 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000622 // - a data member of an anonymous union.
623 assert(!isa<IndirectFieldDecl>(D) && "Didn't expect an IndirectFieldDecl!");
624 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000625
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000626 if (D->isInAnonymousNamespace()) {
627 const VarDecl *Var = dyn_cast<VarDecl>(D);
628 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
Rafael Espindola593537a2013-05-05 20:15:21 +0000629 if ((!Var || !isFirstInExternCContext(Var)) &&
630 (!Func || !isFirstInExternCContext(Func)))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000631 return LinkageInfo::uniqueExternal();
632 }
John McCallb7139c42010-10-28 04:18:25 +0000633
John McCall457a04e2010-10-22 21:05:15 +0000634 // Set up the defaults.
635
636 // C99 6.2.2p5:
637 // If the declaration of an identifier for an object has file
638 // scope and no storage-class specifier, its linkage is
639 // external.
John McCallc273f242010-10-30 11:50:40 +0000640 LinkageInfo LV;
641
John McCalld041a9b2013-02-20 01:54:26 +0000642 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000643 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000644 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000645 } else {
646 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000647 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000648 for (const DeclContext *DC = D->getDeclContext();
649 !isa<TranslationUnitDecl>(DC);
650 DC = DC->getParent()) {
651 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
652 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000653 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000654 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000655 break;
656 }
657 }
658 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000659
John McCalldf25c432013-02-16 00:17:33 +0000660 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000661 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000662 // Use global type/value visibility as appropriate.
663 Visibility globalVisibility;
664 if (computation == LVForValue) {
665 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
666 } else {
667 assert(computation == LVForType);
668 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
669 }
670 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000671
672 // If we're paying attention to global visibility, apply
673 // -finline-visibility-hidden if this is an inline method.
674 if (useInlineVisibilityHidden(D))
675 LV.mergeVisibility(HiddenVisibility, true);
676 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000677 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000678
Douglas Gregorf73b2822009-11-25 22:24:25 +0000679 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000680
Douglas Gregorf73b2822009-11-25 22:24:25 +0000681 // A name having namespace scope has external linkage if it is the
682 // name of
683 //
684 // - an object or reference, unless it has internal linkage; or
685 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000686 // GCC applies the following optimization to variables and static
687 // data members, but not to functions:
688 //
John McCall457a04e2010-10-22 21:05:15 +0000689 // Modify the variable's LV by the LV of its type unless this is
690 // C or extern "C". This follows from [basic.link]p9:
691 // A type without linkage shall not be used as the type of a
692 // variable or function with external linkage unless
693 // - the entity has C language linkage, or
694 // - the entity is declared within an unnamed namespace, or
695 // - the entity is not used or is defined in the same
696 // translation unit.
697 // and [basic.link]p10:
698 // ...the types specified by all declarations referring to a
699 // given variable or function shall be identical...
700 // C does not have an equivalent rule.
701 //
John McCall5fe84122010-10-26 04:59:26 +0000702 // Ignore this if we've got an explicit attribute; the user
703 // probably knows what they're doing.
704 //
John McCall457a04e2010-10-22 21:05:15 +0000705 // Note that we don't want to make the variable non-external
706 // because of this, but unique-external linkage suits us.
Rafael Espindola593537a2013-05-05 20:15:21 +0000707 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000708 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Rafael Espindola4a5da442013-02-27 02:56:45 +0000709 if (TypeLV.getLinkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000710 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000711 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000712 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000713 }
714
John McCall23032652010-11-02 18:38:13 +0000715 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000716 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000717
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000718 // Note that Sema::MergeVarDecl already takes care of implementing
719 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
720 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000721
Larisse Voufo5899e192014-07-02 23:08:34 +0000722 // As per function and class template specializations (below),
723 // consider LV for the template and template arguments. We're at file
724 // scope, so we do not need to worry about nested specializations.
725 if (const VarTemplateSpecializationDecl *spec
726 = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
727 mergeTemplateLV(LV, spec, computation);
728 }
729
Douglas Gregorf73b2822009-11-25 22:24:25 +0000730 // - a function, unless it has internal linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000731 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000732 // In theory, we can modify the function's LV by the LV of its
733 // type unless it has C linkage (see comment above about variables
734 // for justification). In practice, GCC doesn't do this, so it's
735 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000736
John McCall23032652010-11-02 18:38:13 +0000737 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000738 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000739
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000740 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
741 // merging storage classes and visibility attributes, so we don't have to
742 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000743
John McCallf768aa72011-02-10 06:50:24 +0000744 // In C++, then if the type of the function uses a type with
745 // unique-external linkage, it's not legally usable from outside
746 // this translation unit. However, we should use the C linkage
747 // rules instead for extern "C" declarations.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000748 if (Context.getLangOpts().CPlusPlus &&
Richard Smith50f4afc2013-05-12 23:17:59 +0000749 !Function->isInExternCContext()) {
750 // Only look at the type-as-written. If this function has an auto-deduced
751 // return type, we can't compute the linkage of that type because it could
752 // require looking at the linkage of this function, and we don't need this
753 // for correctness because the type is not part of the function's
754 // signature.
Faisal Valid2598e92013-10-08 04:15:04 +0000755 // FIXME: This is a hack. We should be able to solve this circularity and
756 // the one in getLVForClassMember for Functions some other way.
Richard Smith50f4afc2013-05-12 23:17:59 +0000757 QualType TypeAsWritten = Function->getType();
758 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
759 TypeAsWritten = TSI->getType();
760 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
761 return LinkageInfo::uniqueExternal();
762 }
John McCallf768aa72011-02-10 06:50:24 +0000763
John McCall5f46c482013-02-21 23:42:58 +0000764 // Consider LV from the template and the template arguments.
765 // We're at file scope, so we do not need to worry about nested
766 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000767 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000768 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000769 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000770 }
771
Douglas Gregorf73b2822009-11-25 22:24:25 +0000772 // - a named class (Clause 9), or an unnamed class defined in a
773 // typedef declaration in which the class has the typedef name
774 // for linkage purposes (7.1.3); or
775 // - a named enumeration (7.2), or an unnamed enumeration
776 // defined in a typedef declaration in which the enumeration
777 // has the typedef name for linkage purposes (7.1.3); or
John McCall457a04e2010-10-22 21:05:15 +0000778 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
779 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000780 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000781 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000782
John McCall457a04e2010-10-22 21:05:15 +0000783 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000784 // linkage of the template and template arguments. We're at file
785 // scope, so we do not need to worry about nested specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000786 if (const ClassTemplateSpecializationDecl *spec
John McCall457a04e2010-10-22 21:05:15 +0000787 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000788 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000789 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000790
791 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000792 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000793 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000794 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000795 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000796 return LinkageInfo::none();
797 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000798
799 // - a template, unless it is a function template that has
800 // internal linkage (Clause 14);
John McCall8bc6d5b2011-03-04 10:39:25 +0000801 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000802 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000803 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000804 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000805 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
806
Douglas Gregorf73b2822009-11-25 22:24:25 +0000807 // - a namespace (7.3), unless it is declared within an unnamed
808 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000809 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
810 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000811
John McCall457a04e2010-10-22 21:05:15 +0000812 // By extension, we assign external linkage to Objective-C
813 // interfaces.
814 } else if (isa<ObjCInterfaceDecl>(D)) {
815 // fallout
816
817 // Everything not covered here has no linkage.
818 } else {
Richard Smith2516ba22014-08-11 18:35:44 +0000819 // FIXME: A typedef declaration has linkage if it gives a type a name for
820 // linkage purposes.
John McCallc273f242010-10-30 11:50:40 +0000821 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000822 }
823
824 // If we ended up with non-external linkage, visibility should
825 // always be default.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000826 if (LV.getLinkage() != ExternalLinkage)
827 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000828
John McCall457a04e2010-10-22 21:05:15 +0000829 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000830}
831
John McCalldf25c432013-02-16 00:17:33 +0000832static LinkageInfo getLVForClassMember(const NamedDecl *D,
833 LVComputationKind computation) {
John McCall457a04e2010-10-22 21:05:15 +0000834 // Only certain class members have linkage. Note that fields don't
835 // really have linkage, but it's convenient to say they do for the
836 // purposes of calculating linkage of pointer-to-data-member
837 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000838 //
839 // Templates also don't officially have linkage, but since we ignore
840 // the C++ standard and look at template arguments when determining
841 // linkage and visibility of a template specialization, we might hit
842 // a template template argument that way. If we do, we need to
843 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000844 if (!(isa<CXXMethodDecl>(D) ||
845 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000846 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000847 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000848 isa<TagDecl>(D) ||
849 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000850 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000851
John McCall07072662010-11-02 01:45:15 +0000852 LinkageInfo LV;
853
John McCall07072662010-11-02 01:45:15 +0000854 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000855 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000856 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000857 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000858 // If we're paying attention to global visibility, apply
859 // -finline-visibility-hidden if this is an inline method.
860 //
861 // Note that we do this before merging information about
862 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000863 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000864 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000865 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000866
867 // If this class member has an explicit visibility attribute, the only
868 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000869 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000870 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000871 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000872 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000873
John McCall5f46c482013-02-21 23:42:58 +0000874 LinkageInfo classLV =
875 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
John McCall8823c652010-08-13 08:35:10 +0000876 // If the class already has unique-external linkage, we can't improve.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000877 if (classLV.getLinkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000878 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000879
Rafael Espindolae6190db2013-05-28 02:22:10 +0000880 if (!isExternallyVisible(classLV.getLinkage()))
881 return LinkageInfo::none();
882
883
John McCall5f46c482013-02-21 23:42:58 +0000884 // Otherwise, don't merge in classLV yet, because in certain cases
885 // we need to completely ignore the visibility from it.
886
887 // Specifically, if this decl exists and has an explicit attribute.
Craig Topper36250ad2014-05-12 05:36:57 +0000888 const NamedDecl *explicitSpecSuppressor = nullptr;
John McCall5f46c482013-02-21 23:42:58 +0000889
John McCall8823c652010-08-13 08:35:10 +0000890 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000891 // If the type of the function uses a type with unique-external
892 // linkage, it's not legally usable from outside this translation unit.
Faisal Valid2598e92013-10-08 04:15:04 +0000893 // But only look at the type-as-written. If this function has an auto-deduced
894 // return type, we can't compute the linkage of that type because it could
895 // require looking at the linkage of this function, and we don't need this
896 // for correctness because the type is not part of the function's
897 // signature.
898 // FIXME: This is a hack. We should be able to solve this circularity and the
899 // one in getLVForNamespaceScopeDecl for Functions some other way.
900 {
901 QualType TypeAsWritten = MD->getType();
902 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
903 TypeAsWritten = TSI->getType();
904 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
905 return LinkageInfo::uniqueExternal();
906 }
John McCall457a04e2010-10-22 21:05:15 +0000907 // If this is a method template specialization, use the linkage for
908 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000909 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000910 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000911 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000912 if (spec->isExplicitSpecialization()) {
913 explicitSpecSuppressor = MD;
914 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
915 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
916 }
917 } else if (isExplicitMemberSpecialization(MD)) {
918 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000919 }
John McCall457a04e2010-10-22 21:05:15 +0000920
John McCall37bb6c92010-10-29 22:22:43 +0000921 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCallb8c604a2011-06-27 23:06:04 +0000922 if (const ClassTemplateSpecializationDecl *spec
John McCall37bb6c92010-10-29 22:22:43 +0000923 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000924 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000925 if (spec->isExplicitSpecialization()) {
926 explicitSpecSuppressor = spec;
927 } else {
928 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
929 if (isExplicitMemberSpecialization(temp)) {
930 explicitSpecSuppressor = temp->getTemplatedDecl();
931 }
932 }
933 } else if (isExplicitMemberSpecialization(RD)) {
934 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000935 }
936
John McCall37bb6c92010-10-29 22:22:43 +0000937 // Static data members.
938 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000939 if (const VarTemplateSpecializationDecl *spec
940 = dyn_cast<VarTemplateSpecializationDecl>(VD))
941 mergeTemplateLV(LV, spec, computation);
942
John McCall36cd5cc2010-10-30 09:18:49 +0000943 // Modify the variable's linkage by its type, but ignore the
944 // type's visibility unless it's a definition.
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000945 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000946 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
947 LV.mergeVisibility(typeLV);
948 LV.mergeExternalVisibility(typeLV);
John McCall5f46c482013-02-21 23:42:58 +0000949
950 if (isExplicitMemberSpecialization(VD)) {
951 explicitSpecSuppressor = VD;
952 }
John McCalldf25c432013-02-16 00:17:33 +0000953
954 // Template members.
955 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
956 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +0000957 (!LV.isVisibilityExplicit() &&
958 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000959 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000960 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000961 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000962 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +0000963
964 if (const RedeclarableTemplateDecl *redeclTemp =
965 dyn_cast<RedeclarableTemplateDecl>(temp)) {
966 if (isExplicitMemberSpecialization(redeclTemp)) {
967 explicitSpecSuppressor = temp->getTemplatedDecl();
968 }
969 }
John McCall37bb6c92010-10-29 22:22:43 +0000970 }
971
John McCall5f46c482013-02-21 23:42:58 +0000972 // We should never be looking for an attribute directly on a template.
973 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
974
975 // If this member is an explicit member specialization, and it has
976 // an explicit attribute, ignore visibility from the parent.
977 bool considerClassVisibility = true;
978 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +0000979 // optimization: hasDVA() is true only with explicit visibility.
980 LV.isVisibilityExplicit() &&
981 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +0000982 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
983 considerClassVisibility = false;
984 }
985
986 // Finally, merge in information from the class.
987 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +0000988 return LV;
John McCall8823c652010-08-13 08:35:10 +0000989}
990
David Blaikie68e081d2011-12-20 02:48:34 +0000991void NamedDecl::anchor() { }
992
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000993static LinkageInfo computeLVForDecl(const NamedDecl *D,
994 LVComputationKind computation);
995
Rafael Espindola0e0d0092013-03-14 03:07:35 +0000996bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +0000997 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +0000998 return true;
John McCalld396b972011-02-08 19:01:05 +0000999
Rafael Espindolaecf63c62013-05-29 04:55:30 +00001000 return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
Rafael Espindola50df3a02013-05-25 17:16:20 +00001001 getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +00001002}
1003
Rafael Espindola3ae00052013-05-13 00:12:11 +00001004Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +00001005 // We don't care about visibility here, so ask for the cheapest
1006 // possible visibility analysis.
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001007 return getLVForDecl(this, LVForLinkageOnly).getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001008}
1009
John McCallc273f242010-10-30 11:50:40 +00001010LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCalldf25c432013-02-16 00:17:33 +00001011 LVComputationKind computation =
1012 (usesTypeVisibility(this) ? LVForType : LVForValue);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001013 return getLVForDecl(this, computation);
John McCall033caa52010-10-29 00:29:13 +00001014}
Ted Kremenek926d8602010-04-20 23:15:35 +00001015
Rafael Espindola9ad61122013-11-26 16:09:08 +00001016static Optional<Visibility>
1017getExplicitVisibilityAux(const NamedDecl *ND,
1018 NamedDecl::ExplicitVisibilityKind kind,
1019 bool IsMostRecent) {
1020 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1021
Rafael Espindola3a52c442013-02-26 19:33:14 +00001022 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001023 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001024 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001025
Rafael Espindola3a52c442013-02-26 19:33:14 +00001026 // If this is a member class of a specialization of a class template
1027 // and the corresponding decl has explicit visibility, use that.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001028 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +00001029 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1030 if (InstantiatedFrom)
1031 return getVisibilityOf(InstantiatedFrom, kind);
1032 }
1033
1034 // If there wasn't explicit visibility there, and this is a
1035 // specialization of a class template, check for visibility
1036 // on the pattern.
1037 if (const ClassTemplateSpecializationDecl *spec
Rafael Espindola9ad61122013-11-26 16:09:08 +00001038 = dyn_cast<ClassTemplateSpecializationDecl>(ND))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001039 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1040 kind);
1041
1042 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +00001043 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +00001044 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1045 if (MostRecent != ND)
1046 return getExplicitVisibilityAux(MostRecent, kind, true);
1047 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001048
Rafael Espindola9ad61122013-11-26 16:09:08 +00001049 if (const VarDecl *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +00001050 if (Var->isStaticDataMember()) {
1051 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1052 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001053 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +00001054 }
1055
David Majnemer35b02bc2014-04-29 07:32:26 +00001056 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1057 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1058 kind);
1059
David Blaikie7a30dc52013-02-21 01:47:18 +00001060 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +00001061 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001062 // Also handle function template specializations.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001063 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001064 // If the function is a specialization of a template with an
1065 // explicit visibility attribute, use that.
1066 if (FunctionTemplateSpecializationInfo *templateInfo
1067 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +00001068 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1069 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001070
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001071 // If the function is a member of a specialization of a class template
1072 // and the corresponding decl has explicit visibility, use that.
1073 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1074 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001075 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001076
David Blaikie7a30dc52013-02-21 01:47:18 +00001077 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001078 }
1079
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001080 // The visibility of a template is stored in the templated decl.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001081 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001082 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001083
David Blaikie7a30dc52013-02-21 01:47:18 +00001084 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001085}
1086
Rafael Espindola9ad61122013-11-26 16:09:08 +00001087Optional<Visibility>
1088NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1089 return getExplicitVisibilityAux(this, kind, false);
1090}
1091
Eli Friedman7e346a82013-07-01 20:22:57 +00001092static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
1093 LVComputationKind computation) {
1094 // This lambda has its linkage/visibility determined by its owner.
1095 if (ContextDecl) {
1096 if (isa<ParmVarDecl>(ContextDecl))
1097 DC = ContextDecl->getDeclContext()->getRedeclContext();
1098 else
1099 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1100 }
Faisal Vali98b8e182013-09-29 20:27:06 +00001101
Eli Friedman7e346a82013-07-01 20:22:57 +00001102 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
1103 return getLVForDecl(ND, computation);
Faisal Vali98b8e182013-09-29 20:27:06 +00001104
Eli Friedman7e346a82013-07-01 20:22:57 +00001105 return LinkageInfo::external();
1106}
1107
John McCalldf25c432013-02-16 00:17:33 +00001108static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1109 LVComputationKind computation) {
1110 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1111 if (Function->isInAnonymousNamespace() &&
Rafael Espindola593537a2013-05-05 20:15:21 +00001112 !Function->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001113 return LinkageInfo::uniqueExternal();
1114
1115 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001116 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCalldf25c432013-02-16 00:17:33 +00001117 return LinkageInfo::internal();
1118
1119 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001120 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001121 if (Optional<Visibility> Vis =
1122 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001123 LV.mergeVisibility(*Vis, true);
1124 }
1125
1126 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1127 // merging storage classes and visibility attributes, so we don't have to
1128 // look at previous decls in here.
1129
1130 return LV;
1131 }
1132
1133 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001134 if (Var->hasExternalStorage()) {
Rafael Espindola593537a2013-05-05 20:15:21 +00001135 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001136 return LinkageInfo::uniqueExternal();
1137
John McCalldf25c432013-02-16 00:17:33 +00001138 LinkageInfo LV;
1139 if (Var->getStorageClass() == SC_PrivateExtern)
1140 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001141 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001142 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001143 LV.mergeVisibility(*Vis, true);
1144 }
1145
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001146 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1147 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1148 if (PrevLV.getLinkage())
1149 LV.setLinkage(PrevLV.getLinkage());
1150 LV.mergeVisibility(PrevLV);
1151 }
1152
John McCalldf25c432013-02-16 00:17:33 +00001153 return LV;
1154 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001155
1156 if (!Var->isStaticLocal())
1157 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001158 }
1159
Rafael Espindolaa4184182013-06-17 20:04:51 +00001160 ASTContext &Context = D->getASTContext();
1161 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001162 return LinkageInfo::none();
1163
Eli Friedman7e346a82013-07-01 20:22:57 +00001164 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1165 if (!OuterD)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001166 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001167
Eli Friedman7e346a82013-07-01 20:22:57 +00001168 LinkageInfo LV;
1169 if (const BlockDecl *BD = dyn_cast<BlockDecl>(OuterD)) {
1170 if (!BD->getBlockManglingNumber())
1171 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001172
Eli Friedman7e346a82013-07-01 20:22:57 +00001173 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1174 BD->getBlockManglingContextDecl(), computation);
1175 } else {
1176 const FunctionDecl *FD = cast<FunctionDecl>(OuterD);
1177 if (!FD->isInlined() &&
1178 FD->getTemplateSpecializationKind() == TSK_Undeclared)
1179 return LinkageInfo::none();
1180
1181 LV = getLVForDecl(FD, computation);
1182 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001183 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001184 return LinkageInfo::none();
1185 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1186 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001187}
1188
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001189static inline const CXXRecordDecl*
1190getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1191 const CXXRecordDecl *Ret = Record;
1192 while (Record && Record->isLambda()) {
1193 Ret = Record;
1194 if (!Record->getParent()) break;
1195 // Get the Containing Class of this Lambda Class
1196 Record = dyn_cast_or_null<CXXRecordDecl>(
1197 Record->getParent()->getParent());
1198 }
1199 return Ret;
1200}
1201
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001202static LinkageInfo computeLVForDecl(const NamedDecl *D,
1203 LVComputationKind computation) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001204 // Objective-C: treat all Objective-C declarations as having external
1205 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001206 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001207 default:
1208 break;
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001209 case Decl::ParmVar:
1210 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001211 case Decl::TemplateTemplateParm: // count these as external
1212 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001213 case Decl::ObjCAtDefsField:
1214 case Decl::ObjCCategory:
1215 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001216 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001217 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001218 case Decl::ObjCMethod:
1219 case Decl::ObjCProperty:
1220 case Decl::ObjCPropertyImpl:
1221 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +00001222 return LinkageInfo::external();
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001223
1224 case Decl::CXXRecord: {
1225 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1226 if (Record->isLambda()) {
1227 if (!Record->getLambdaManglingNumber()) {
1228 // This lambda has no mangling number, so it's internal.
1229 return LinkageInfo::internal();
1230 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001231
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001232 // This lambda has its linkage/visibility determined:
1233 // - either by the outermost lambda if that lambda has no mangling
1234 // number.
1235 // - or by the parent of the outer most lambda
1236 // This prevents infinite recursion in settings such as nested lambdas
1237 // used in NSDMI's, for e.g.
1238 // struct L {
1239 // int t{};
1240 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1241 // };
1242 const CXXRecordDecl *OuterMostLambda =
1243 getOutermostEnclosingLambda(Record);
1244 if (!OuterMostLambda->getLambdaManglingNumber())
1245 return LinkageInfo::internal();
1246
1247 return getLVForClosure(
1248 OuterMostLambda->getDeclContext()->getRedeclContext(),
1249 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001250 }
1251
1252 break;
1253 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001254 }
1255
Douglas Gregorf73b2822009-11-25 22:24:25 +00001256 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001257 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCalldf25c432013-02-16 00:17:33 +00001258 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001259
1260 // C++ [basic.link]p5:
1261 // In addition, a member function, static data member, a named
1262 // class or enumeration of class scope, or an unnamed class or
1263 // enumeration defined in a class-scope typedef declaration such
1264 // that the class or enumeration has the typedef name for linkage
1265 // purposes (7.1.3), has external linkage if the name of the class
1266 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001267 if (D->getDeclContext()->isRecord())
John McCalldf25c432013-02-16 00:17:33 +00001268 return getLVForClassMember(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001269
1270 // C++ [basic.link]p6:
1271 // The name of a function declared in block scope and the name of
1272 // an object declared by a block scope extern declaration have
1273 // linkage. If there is a visible declaration of an entity with
1274 // linkage having the same name and type, ignoring entities
1275 // declared outside the innermost enclosing namespace scope, the
1276 // block scope declaration declares that same entity and receives
1277 // the linkage of the previous declaration. If there is more than
1278 // one such matching entity, the program is ill-formed. Otherwise,
1279 // if no matching entity is found, the block scope entity receives
1280 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001281 if (D->getDeclContext()->isFunctionOrMethod())
1282 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001283
1284 // C++ [basic.link]p6:
1285 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001286 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001287}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001288
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001289namespace clang {
1290class LinkageComputer {
1291public:
1292 static LinkageInfo getLVForDecl(const NamedDecl *D,
1293 LVComputationKind computation) {
1294 if (computation == LVForLinkageOnly && D->hasCachedLinkage())
1295 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1296
1297 LinkageInfo LV = computeLVForDecl(D, computation);
1298 if (D->hasCachedLinkage())
1299 assert(D->getCachedLinkage() == LV.getLinkage());
1300
1301 D->setCachedLinkage(LV.getLinkage());
1302
1303#ifndef NDEBUG
1304 // In C (because of gnu inline) and in c++ with microsoft extensions an
1305 // static can follow an extern, so we can have two decls with different
1306 // linkages.
1307 const LangOptions &Opts = D->getASTContext().getLangOpts();
1308 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1309 return LV;
1310
1311 // We have just computed the linkage for this decl. By induction we know
1312 // that all other computed linkages match, check that the one we just
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001313 // computed also does.
Craig Topper36250ad2014-05-12 05:36:57 +00001314 NamedDecl *Old = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +00001315 for (auto I : D->redecls()) {
1316 NamedDecl *T = cast<NamedDecl>(I);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001317 if (T == D)
1318 continue;
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001319 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001320 Old = T;
1321 break;
1322 }
1323 }
1324 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1325#endif
1326
1327 return LV;
1328 }
1329};
1330}
1331
1332static LinkageInfo getLVForDecl(const NamedDecl *D,
1333 LVComputationKind computation) {
1334 return clang::LinkageComputer::getLVForDecl(D, computation);
1335}
1336
Douglas Gregor2ada0482009-02-04 17:27:36 +00001337std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001338 std::string QualName;
1339 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001340 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001341 return OS.str();
1342}
1343
1344void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1345 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1346}
1347
1348void NamedDecl::printQualifiedName(raw_ostream &OS,
1349 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001350 const DeclContext *Ctx = getDeclContext();
1351
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001352 if (Ctx->isFunctionOrMethod()) {
1353 printName(OS);
1354 return;
1355 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001356
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001357 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001358 ContextsTy Contexts;
1359
1360 // Collect contexts.
1361 while (Ctx && isa<NamedDecl>(Ctx)) {
1362 Contexts.push_back(Ctx);
1363 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001364 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001365
1366 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1367 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00001368 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001369 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001370 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001371 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00001372 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1373 TemplateArgs.data(),
1374 TemplateArgs.size(),
1375 P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001376 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Richard Smith46dd5bb2014-05-30 22:16:51 +00001377 if (P.SuppressUnwrittenScope &&
1378 (ND->isAnonymousNamespace() || ND->isInline()))
1379 continue;
Sam Weinig07d211e2009-12-24 23:15:03 +00001380 if (ND->isAnonymousNamespace())
David Blaikieabe1a392014-04-02 05:58:29 +00001381 OS << "(anonymous namespace)";
Sam Weinig07d211e2009-12-24 23:15:03 +00001382 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001383 OS << *ND;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001384 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1385 if (!RD->getIdentifier())
David Blaikieabe1a392014-04-02 05:58:29 +00001386 OS << "(anonymous " << RD->getKindName() << ')';
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001387 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001388 OS << *RD;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001389 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Craig Topper36250ad2014-05-12 05:36:57 +00001390 const FunctionProtoType *FT = nullptr;
Sam Weinigb999f682009-12-28 03:19:38 +00001391 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001392 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001393
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001394 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001395 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001396 unsigned NumParams = FD->getNumParams();
1397 for (unsigned i = 0; i < NumParams; ++i) {
1398 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001399 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001400 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001401 }
1402
1403 if (FT->isVariadic()) {
1404 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001405 OS << ", ";
1406 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001407 }
1408 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001409 OS << ')';
1410 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001411 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001412 }
1413 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001414 }
1415
John McCalla2a3f7d2010-03-16 21:48:18 +00001416 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001417 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001418 else
David Blaikieabe1a392014-04-02 05:58:29 +00001419 OS << "(anonymous)";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001420}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001421
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001422void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1423 const PrintingPolicy &Policy,
1424 bool Qualified) const {
1425 if (Qualified)
1426 printQualifiedName(OS, Policy);
1427 else
1428 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001429}
1430
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001431bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001432 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1433
Douglas Gregor889ceb72009-02-03 19:21:40 +00001434 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1435 // We want to keep it, unless it nominates same namespace.
1436 if (getKind() == Decl::UsingDirective) {
Douglas Gregor12441b32011-02-25 16:33:46 +00001437 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1438 ->getOriginalNamespace() ==
1439 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1440 ->getOriginalNamespace();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001441 }
Mike Stump11289f42009-09-09 15:08:12 +00001442
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001443 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1444 // For function declarations, we keep track of redeclarations.
Douglas Gregorec9fd132012-01-14 16:38:05 +00001445 return FD->getPreviousDecl() == OldD;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001446
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001447 // For function templates, the underlying function declarations are linked.
1448 if (const FunctionTemplateDecl *FunctionTemplate
1449 = dyn_cast<FunctionTemplateDecl>(this))
1450 if (const FunctionTemplateDecl *OldFunctionTemplate
1451 = dyn_cast<FunctionTemplateDecl>(OldD))
1452 return FunctionTemplate->getTemplatedDecl()
1453 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001454
Steve Naroffc4173fa2009-02-22 19:35:57 +00001455 // For method declarations, we keep track of redeclarations.
1456 if (isa<ObjCMethodDecl>(this))
1457 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001458
Richard Smithbaf3ca52014-03-17 21:46:03 +00001459 // FIXME: Is this correct if one of the decls comes from an inline namespace?
John McCall9f3059a2009-10-09 21:13:30 +00001460 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1461 return true;
1462
John McCall3f746822009-11-17 05:59:44 +00001463 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1464 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1465 cast<UsingShadowDecl>(OldD)->getTargetDecl();
1466
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001467 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1468 ASTContext &Context = getASTContext();
1469 return Context.getCanonicalNestedNameSpecifier(
1470 cast<UsingDecl>(this)->getQualifier()) ==
1471 Context.getCanonicalNestedNameSpecifier(
1472 cast<UsingDecl>(OldD)->getQualifier());
1473 }
Argyrios Kyrtzidis4b520072010-11-04 08:48:52 +00001474
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001475 if (isa<UnresolvedUsingValueDecl>(this) &&
1476 isa<UnresolvedUsingValueDecl>(OldD)) {
1477 ASTContext &Context = getASTContext();
1478 return Context.getCanonicalNestedNameSpecifier(
1479 cast<UnresolvedUsingValueDecl>(this)->getQualifier()) ==
1480 Context.getCanonicalNestedNameSpecifier(
1481 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1482 }
1483
Douglas Gregorb59643b2012-01-03 23:26:26 +00001484 // A typedef of an Objective-C class type can replace an Objective-C class
1485 // declaration or definition, and vice versa.
Richard Smithbaf3ca52014-03-17 21:46:03 +00001486 // FIXME: Is this correct if one of the decls comes from an inline namespace?
Douglas Gregorb59643b2012-01-03 23:26:26 +00001487 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1488 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1489 return true;
Richard Smithbaf3ca52014-03-17 21:46:03 +00001490
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001491 // For non-function declarations, if the declarations are of the
Richard Smithbaf3ca52014-03-17 21:46:03 +00001492 // same kind and have the same parent then this must be a redeclaration,
1493 // or semantic analysis would not have given us the new declaration.
1494 // Note that inline namespaces can give us two declarations with the same
1495 // name and kind in the same scope but different contexts.
1496 return this->getKind() == OldD->getKind() &&
1497 this->getDeclContext()->getRedeclContext()->Equals(
1498 OldD->getDeclContext()->getRedeclContext());
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001499}
1500
Douglas Gregoreddf4332009-02-24 20:03:32 +00001501bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001502 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001503}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001504
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001505NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001506 NamedDecl *ND = this;
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001507 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1508 ND = UD->getTargetDecl();
1509
1510 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1511 return AD->getClassInterface();
1512
1513 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001514}
1515
John McCalla8ae2222010-04-06 21:38:20 +00001516bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001517 if (!isCXXClassMember())
1518 return false;
1519
John McCalla8ae2222010-04-06 21:38:20 +00001520 const NamedDecl *D = this;
1521 if (isa<UsingShadowDecl>(D))
1522 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1523
John McCall5e77d762013-04-16 07:28:30 +00001524 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001525 return true;
Alp Tokera2794f92014-01-22 07:29:52 +00001526 if (const CXXMethodDecl *MD =
1527 dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1528 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001529 return false;
1530}
1531
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001532//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001533// DeclaratorDecl Implementation
1534//===----------------------------------------------------------------------===//
1535
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001536template <typename DeclT>
1537static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1538 if (decl->getNumTemplateParameterLists() > 0)
1539 return decl->getTemplateParameterList(0)->getTemplateLoc();
1540 else
1541 return decl->getInnerLocStart();
1542}
1543
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001544SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001545 TypeSourceInfo *TSI = getTypeSourceInfo();
1546 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001547 return SourceLocation();
1548}
1549
Douglas Gregor14454802011-02-25 02:25:35 +00001550void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1551 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001552 // Make sure the extended decl info is allocated.
1553 if (!hasExtInfo()) {
1554 // Save (non-extended) type source info pointer.
1555 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1556 // Allocate external info struct.
1557 DeclInfo = new (getASTContext()) ExtInfo;
1558 // Restore savedTInfo into (extended) decl info.
1559 getExtInfo()->TInfo = savedTInfo;
1560 }
1561 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001562 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001563 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001564 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001565 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001566 if (getExtInfo()->NumTemplParamLists == 0) {
1567 // Save type source info pointer.
1568 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1569 // Deallocate the extended decl info.
1570 getASTContext().Deallocate(getExtInfo());
1571 // Restore savedTInfo into (non-extended) decl info.
1572 DeclInfo = savedTInfo;
1573 }
1574 else
1575 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001576 }
1577 }
1578}
1579
Abramo Bagnara60804e12011-03-18 15:16:37 +00001580void
1581DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1582 unsigned NumTPLists,
1583 TemplateParameterList **TPLists) {
1584 assert(NumTPLists > 0);
1585 // Make sure the extended decl info is allocated.
1586 if (!hasExtInfo()) {
1587 // Save (non-extended) type source info pointer.
1588 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1589 // Allocate external info struct.
1590 DeclInfo = new (getASTContext()) ExtInfo;
1591 // Restore savedTInfo into (extended) decl info.
1592 getExtInfo()->TInfo = savedTInfo;
1593 }
1594 // Set the template parameter lists info.
1595 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1596}
1597
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001598SourceLocation DeclaratorDecl::getOuterLocStart() const {
1599 return getTemplateOrInnerLocStart(this);
1600}
1601
Abramo Bagnaraea947882011-03-08 16:41:52 +00001602namespace {
1603
1604// Helper function: returns true if QT is or contains a type
1605// having a postfix component.
1606bool typeIsPostfix(clang::QualType QT) {
1607 while (true) {
1608 const Type* T = QT.getTypePtr();
1609 switch (T->getTypeClass()) {
1610 default:
1611 return false;
1612 case Type::Pointer:
1613 QT = cast<PointerType>(T)->getPointeeType();
1614 break;
1615 case Type::BlockPointer:
1616 QT = cast<BlockPointerType>(T)->getPointeeType();
1617 break;
1618 case Type::MemberPointer:
1619 QT = cast<MemberPointerType>(T)->getPointeeType();
1620 break;
1621 case Type::LValueReference:
1622 case Type::RValueReference:
1623 QT = cast<ReferenceType>(T)->getPointeeType();
1624 break;
1625 case Type::PackExpansion:
1626 QT = cast<PackExpansionType>(T)->getPattern();
1627 break;
1628 case Type::Paren:
1629 case Type::ConstantArray:
1630 case Type::DependentSizedArray:
1631 case Type::IncompleteArray:
1632 case Type::VariableArray:
1633 case Type::FunctionProto:
1634 case Type::FunctionNoProto:
1635 return true;
1636 }
1637 }
1638}
1639
1640} // namespace
1641
1642SourceRange DeclaratorDecl::getSourceRange() const {
1643 SourceLocation RangeEnd = getLocation();
1644 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001645 // If the declaration has no name or the type extends past the name take the
1646 // end location of the type.
1647 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001648 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1649 }
1650 return SourceRange(getOuterLocStart(), RangeEnd);
1651}
1652
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001653void
Douglas Gregor20527e22010-06-15 17:44:38 +00001654QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1655 unsigned NumTPLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001656 TemplateParameterList **TPLists) {
Craig Topper36250ad2014-05-12 05:36:57 +00001657 assert((NumTPLists == 0 || TPLists != nullptr) &&
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001658 "Empty array of template parameters with positive size!");
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001659
1660 // Free previous template parameters (if any).
1661 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001662 Context.Deallocate(TemplParamLists);
Craig Topper36250ad2014-05-12 05:36:57 +00001663 TemplParamLists = nullptr;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001664 NumTemplParamLists = 0;
1665 }
1666 // Set info on matched template parameter lists (if any).
1667 if (NumTPLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001668 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001669 NumTemplParamLists = NumTPLists;
1670 for (unsigned i = NumTPLists; i-- > 0; )
1671 TemplParamLists[i] = TPLists[i];
1672 }
1673}
1674
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001675//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001676// VarDecl Implementation
1677//===----------------------------------------------------------------------===//
1678
Sebastian Redl833ef452010-01-26 22:01:41 +00001679const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1680 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001681 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001682 case SC_Auto: return "auto";
1683 case SC_Extern: return "extern";
1684 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1685 case SC_PrivateExtern: return "__private_extern__";
1686 case SC_Register: return "register";
1687 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001688 }
1689
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001690 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001691}
1692
Richard Smith053f6c62014-05-16 23:01:30 +00001693VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1694 SourceLocation StartLoc, SourceLocation IdLoc,
1695 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1696 StorageClass SC)
1697 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1698 redeclarable_base(C), Init() {
Benjamin Kramera939c232014-03-15 18:54:13 +00001699 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1700 "VarDeclBitfields too large!");
1701 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1702 "ParmVarDeclBitfields too large!");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001703 AllBits = 0;
1704 VarDeclBits.SClass = SC;
1705 // Everything else is implicitly initialized to false.
1706}
1707
Abramo Bagnaradff19302011-03-08 08:55:46 +00001708VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1709 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001710 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001711 StorageClass S) {
Richard Smith053f6c62014-05-16 23:01:30 +00001712 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001713}
1714
Douglas Gregor72172e92012-01-05 21:55:30 +00001715VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00001716 return new (C, ID)
1717 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1718 QualType(), nullptr, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001719}
1720
Douglas Gregorbf62d642010-12-06 18:36:25 +00001721void VarDecl::setStorageClass(StorageClass SC) {
1722 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001723 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001724}
1725
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001726VarDecl::TLSKind VarDecl::getTLSKind() const {
1727 switch (VarDeclBits.TSCSpec) {
1728 case TSCS_unspecified:
1729 if (hasAttr<ThreadAttr>())
1730 return TLS_Static;
1731 return TLS_None;
1732 case TSCS___thread: // Fall through.
1733 case TSCS__Thread_local:
1734 return TLS_Static;
1735 case TSCS_thread_local:
1736 return TLS_Dynamic;
1737 }
1738 llvm_unreachable("Unknown thread storage class specifier!");
1739}
1740
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001741SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001742 if (const Expr *Init = getInit()) {
1743 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001744 // If Init is implicit, ignore its source range and fallback on
1745 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1746 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001747 return SourceRange(getOuterLocStart(), InitEnd);
1748 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001749 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001750}
1751
Rafael Espindola88510672013-01-04 21:18:45 +00001752template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001753static LanguageLinkage getDeclLanguageLinkage(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001754 // C++ [dcl.link]p1: All function types, function names with external linkage,
1755 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001756 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001757 return NoLanguageLinkage;
1758
1759 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001760 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001761 ASTContext &Context = D.getASTContext();
1762 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001763 return CLanguageLinkage;
1764
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001765 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1766 // language linkage of the names of class members and the function type of
1767 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001768 const DeclContext *DC = D.getDeclContext();
1769 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001770 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001771
1772 // If the first decl is in an extern "C" context, any other redeclaration
1773 // will have C language linkage. If the first one is not in an extern "C"
1774 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00001775 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00001776 return CLanguageLinkage;
1777 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001778}
1779
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001780template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001781static bool isDeclExternC(const T &D) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001782 // Since the context is ignored for class members, they can only have C++
1783 // language linkage or no language linkage.
1784 const DeclContext *DC = D.getDeclContext();
1785 if (DC->isRecord()) {
1786 assert(D.getASTContext().getLangOpts().CPlusPlus);
1787 return false;
1788 }
1789
1790 return D.getLanguageLinkage() == CLanguageLinkage;
1791}
1792
Rafael Espindolaf4187652013-02-14 01:18:37 +00001793LanguageLinkage VarDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00001794 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001795}
1796
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001797bool VarDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00001798 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001799}
1800
Rafael Espindola593537a2013-05-05 20:15:21 +00001801bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001802 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001803}
1804
1805bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001806 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001807}
1808
Rafael Espindola8db352d2013-10-17 15:37:26 +00001809VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00001810
Daniel Dunbar9d355812012-03-09 01:51:51 +00001811VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1812 ASTContext &C) const
1813{
Sebastian Redl35351a92010-01-31 22:27:38 +00001814 // C++ [basic.def]p2:
1815 // A declaration is a definition unless [...] it contains the 'extern'
1816 // specifier or a linkage-specification and neither an initializer [...],
1817 // it declares a static data member in a class declaration [...].
Richard Smith8809a0c2013-09-27 20:14:12 +00001818 // C++1y [temp.expl.spec]p15:
1819 // An explicit specialization of a static data member or an explicit
1820 // specialization of a static data member template is a definition if the
1821 // declaration includes an initializer; otherwise, it is a declaration.
1822 //
1823 // FIXME: How do you declare (but not define) a partial specialization of
1824 // a static data member template outside the containing class?
Sebastian Redl35351a92010-01-31 22:27:38 +00001825 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00001826 if (isOutOfLine() &&
1827 (hasInit() ||
1828 // If the first declaration is out-of-line, this may be an
1829 // instantiation of an out-of-line partial specialization of a variable
1830 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00001831 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00001832 ? getTemplateSpecializationKind() == TSK_Undeclared
1833 : getTemplateSpecializationKind() !=
1834 TSK_ExplicitSpecialization) ||
1835 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00001836 return Definition;
1837 else
1838 return DeclarationOnly;
1839 }
1840 // C99 6.7p5:
1841 // A definition of an identifier is a declaration for that identifier that
1842 // [...] causes storage to be reserved for that object.
1843 // Note: that applies for all non-file-scope objects.
1844 // C99 6.9.2p1:
1845 // If the declaration of an identifier for an object has file scope and an
1846 // initializer, the declaration is an external definition for the identifier
1847 if (hasInit())
1848 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00001849
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001850 if (hasAttr<AliasAttr>())
1851 return Definition;
1852
Richard Smith8809a0c2013-09-27 20:14:12 +00001853 // A variable template specialization (other than a static data member
1854 // template or an explicit specialization) is a declaration until we
1855 // instantiate its initializer.
1856 if (isa<VarTemplateSpecializationDecl>(this) &&
1857 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1858 return DeclarationOnly;
1859
Sebastian Redl35351a92010-01-31 22:27:38 +00001860 if (hasExternalStorage())
1861 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00001862
Rafael Espindolabff59562013-04-25 12:11:36 +00001863 // [dcl.link] p7:
1864 // A declaration directly contained in a linkage-specification is treated
1865 // as if it contains the extern specifier for the purpose of determining
1866 // the linkage of the declared name and whether it is a definition.
Richard Smith03c05032014-02-17 23:34:47 +00001867 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00001868 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00001869
Sebastian Redl35351a92010-01-31 22:27:38 +00001870 // C99 6.9.2p2:
1871 // A declaration of an object that has file scope without an initializer,
1872 // and without a storage class specifier or the scs 'static', constitutes
1873 // a tentative definition.
1874 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001875 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00001876 return TentativeDefinition;
1877
1878 // What's left is (in C, block-scope) declarations without initializers or
1879 // external storage. These are definitions.
1880 return Definition;
1881}
1882
Sebastian Redl35351a92010-01-31 22:27:38 +00001883VarDecl *VarDecl::getActingDefinition() {
1884 DefinitionKind Kind = isThisDeclarationADefinition();
1885 if (Kind != TentativeDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00001886 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00001887
Craig Topper36250ad2014-05-12 05:36:57 +00001888 VarDecl *LastTentative = nullptr;
Rafael Espindola8db352d2013-10-17 15:37:26 +00001889 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001890 for (auto I : First->redecls()) {
1891 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00001892 if (Kind == Definition)
Craig Topper36250ad2014-05-12 05:36:57 +00001893 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00001894 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00001895 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00001896 }
1897 return LastTentative;
1898}
1899
Daniel Dunbar9d355812012-03-09 01:51:51 +00001900VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001901 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001902 for (auto I : First->redecls()) {
1903 if (I->isThisDeclarationADefinition(C) == Definition)
1904 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00001905 }
Craig Topper36250ad2014-05-12 05:36:57 +00001906 return nullptr;
Sebastian Redl5ca79842010-02-01 20:16:42 +00001907}
1908
Daniel Dunbar9d355812012-03-09 01:51:51 +00001909VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00001910 DefinitionKind Kind = DeclarationOnly;
1911
Rafael Espindola8db352d2013-10-17 15:37:26 +00001912 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001913 for (auto I : First->redecls()) {
1914 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001915 if (Kind == Definition)
1916 break;
1917 }
John McCall37bb6c92010-10-29 22:22:43 +00001918
1919 return Kind;
1920}
1921
Sebastian Redl5ca79842010-02-01 20:16:42 +00001922const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00001923 for (auto I : redecls()) {
1924 if (auto Expr = I->getInit()) {
1925 D = I;
1926 return Expr;
1927 }
Sebastian Redl833ef452010-01-26 22:01:41 +00001928 }
Craig Topper36250ad2014-05-12 05:36:57 +00001929 return nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00001930}
1931
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001932bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00001933 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001934 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001935
1936 if (!isStaticDataMember())
1937 return false;
1938
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001939 // If this static data member was instantiated from a static data member of
1940 // a class template, check whether that static data member was defined
1941 // out-of-line.
1942 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1943 return VD->isOutOfLine();
1944
1945 return false;
1946}
1947
Douglas Gregor1d957a32009-10-27 18:42:08 +00001948VarDecl *VarDecl::getOutOfLineDefinition() {
1949 if (!isStaticDataMember())
Craig Topper36250ad2014-05-12 05:36:57 +00001950 return nullptr;
1951
Aaron Ballman86c93902014-03-06 23:45:36 +00001952 for (auto RD : redecls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00001953 if (RD->getLexicalDeclContext()->isFileContext())
Aaron Ballman86c93902014-03-06 23:45:36 +00001954 return RD;
Douglas Gregor1d957a32009-10-27 18:42:08 +00001955 }
Craig Topper36250ad2014-05-12 05:36:57 +00001956
1957 return nullptr;
Douglas Gregor1d957a32009-10-27 18:42:08 +00001958}
1959
Douglas Gregord5058122010-02-11 01:19:42 +00001960void VarDecl::setInit(Expr *I) {
Sebastian Redl833ef452010-01-26 22:01:41 +00001961 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1962 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00001963 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00001964 }
1965
1966 Init = I;
1967}
1968
Daniel Dunbar9d355812012-03-09 01:51:51 +00001969bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001970 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00001971
Richard Smith35ecb362012-03-02 04:14:40 +00001972 if (!Lang.CPlusPlus)
1973 return false;
1974
1975 // In C++11, any variable of reference type can be used in a constant
1976 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001977 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00001978 return true;
1979
1980 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00001981 // not require the variable to be non-volatile, but we consider this to be a
1982 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00001983 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00001984 return false;
1985
1986 // In C++, const, non-volatile variables of integral or enumeration types
1987 // can be used in constant expressions.
1988 if (getType()->isIntegralOrEnumerationType())
1989 return true;
1990
Richard Smith35ecb362012-03-02 04:14:40 +00001991 // Additionally, in C++11, non-volatile constexpr variables can be used in
1992 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001993 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00001994}
1995
Richard Smithd0b4dd62011-12-19 06:19:21 +00001996/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1997/// form, which contains extra information on the evaluated value of the
1998/// initializer.
1999EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2000 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
2001 if (!Eval) {
2002 Stmt *S = Init.get<Stmt *>();
Manuel Klimeka7328992013-06-03 13:51:33 +00002003 // Note: EvaluatedStmt contains an APValue, which usually holds
2004 // resources not allocated from the ASTContext. We need to do some
2005 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2006 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002007 Eval = new (getASTContext()) EvaluatedStmt;
2008 Eval->Value = S;
2009 Init = Eval;
2010 }
2011 return Eval;
2012}
2013
Richard Smithdafff942012-01-14 04:30:29 +00002014APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002015 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00002016 return evaluateValue(Notes);
2017}
2018
Manuel Klimeka7328992013-06-03 13:51:33 +00002019namespace {
2020// Destroy an APValue that was allocated in an ASTContext.
2021void DestroyAPValue(void* UntypedValue) {
2022 static_cast<APValue*>(UntypedValue)->~APValue();
2023}
2024} // namespace
2025
Richard Smithdafff942012-01-14 04:30:29 +00002026APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002027 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002028 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2029
2030 // We only produce notes indicating why an initializer is non-constant the
2031 // first time it is evaluated. FIXME: The notes won't always be emitted the
2032 // first time we try evaluation, so might not be produced at all.
2033 if (Eval->WasEvaluated)
Craig Topper36250ad2014-05-12 05:36:57 +00002034 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002035
2036 const Expr *Init = cast<Expr>(Eval->Value);
2037 assert(!Init->isValueDependent());
2038
2039 if (Eval->IsEvaluating) {
2040 // FIXME: Produce a diagnostic for self-initialization.
2041 Eval->CheckedICE = true;
2042 Eval->IsICE = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002043 return nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002044 }
2045
2046 Eval->IsEvaluating = true;
2047
2048 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2049 this, Notes);
2050
Manuel Klimeka7328992013-06-03 13:51:33 +00002051 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2052 // or that it's empty (so that there's nothing to clean up) if evaluation
2053 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002054 if (!Result)
2055 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00002056 else if (Eval->Evaluated.needsCleanup())
2057 getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002058
2059 Eval->IsEvaluating = false;
2060 Eval->WasEvaluated = true;
2061
2062 // In C++11, we have determined whether the initializer was a constant
2063 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002064 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002065 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00002066 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002067 }
2068
Craig Topper36250ad2014-05-12 05:36:57 +00002069 return Result ? &Eval->Evaluated : nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002070}
2071
2072bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00002073 // Initializers of weak variables are never ICEs.
2074 if (isWeak())
2075 return false;
2076
Richard Smithd0b4dd62011-12-19 06:19:21 +00002077 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2078 if (Eval->CheckedICE)
2079 // We have already checked whether this subexpression is an
2080 // integral constant expression.
2081 return Eval->IsICE;
2082
2083 const Expr *Init = cast<Expr>(Eval->Value);
2084 assert(!Init->isValueDependent());
2085
2086 // In C++11, evaluate the initializer to check whether it's a constant
2087 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002088 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002089 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002090 evaluateValue(Notes);
2091 return Eval->IsICE;
2092 }
2093
2094 // It's an ICE whether or not the definition we found is
2095 // out-of-line. See DR 721 and the discussion in Clang PR
2096 // 6206 for details.
2097
2098 if (Eval->CheckingICE)
2099 return false;
2100 Eval->CheckingICE = true;
2101
2102 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2103 Eval->CheckingICE = false;
2104 Eval->CheckedICE = true;
2105 return Eval->IsICE;
2106}
2107
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002108VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002109 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002110 return cast<VarDecl>(MSI->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002111
2112 return nullptr;
Douglas Gregor86d142a2009-10-08 07:24:58 +00002113}
2114
Douglas Gregor3c74d412009-10-14 20:14:33 +00002115TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002116 if (const VarTemplateSpecializationDecl *Spec =
2117 dyn_cast<VarTemplateSpecializationDecl>(this))
2118 return Spec->getSpecializationKind();
2119
Sebastian Redl35351a92010-01-31 22:27:38 +00002120 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002121 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002122
Douglas Gregor86d142a2009-10-08 07:24:58 +00002123 return TSK_Undeclared;
2124}
2125
Richard Smith8809a0c2013-09-27 20:14:12 +00002126SourceLocation VarDecl::getPointOfInstantiation() const {
2127 if (const VarTemplateSpecializationDecl *Spec =
2128 dyn_cast<VarTemplateSpecializationDecl>(this))
2129 return Spec->getPointOfInstantiation();
2130
2131 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2132 return MSI->getPointOfInstantiation();
2133
2134 return SourceLocation();
2135}
2136
Larisse Voufo39a1e502013-08-06 01:03:05 +00002137VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2138 return getASTContext().getTemplateOrSpecializationInfo(this)
2139 .dyn_cast<VarTemplateDecl *>();
2140}
2141
2142void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2143 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2144}
2145
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002146MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002147 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002148 // FIXME: Remove ?
2149 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2150 return getASTContext().getTemplateOrSpecializationInfo(this)
2151 .dyn_cast<MemberSpecializationInfo *>();
Craig Topper36250ad2014-05-12 05:36:57 +00002152 return nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002153}
2154
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002155void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2156 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002157 assert((isa<VarTemplateSpecializationDecl>(this) ||
2158 getMemberSpecializationInfo()) &&
2159 "not a variable or static data member template specialization");
2160
Larisse Voufo39a1e502013-08-06 01:03:05 +00002161 if (VarTemplateSpecializationDecl *Spec =
2162 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2163 Spec->setSpecializationKind(TSK);
2164 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2165 Spec->getPointOfInstantiation().isInvalid())
2166 Spec->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002167 }
2168
2169 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2170 MSI->setTemplateSpecializationKind(TSK);
2171 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2172 MSI->getPointOfInstantiation().isInvalid())
2173 MSI->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002174 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002175}
2176
2177void
2178VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2179 TemplateSpecializationKind TSK) {
2180 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2181 "Previous template or instantiation?");
2182 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002183}
2184
Sebastian Redl833ef452010-01-26 22:01:41 +00002185//===----------------------------------------------------------------------===//
2186// ParmVarDecl Implementation
2187//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002188
Sebastian Redl833ef452010-01-26 22:01:41 +00002189ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002190 SourceLocation StartLoc,
2191 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002192 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002193 StorageClass S, Expr *DefArg) {
Richard Smith053f6c62014-05-16 23:01:30 +00002194 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smithf7981722013-11-22 09:01:48 +00002195 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002196}
2197
Reid Kleckner8a365022013-06-24 17:51:48 +00002198QualType ParmVarDecl::getOriginalType() const {
2199 TypeSourceInfo *TSI = getTypeSourceInfo();
2200 QualType T = TSI ? TSI->getType() : getType();
2201 if (const DecayedType *DT = dyn_cast<DecayedType>(T))
2202 return DT->getOriginalType();
2203 return T;
2204}
2205
Douglas Gregor72172e92012-01-05 21:55:30 +00002206ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00002207 return new (C, ID)
2208 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2209 nullptr, QualType(), nullptr, SC_None, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00002210}
2211
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002212SourceRange ParmVarDecl::getSourceRange() const {
2213 if (!hasInheritedDefaultArg()) {
2214 SourceRange ArgRange = getDefaultArgRange();
2215 if (ArgRange.isValid())
2216 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2217 }
2218
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002219 // DeclaratorDecl considers the range of postfix types as overlapping with the
2220 // declaration name, but this is not the case with parameters in ObjC methods.
2221 if (isa<ObjCMethodDecl>(getDeclContext()))
2222 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2223
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002224 return DeclaratorDecl::getSourceRange();
2225}
2226
Sebastian Redl833ef452010-01-26 22:01:41 +00002227Expr *ParmVarDecl::getDefaultArg() {
2228 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2229 assert(!hasUninstantiatedDefaultArg() &&
2230 "Default argument is not yet instantiated!");
2231
2232 Expr *Arg = getInit();
John McCall5d413782010-12-06 08:20:24 +00002233 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002234 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002235
Sebastian Redl833ef452010-01-26 22:01:41 +00002236 return Arg;
2237}
2238
Sebastian Redl833ef452010-01-26 22:01:41 +00002239SourceRange ParmVarDecl::getDefaultArgRange() const {
2240 if (const Expr *E = getInit())
2241 return E->getSourceRange();
2242
2243 if (hasUninstantiatedDefaultArg())
2244 return getUninstantiatedDefaultArg()->getSourceRange();
2245
2246 return SourceRange();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002247}
2248
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00002249bool ParmVarDecl::isParameterPack() const {
2250 return isa<PackExpansionType>(getType());
2251}
2252
Ted Kremenek540017e2011-10-06 05:00:56 +00002253void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2254 getASTContext().setParameterIndex(this, parameterIndex);
2255 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2256}
2257
2258unsigned ParmVarDecl::getParameterIndexLarge() const {
2259 return getASTContext().getParameterIndex(this);
2260}
2261
Nuno Lopes394ec982008-12-17 23:39:55 +00002262//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002263// FunctionDecl Implementation
2264//===----------------------------------------------------------------------===//
2265
Benjamin Kramer9170e912013-02-22 15:46:01 +00002266void FunctionDecl::getNameForDiagnostic(
2267 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2268 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002269 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2270 if (TemplateArgs)
Benjamin Kramer9170e912013-02-22 15:46:01 +00002271 TemplateSpecializationType::PrintTemplateArgumentList(
2272 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002273}
2274
Ted Kremenek186a0742010-04-29 16:49:01 +00002275bool FunctionDecl::isVariadic() const {
2276 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
2277 return FT->isVariadic();
2278 return false;
2279}
2280
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002281bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002282 for (auto I : redecls()) {
Francois Pichet1c229c02011-04-22 22:18:13 +00002283 if (I->Body || I->IsLateTemplateParsed) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002284 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002285 return true;
2286 }
2287 }
2288
2289 return false;
2290}
2291
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002292bool FunctionDecl::hasTrivialBody() const
2293{
2294 Stmt *S = getBody();
2295 if (!S) {
2296 // Since we don't have a body for this function, we don't know if it's
2297 // trivial or not.
2298 return false;
2299 }
2300
2301 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2302 return true;
2303 return false;
2304}
2305
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002306bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002307 for (auto I : redecls()) {
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002308 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
2309 I->hasAttr<AliasAttr>()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002310 Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002311 return true;
2312 }
2313 }
2314
2315 return false;
2316}
2317
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002318Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002319 if (!hasBody(Definition))
Craig Topper36250ad2014-05-12 05:36:57 +00002320 return nullptr;
Rafael Espindola44503012013-10-19 01:37:17 +00002321
2322 if (Definition->Body)
2323 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002324
Craig Topper36250ad2014-05-12 05:36:57 +00002325 return nullptr;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002326}
2327
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002328void FunctionDecl::setBody(Stmt *B) {
2329 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002330 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002331 EndRangeLoc = B->getLocEnd();
2332}
2333
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002334void FunctionDecl::setPure(bool P) {
2335 IsPure = P;
2336 if (P)
2337 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2338 Parent->markedVirtualFunctionPure();
2339}
2340
Richard Smith8d0dc312013-07-21 23:12:18 +00002341template<std::size_t Len>
2342static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2343 IdentifierInfo *II = ND->getIdentifier();
2344 return II && II->isStr(Str);
2345}
2346
Douglas Gregor16618f22009-09-12 00:17:51 +00002347bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002348 const TranslationUnitDecl *tunit =
2349 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2350 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002351 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002352 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002353}
2354
David Majnemerc729b0b2013-09-16 22:44:20 +00002355bool FunctionDecl::isMSVCRTEntryPoint() const {
2356 const TranslationUnitDecl *TUnit =
2357 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2358 if (!TUnit)
2359 return false;
2360
2361 // Even though we aren't really targeting MSVCRT if we are freestanding,
2362 // semantic analysis for these functions remains the same.
2363
2364 // MSVCRT entry points only exist on MSVCRT targets.
2365 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2366 return false;
2367
2368 // Nameless functions like constructors cannot be entry points.
2369 if (!getIdentifier())
2370 return false;
2371
2372 return llvm::StringSwitch<bool>(getName())
2373 .Cases("main", // an ANSI console app
2374 "wmain", // a Unicode console App
2375 "WinMain", // an ANSI GUI app
2376 "wWinMain", // a Unicode GUI app
2377 "DllMain", // a DLL
2378 true)
2379 .Default(false);
2380}
2381
John McCall53ffd372011-05-15 17:49:20 +00002382bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2383 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2384 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2385 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2386 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2387 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2388
Richard Smithf6004412014-01-19 23:25:37 +00002389 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2390 return false;
John McCall53ffd372011-05-15 17:49:20 +00002391
2392 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002393 if (proto->getNumParams() != 2 || proto->isVariadic())
2394 return false;
John McCall53ffd372011-05-15 17:49:20 +00002395
2396 ASTContext &Context =
2397 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2398 ->getASTContext();
2399
2400 // The result type and first argument type are constant across all
2401 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002402 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002403}
2404
Richard Smith8d0dc312013-07-21 23:12:18 +00002405bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2406 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2407 return false;
2408 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2409 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2410 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2411 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2412 return false;
2413
2414 if (isa<CXXRecordDecl>(getDeclContext()))
2415 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002416
2417 // This can only fail for an invalid 'operator new' declaration.
2418 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2419 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002420
2421 const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
Nick Lewycky6fb99b92014-06-07 00:43:57 +00002422 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 2 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002423 return false;
2424
2425 // If this is a single-parameter function, it must be a replaceable global
2426 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002427 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002428 return true;
2429
2430 // Otherwise, we're looking for a second parameter whose type is
Richard Smith1cdec012013-09-29 04:40:38 +00002431 // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
Alp Toker9cacbab2014-01-20 20:26:09 +00002432 QualType Ty = FPT->getParamType(1);
Richard Smith1cdec012013-09-29 04:40:38 +00002433 ASTContext &Ctx = getASTContext();
Richard Smithb47c36f2013-11-05 09:12:18 +00002434 if (Ctx.getLangOpts().SizedDeallocation &&
2435 Ctx.hasSameType(Ty, Ctx.getSizeType()))
Richard Smith1cdec012013-09-29 04:40:38 +00002436 return true;
Richard Smith8d0dc312013-07-21 23:12:18 +00002437 if (!Ty->isReferenceType())
2438 return false;
2439 Ty = Ty->getPointeeType();
2440 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2441 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002442 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Richard Trieuc771d5d2014-05-28 02:16:01 +00002443 return RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace();
Richard Smith8d0dc312013-07-21 23:12:18 +00002444}
2445
Richard Smithb47c36f2013-11-05 09:12:18 +00002446FunctionDecl *
2447FunctionDecl::getCorrespondingUnsizedGlobalDeallocationFunction() const {
2448 ASTContext &Ctx = getASTContext();
2449 if (!Ctx.getLangOpts().SizedDeallocation)
Craig Topper36250ad2014-05-12 05:36:57 +00002450 return nullptr;
Richard Smithb47c36f2013-11-05 09:12:18 +00002451
2452 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
Craig Topper36250ad2014-05-12 05:36:57 +00002453 return nullptr;
Richard Smithb47c36f2013-11-05 09:12:18 +00002454 if (getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2455 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
Craig Topper36250ad2014-05-12 05:36:57 +00002456 return nullptr;
Richard Smithb47c36f2013-11-05 09:12:18 +00002457 if (isa<CXXRecordDecl>(getDeclContext()))
Craig Topper36250ad2014-05-12 05:36:57 +00002458 return nullptr;
Richard Smithf6004412014-01-19 23:25:37 +00002459
2460 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
Craig Topper36250ad2014-05-12 05:36:57 +00002461 return nullptr;
Richard Smithb47c36f2013-11-05 09:12:18 +00002462
2463 if (getNumParams() != 2 || isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00002464 !Ctx.hasSameType(getType()->castAs<FunctionProtoType>()->getParamType(1),
Richard Smithb47c36f2013-11-05 09:12:18 +00002465 Ctx.getSizeType()))
Craig Topper36250ad2014-05-12 05:36:57 +00002466 return nullptr;
Richard Smithb47c36f2013-11-05 09:12:18 +00002467
2468 // This is a sized deallocation function. Find the corresponding unsized
2469 // deallocation function.
2470 lookup_const_result R = getDeclContext()->lookup(getDeclName());
2471 for (lookup_const_result::iterator RI = R.begin(), RE = R.end(); RI != RE;
2472 ++RI)
2473 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*RI))
2474 if (FD->getNumParams() == 1 && !FD->isVariadic())
2475 return FD;
Craig Topper36250ad2014-05-12 05:36:57 +00002476 return nullptr;
Richard Smithb47c36f2013-11-05 09:12:18 +00002477}
2478
Rafael Espindolaf4187652013-02-14 01:18:37 +00002479LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00002480 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002481}
2482
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002483bool FunctionDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00002484 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002485}
2486
Rafael Espindola593537a2013-05-05 20:15:21 +00002487bool FunctionDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002488 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002489}
2490
2491bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002492 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002493}
2494
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002495bool FunctionDecl::isGlobal() const {
2496 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2497 return Method->isStatic();
2498
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002499 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002500 return false;
2501
Mike Stump11289f42009-09-09 15:08:12 +00002502 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002503 DC->isNamespace();
2504 DC = DC->getParent()) {
2505 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2506 if (!Namespace->getDeclName())
2507 return false;
2508 break;
2509 }
2510 }
2511
2512 return true;
2513}
2514
Richard Smith10876ef2013-01-17 01:30:42 +00002515bool FunctionDecl::isNoReturn() const {
2516 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
Richard Smithdebc59d2013-01-30 05:45:05 +00002517 hasAttr<C11NoReturnAttr>() ||
Richard Smith10876ef2013-01-17 01:30:42 +00002518 getType()->getAs<FunctionType>()->getNoReturnAttr();
2519}
2520
Sebastian Redl833ef452010-01-26 22:01:41 +00002521void
2522FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002523 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002524
2525 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2526 FunctionTemplateDecl *PrevFunTmpl
Craig Topper36250ad2014-05-12 05:36:57 +00002527 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002528 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00002529 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002530 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002531
Axel Naumannfbc7b982011-11-08 18:21:06 +00002532 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002533 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002534}
2535
2536const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002537 return getFirstDecl();
Sebastian Redl833ef452010-01-26 22:01:41 +00002538}
2539
Rafael Espindola8db352d2013-10-17 15:37:26 +00002540FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002541
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002542/// \brief Returns a value indicating whether this function
2543/// corresponds to a builtin function.
2544///
2545/// The function corresponds to a built-in function if it is
2546/// declared at translation scope or within an extern "C" block and
2547/// its name matches with the name of a builtin. The returned value
2548/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002549/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002550/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002551unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002552 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002553 return 0;
2554
2555 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002556 if (!BuiltinID)
2557 return 0;
2558
2559 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00002560 if (Context.getLangOpts().CPlusPlus) {
2561 const LinkageSpecDecl *LinkageDecl = dyn_cast<LinkageSpecDecl>(
2562 getFirstDecl()->getDeclContext());
2563 // In C++, the first declaration of a builtin is always inside an implicit
2564 // extern "C".
2565 // FIXME: A recognised library function may not be directly in an extern "C"
2566 // declaration, for instance "extern "C" { namespace std { decl } }".
2567 if (!LinkageDecl || LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
2568 return 0;
2569 }
2570
2571 // If the function is marked "overloadable", it has a different mangled name
2572 // and is not the C library function.
Aaron Ballman9ead1242013-12-19 02:39:40 +00002573 if (hasAttr<OverloadableAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00002574 return 0;
2575
Douglas Gregore711f702009-02-14 18:57:46 +00002576 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2577 return BuiltinID;
2578
2579 // This function has the name of a known C library
2580 // function. Determine whether it actually refers to the C library
2581 // function or whether it just has the same name.
2582
Douglas Gregora908e7f2009-02-17 03:23:10 +00002583 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002584 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002585 return 0;
2586
Warren Hunt445d83e2013-11-01 23:46:51 +00002587 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002588}
2589
2590
Chris Lattner47c0d002009-04-25 06:03:53 +00002591/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002592/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002593/// after it has been created.
2594unsigned FunctionDecl::getNumParams() const {
Reid Kleckner0503a872013-12-05 01:23:43 +00002595 const FunctionProtoType *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002596 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002597}
2598
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002599void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002600 ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00002601 assert(!ParamInfo && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002602 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002603
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002604 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002605 if (!NewParamInfo.empty()) {
2606 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2607 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002608 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002609}
Chris Lattner41943152007-01-25 04:52:46 +00002610
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002611void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
James Molloy6f8780b2012-02-29 10:24:19 +00002612 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2613
2614 if (!NewDecls.empty()) {
2615 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2616 std::copy(NewDecls.begin(), NewDecls.end(), A);
Craig Topper5fc8fc22014-08-27 06:28:36 +00002617 DeclsInPrototypeScope = llvm::makeArrayRef(A, NewDecls.size());
Serge Pavlova8261472014-06-25 17:09:41 +00002618 // Move declarations introduced in prototype to the function context.
2619 for (auto I : NewDecls) {
2620 DeclContext *DC = I->getDeclContext();
2621 // Forward-declared reference to an enumeration is not added to
2622 // declaration scope, so skip declaration that is absent from its
2623 // declaration contexts.
2624 if (DC->containsDecl(I)) {
2625 DC->removeDecl(I);
2626 I->setDeclContext(this);
2627 addDecl(I);
2628 }
2629 }
James Molloy6f8780b2012-02-29 10:24:19 +00002630 }
2631}
2632
Chris Lattner58258242008-04-10 02:22:51 +00002633/// getMinRequiredArguments - Returns the minimum number of arguments
2634/// needed to call this function. This may be fewer than the number of
2635/// function parameters, if some of the parameters have default
Richard Smith91151782014-04-01 19:18:16 +00002636/// arguments (in C++) or are parameter packs (C++11).
Chris Lattner58258242008-04-10 02:22:51 +00002637unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002638 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002639 return getNumParams();
Chris Lattner58258242008-04-10 02:22:51 +00002640
Richard Smith91151782014-04-01 19:18:16 +00002641 unsigned NumRequiredArgs = 0;
2642 for (auto *Param : params())
2643 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2644 ++NumRequiredArgs;
Chris Lattner58258242008-04-10 02:22:51 +00002645 return NumRequiredArgs;
2646}
2647
David Majnemer54e3ba52014-04-02 23:17:29 +00002648/// \brief The combination of the extern and inline keywords under MSVC forces
2649/// the function to be required.
2650///
2651/// Note: This function assumes that we will only get called when isInlined()
2652/// would return true for this FunctionDecl.
2653bool FunctionDecl::isMSExternInline() const {
2654 assert(isInlined() && "expected to get called on an inlined function!");
2655
2656 const ASTContext &Context = getASTContext();
Hans Wennborgb0f2f142014-05-15 22:07:49 +00002657 if (!Context.getLangOpts().MSVCCompat && !hasAttr<DLLExportAttr>())
David Majnemer54e3ba52014-04-02 23:17:29 +00002658 return false;
2659
2660 for (const FunctionDecl *FD = this; FD; FD = FD->getPreviousDecl())
2661 if (FD->getStorageClass() == SC_Extern)
2662 return true;
2663
2664 return false;
2665}
2666
2667static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
2668 if (Redecl->getStorageClass() != SC_Extern)
2669 return false;
2670
2671 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
2672 FD = FD->getPreviousDecl())
2673 if (FD->getStorageClass() == SC_Extern)
2674 return false;
2675
2676 return true;
2677}
2678
Eli Friedman1b125c32012-02-07 03:50:18 +00002679static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2680 // Only consider file-scope declarations in this test.
2681 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2682 return false;
2683
2684 // Only consider explicit declarations; the presence of a builtin for a
2685 // libcall shouldn't affect whether a definition is externally visible.
2686 if (Redecl->isImplicit())
2687 return false;
2688
2689 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2690 return true; // Not an inline definition
2691
2692 return false;
2693}
2694
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002695/// \brief For a function declaration in C or C++, determine whether this
2696/// declaration causes the definition to be externally visible.
2697///
David Majnemer54e3ba52014-04-02 23:17:29 +00002698/// For instance, this determines if adding the current declaration to the set
Eli Friedman1b125c32012-02-07 03:50:18 +00002699/// of redeclarations of the given functions causes
2700/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002701bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2702 assert(!doesThisDeclarationHaveABody() &&
2703 "Must have a declaration without a body.");
2704
2705 ASTContext &Context = getASTContext();
2706
David Majnemer54e3ba52014-04-02 23:17:29 +00002707 if (Context.getLangOpts().MSVCCompat) {
2708 const FunctionDecl *Definition;
2709 if (hasBody(Definition) && Definition->isInlined() &&
2710 redeclForcesDefMSVC(this))
2711 return true;
2712 }
2713
David Blaikiebbafb8a2012-03-11 07:00:24 +00002714 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002715 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2716 // an externally visible definition.
2717 //
2718 // FIXME: What happens if gnu_inline gets added on after the first
2719 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002720 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002721 return false;
2722
2723 const FunctionDecl *Prev = this;
2724 bool FoundBody = false;
2725 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002726 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002727
2728 if (Prev->Body) {
2729 // If it's not the case that both 'inline' and 'extern' are
2730 // specified on the definition, then it is always externally visible.
2731 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002732 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002733 return false;
2734 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002735 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002736 return false;
2737 }
2738 }
2739 return FoundBody;
2740 }
2741
David Blaikiebbafb8a2012-03-11 07:00:24 +00002742 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002743 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002744
2745 // C99 6.7.4p6:
2746 // [...] If all of the file scope declarations for a function in a
2747 // translation unit include the inline function specifier without extern,
2748 // then the definition in that translation unit is an inline definition.
2749 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002750 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002751 const FunctionDecl *Prev = this;
2752 bool FoundBody = false;
2753 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002754 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002755 if (RedeclForcesDefC99(Prev))
2756 return false;
2757 }
2758 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002759}
2760
Alp Tokerd0787eb2014-07-02 01:47:15 +00002761SourceRange FunctionDecl::getReturnTypeSourceRange() const {
2762 const TypeSourceInfo *TSI = getTypeSourceInfo();
2763 if (!TSI)
2764 return SourceRange();
Alp Tokerf5b10792014-07-02 12:55:58 +00002765 FunctionTypeLoc FTL =
2766 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
2767 if (!FTL)
Alp Tokerd0787eb2014-07-02 01:47:15 +00002768 return SourceRange();
2769
Alp Tokerf5b10792014-07-02 12:55:58 +00002770 // Skip self-referential return types.
2771 const SourceManager &SM = getASTContext().getSourceManager();
2772 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
2773 SourceLocation Boundary = getNameInfo().getLocStart();
2774 if (RTRange.isInvalid() || Boundary.isInvalid() ||
2775 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
2776 return SourceRange();
Alp Tokerd0787eb2014-07-02 01:47:15 +00002777
Alp Tokerf5b10792014-07-02 12:55:58 +00002778 return RTRange;
Alp Tokerd0787eb2014-07-02 01:47:15 +00002779}
2780
Richard Smithf3814ad2013-01-25 00:08:28 +00002781/// \brief For an inline function definition in C, or for a gnu_inline function
2782/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002783///
2784/// Inline function definitions are always available for inlining optimizations.
2785/// However, depending on the language dialect, declaration specifiers, and
2786/// attributes, the definition of an inline function may or may not be
2787/// "externally" visible to other translation units in the program.
2788///
2789/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00002790/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00002791/// inline definition becomes externally visible (C99 6.7.4p6).
2792///
2793/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2794/// definition, we use the GNU semantics for inline, which are nearly the
2795/// opposite of C99 semantics. In particular, "inline" by itself will create
2796/// an externally visible symbol, but "extern inline" will not create an
2797/// externally visible symbol.
2798bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002799 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002800 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00002801 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00002802
David Blaikiebbafb8a2012-03-11 07:00:24 +00002803 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002804 // Note: If you change the logic here, please change
2805 // doesDeclarationForceExternallyVisibleDefinition as well.
2806 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00002807 // If it's not the case that both 'inline' and 'extern' are
2808 // specified on the definition, then this inline definition is
2809 // externally visible.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002810 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00002811 return true;
2812
2813 // If any declaration is 'inline' but not 'extern', then this definition
2814 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00002815 for (auto Redecl : redecls()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00002816 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002817 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00002818 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00002819 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00002820
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002821 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002822 }
Eli Friedman1b125c32012-02-07 03:50:18 +00002823
Richard Smithf3814ad2013-01-25 00:08:28 +00002824 // The rest of this function is C-only.
2825 assert(!Context.getLangOpts().CPlusPlus &&
2826 "should not use C inline rules in C++");
2827
Douglas Gregor299d76e2009-09-13 07:46:26 +00002828 // C99 6.7.4p6:
2829 // [...] If all of the file scope declarations for a function in a
2830 // translation unit include the inline function specifier without extern,
2831 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00002832 for (auto Redecl : redecls()) {
2833 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00002834 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002835 }
2836
2837 // C99 6.7.4p6:
2838 // An inline definition does not provide an external definition for the
2839 // function, and does not forbid an external definition in another
2840 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002841 return false;
2842}
2843
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002844/// getOverloadedOperator - Which C++ overloaded operator this
2845/// function represents, if any.
2846OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00002847 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2848 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002849 else
2850 return OO_None;
2851}
2852
Alexis Huntc88db062010-01-13 09:01:02 +00002853/// getLiteralIdentifier - The literal suffix identifier this function
2854/// represents, if any.
2855const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2856 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2857 return getDeclName().getCXXLiteralIdentifier();
2858 else
Craig Topper36250ad2014-05-12 05:36:57 +00002859 return nullptr;
Alexis Huntc88db062010-01-13 09:01:02 +00002860}
2861
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002862FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2863 if (TemplateOrSpecialization.isNull())
2864 return TK_NonTemplate;
2865 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2866 return TK_FunctionTemplate;
2867 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2868 return TK_MemberSpecialization;
2869 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2870 return TK_FunctionTemplateSpecialization;
2871 if (TemplateOrSpecialization.is
2872 <DependentFunctionTemplateSpecializationInfo*>())
2873 return TK_DependentFunctionTemplateSpecialization;
2874
David Blaikie83d382b2011-09-23 05:06:16 +00002875 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002876}
2877
Douglas Gregord801b062009-10-07 23:56:10 +00002878FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002879 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00002880 return cast<FunctionDecl>(Info->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002881
2882 return nullptr;
Douglas Gregord801b062009-10-07 23:56:10 +00002883}
2884
2885void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002886FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2887 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00002888 TemplateSpecializationKind TSK) {
2889 assert(TemplateOrSpecialization.isNull() &&
2890 "Member function is already a specialization");
2891 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002892 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00002893 TemplateOrSpecialization = Info;
2894}
2895
Douglas Gregorafca3b42009-10-27 20:53:28 +00002896bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00002897 // If the function is invalid, it can't be implicitly instantiated.
2898 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00002899 return false;
2900
2901 switch (getTemplateSpecializationKind()) {
2902 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00002903 case TSK_ExplicitInstantiationDefinition:
2904 return false;
2905
2906 case TSK_ImplicitInstantiation:
2907 return true;
2908
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002909 // It is possible to instantiate TSK_ExplicitSpecialization kind
2910 // if the FunctionDecl has a class scope specialization pattern.
2911 case TSK_ExplicitSpecialization:
Craig Topper36250ad2014-05-12 05:36:57 +00002912 return getClassScopeSpecializationPattern() != nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002913
Douglas Gregorafca3b42009-10-27 20:53:28 +00002914 case TSK_ExplicitInstantiationDeclaration:
2915 // Handled below.
2916 break;
2917 }
2918
2919 // Find the actual template from which we will instantiate.
2920 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002921 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00002922 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002923 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00002924
2925 // C++0x [temp.explicit]p9:
2926 // Except for inline functions, other explicit instantiation declarations
2927 // have the effect of suppressing the implicit instantiation of the entity
2928 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002929 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00002930 return true;
2931
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002932 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00002933}
2934
2935bool FunctionDecl::isTemplateInstantiation() const {
2936 switch (getTemplateSpecializationKind()) {
2937 case TSK_Undeclared:
2938 case TSK_ExplicitSpecialization:
2939 return false;
2940 case TSK_ImplicitInstantiation:
2941 case TSK_ExplicitInstantiationDeclaration:
2942 case TSK_ExplicitInstantiationDefinition:
2943 return true;
2944 }
2945 llvm_unreachable("All TSK values handled.");
2946}
Douglas Gregorafca3b42009-10-27 20:53:28 +00002947
2948FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002949 // Handle class scope explicit specialization special case.
2950 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2951 return getClassScopeSpecializationPattern();
Faisal Valib90b2112014-04-03 16:32:21 +00002952
2953 // If this is a generic lambda call operator specialization, its
2954 // instantiation pattern is always its primary template's pattern
2955 // even if its primary template was instantiated from another
2956 // member template (which happens with nested generic lambdas).
2957 // Since a lambda's call operator's body is transformed eagerly,
2958 // we don't have to go hunting for a prototype definition template
2959 // (i.e. instantiated-from-member-template) to use as an instantiation
2960 // pattern.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002961
Faisal Valib90b2112014-04-03 16:32:21 +00002962 if (isGenericLambdaCallOperatorSpecialization(
2963 dyn_cast<CXXMethodDecl>(this))) {
2964 assert(getPrimaryTemplate() && "A generic lambda specialization must be "
2965 "generated from a primary call operator "
2966 "template");
2967 assert(getPrimaryTemplate()->getTemplatedDecl()->getBody() &&
2968 "A generic lambda call operator template must always have a body - "
2969 "even if instantiated from a prototype (i.e. as written) member "
2970 "template");
2971 return getPrimaryTemplate()->getTemplatedDecl();
2972 }
2973
Douglas Gregorafca3b42009-10-27 20:53:28 +00002974 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2975 while (Primary->getInstantiatedFromMemberTemplate()) {
2976 // If we have hit a point where the user provided a specialization of
2977 // this template, we're done looking.
2978 if (Primary->isMemberSpecialization())
2979 break;
Douglas Gregorafca3b42009-10-27 20:53:28 +00002980 Primary = Primary->getInstantiatedFromMemberTemplate();
2981 }
2982
2983 return Primary->getTemplatedDecl();
2984 }
2985
2986 return getInstantiatedFromMemberFunction();
2987}
2988
Douglas Gregor70d83e22009-06-29 17:30:29 +00002989FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00002990 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002991 = TemplateOrSpecialization
2992 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00002993 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00002994 }
Craig Topper36250ad2014-05-12 05:36:57 +00002995 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00002996}
2997
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002998FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2999 return getASTContext().getClassScopeSpecializationPattern(this);
3000}
3001
Douglas Gregor70d83e22009-06-29 17:30:29 +00003002const TemplateArgumentList *
3003FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00003004 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00003005 = TemplateOrSpecialization
3006 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003007 return Info->TemplateArguments;
3008 }
Craig Topper36250ad2014-05-12 05:36:57 +00003009 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003010}
3011
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00003012const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003013FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3014 if (FunctionTemplateSpecializationInfo *Info
3015 = TemplateOrSpecialization
3016 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3017 return Info->TemplateArgumentsAsWritten;
3018 }
Craig Topper36250ad2014-05-12 05:36:57 +00003019 return nullptr;
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003020}
3021
Mike Stump11289f42009-09-09 15:08:12 +00003022void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003023FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3024 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003025 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003026 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003027 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00003028 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3029 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003030 assert(TSK != TSK_Undeclared &&
3031 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00003032 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003033 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003034 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00003035 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3036 TemplateArgs,
3037 TemplateArgsAsWritten,
3038 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003039 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00003040 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003041}
3042
John McCallb9c78482010-04-08 09:05:18 +00003043void
3044FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3045 const UnresolvedSetImpl &Templates,
3046 const TemplateArgumentListInfo &TemplateArgs) {
3047 assert(TemplateOrSpecialization.isNull());
3048 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
3049 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall900d9802010-04-13 22:18:28 +00003050 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallb9c78482010-04-08 09:05:18 +00003051 void *Buffer = Context.Allocate(Size);
3052 DependentFunctionTemplateSpecializationInfo *Info =
3053 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
3054 TemplateArgs);
3055 TemplateOrSpecialization = Info;
3056}
3057
3058DependentFunctionTemplateSpecializationInfo::
3059DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3060 const TemplateArgumentListInfo &TArgs)
3061 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
3062
3063 d.NumTemplates = Ts.size();
3064 d.NumArgs = TArgs.size();
3065
3066 FunctionTemplateDecl **TsArray =
3067 const_cast<FunctionTemplateDecl**>(getTemplates());
3068 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3069 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3070
3071 TemplateArgumentLoc *ArgsArray =
3072 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
3073 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3074 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3075}
3076
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003077TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00003078 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003079 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00003080 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00003081 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00003082 if (FTSInfo)
3083 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00003084
Douglas Gregord801b062009-10-07 23:56:10 +00003085 MemberSpecializationInfo *MSInfo
3086 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3087 if (MSInfo)
3088 return MSInfo->getTemplateSpecializationKind();
3089
3090 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003091}
3092
Mike Stump11289f42009-09-09 15:08:12 +00003093void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003094FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3095 SourceLocation PointOfInstantiation) {
3096 if (FunctionTemplateSpecializationInfo *FTSInfo
3097 = TemplateOrSpecialization.dyn_cast<
3098 FunctionTemplateSpecializationInfo*>()) {
3099 FTSInfo->setTemplateSpecializationKind(TSK);
3100 if (TSK != TSK_ExplicitSpecialization &&
3101 PointOfInstantiation.isValid() &&
3102 FTSInfo->getPointOfInstantiation().isInvalid())
3103 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3104 } else if (MemberSpecializationInfo *MSInfo
3105 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3106 MSInfo->setTemplateSpecializationKind(TSK);
3107 if (TSK != TSK_ExplicitSpecialization &&
3108 PointOfInstantiation.isValid() &&
3109 MSInfo->getPointOfInstantiation().isInvalid())
3110 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3111 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003112 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003113}
3114
3115SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00003116 if (FunctionTemplateSpecializationInfo *FTSInfo
3117 = TemplateOrSpecialization.dyn_cast<
3118 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003119 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00003120 else if (MemberSpecializationInfo *MSInfo
3121 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003122 return MSInfo->getPointOfInstantiation();
3123
3124 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00003125}
3126
Douglas Gregor6411b922009-09-11 20:15:17 +00003127bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00003128 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00003129 return true;
3130
3131 // If this function was instantiated from a member function of a
3132 // class template, check whether that member function was defined out-of-line.
3133 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3134 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003135 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003136 return Definition->isOutOfLine();
3137 }
3138
3139 // If this function was instantiated from a function template,
3140 // check whether that function template was defined out-of-line.
3141 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3142 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003143 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003144 return Definition->isOutOfLine();
3145 }
3146
3147 return false;
3148}
3149
Abramo Bagnaraea947882011-03-08 16:41:52 +00003150SourceRange FunctionDecl::getSourceRange() const {
3151 return SourceRange(getOuterLocStart(), EndRangeLoc);
3152}
3153
Anna Zaks28db7ce2012-01-18 02:45:01 +00003154unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00003155 IdentifierInfo *FnInfo = getIdentifier();
3156
3157 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00003158 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003159
3160 // Builtin handling.
3161 switch (getBuiltinID()) {
3162 case Builtin::BI__builtin_memset:
3163 case Builtin::BI__builtin___memset_chk:
3164 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003165 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003166
3167 case Builtin::BI__builtin_memcpy:
3168 case Builtin::BI__builtin___memcpy_chk:
3169 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003170 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003171
3172 case Builtin::BI__builtin_memmove:
3173 case Builtin::BI__builtin___memmove_chk:
3174 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003175 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003176
3177 case Builtin::BIstrlcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003178 return Builtin::BIstrlcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003179 case Builtin::BIstrlcat:
Anna Zaks22122702012-01-17 00:37:07 +00003180 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003181
3182 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003183 case Builtin::BImemcmp:
3184 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003185
3186 case Builtin::BI__builtin_strncpy:
3187 case Builtin::BI__builtin___strncpy_chk:
3188 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003189 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003190
3191 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003192 case Builtin::BIstrncmp:
3193 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003194
3195 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003196 case Builtin::BIstrncasecmp:
3197 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003198
3199 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003200 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003201 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003202 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003203
3204 case Builtin::BI__builtin_strndup:
3205 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003206 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003207
Anna Zaks314cd092012-02-01 19:08:57 +00003208 case Builtin::BI__builtin_strlen:
3209 case Builtin::BIstrlen:
3210 return Builtin::BIstrlen;
3211
Anna Zaks201d4892012-01-13 21:52:01 +00003212 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003213 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003214 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003215 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003216 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003217 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003218 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003219 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003220 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003221 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003222 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003223 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003224 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003225 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003226 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003227 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003228 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003229 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003230 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003231 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003232 else if (FnInfo->isStr("strlen"))
3233 return Builtin::BIstrlen;
Anna Zaks201d4892012-01-13 21:52:01 +00003234 }
3235 break;
3236 }
Anna Zaks22122702012-01-17 00:37:07 +00003237 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003238}
3239
Chris Lattner59a25942008-03-31 00:36:02 +00003240//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003241// FieldDecl Implementation
3242//===----------------------------------------------------------------------===//
3243
Jay Foad39c79802011-01-12 09:06:06 +00003244FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003245 SourceLocation StartLoc, SourceLocation IdLoc,
3246 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003247 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003248 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003249 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3250 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003251}
3252
Douglas Gregor72172e92012-01-05 21:55:30 +00003253FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003254 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3255 SourceLocation(), nullptr, QualType(), nullptr,
3256 nullptr, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00003257}
3258
Sebastian Redl833ef452010-01-26 22:01:41 +00003259bool FieldDecl::isAnonymousStructOrUnion() const {
3260 if (!isImplicit() || getDeclName())
3261 return false;
3262
3263 if (const RecordType *Record = getType()->getAs<RecordType>())
3264 return Record->getDecl()->isAnonymousStructOrUnion();
3265
3266 return false;
3267}
3268
Alexey Bataev39c81e22014-08-28 04:28:19 +00003269bool FieldDecl::isBitField() const {
3270 if (getInClassInitStyle() == ICIS_NoInit &&
3271 InitializerOrBitWidth.getPointer()) {
3272 assert(getDeclContext() && "No parent context for FieldDecl");
3273 return !getDeclContext()->isRecord() || !getParent()->isLambda();
3274 }
3275 return false;
3276}
3277
Richard Smithcaf33902011-10-10 18:28:20 +00003278unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3279 assert(isBitField() && "not a bitfield");
Alexey Bataev39c81e22014-08-28 04:28:19 +00003280 Expr *BitWidth = static_cast<Expr *>(InitializerOrBitWidth.getPointer());
Richard Smithcaf33902011-10-10 18:28:20 +00003281 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3282}
3283
John McCall4e819612011-01-20 07:57:12 +00003284unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00003285 const FieldDecl *Canonical = getCanonicalDecl();
3286 if (Canonical != this)
3287 return Canonical->getFieldIndex();
3288
John McCall4e819612011-01-20 07:57:12 +00003289 if (CachedFieldIndex) return CachedFieldIndex - 1;
3290
Richard Smithd62306a2011-11-10 06:34:14 +00003291 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00003292 const RecordDecl *RD = getParent();
Richard Smithd62306a2011-11-10 06:34:14 +00003293
Hans Wennborga302cd92014-08-21 16:06:57 +00003294 for (auto *Field : RD->fields()) {
3295 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3296 ++Index;
3297 }
John McCall4e819612011-01-20 07:57:12 +00003298
Richard Smithd62306a2011-11-10 06:34:14 +00003299 assert(CachedFieldIndex && "failed to find field in parent");
3300 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00003301}
3302
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003303SourceRange FieldDecl::getSourceRange() const {
Alexey Bataev39c81e22014-08-28 04:28:19 +00003304 if (const Expr *E =
3305 static_cast<const Expr *>(InitializerOrBitWidth.getPointer()))
Abramo Bagnaraff371ac2011-08-05 08:02:55 +00003306 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00003307 return DeclaratorDecl::getSourceRange();
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003308}
3309
Abramo Bagnarab1cdde72012-07-02 20:35:48 +00003310void FieldDecl::setBitWidth(Expr *Width) {
3311 assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
Alexey Bataev39c81e22014-08-28 04:28:19 +00003312 "bit width, initializer or captured type already set");
Abramo Bagnarab1cdde72012-07-02 20:35:48 +00003313 InitializerOrBitWidth.setPointer(Width);
3314}
3315
Richard Smith938f40b2011-06-11 17:19:42 +00003316void FieldDecl::setInClassInitializer(Expr *Init) {
Richard Smith2b013182012-06-10 03:12:00 +00003317 assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
Alexey Bataev39c81e22014-08-28 04:28:19 +00003318 "bit width, initializer or captured expr already set");
Richard Smith938f40b2011-06-11 17:19:42 +00003319 InitializerOrBitWidth.setPointer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003320}
3321
Alexey Bataev39c81e22014-08-28 04:28:19 +00003322bool FieldDecl::hasCapturedVLAType() const {
3323 return getDeclContext()->isRecord() && getParent()->isLambda() &&
3324 InitializerOrBitWidth.getPointer();
3325}
3326
3327void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
3328 assert(getParent()->isLambda() && "capturing type in non-lambda.");
3329 assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
3330 "bit width, initializer or captured type already set");
3331 InitializerOrBitWidth.setPointer(const_cast<VariableArrayType *>(VLAType));
3332}
3333
Sebastian Redl833ef452010-01-26 22:01:41 +00003334//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003335// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00003336//===----------------------------------------------------------------------===//
3337
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003338SourceLocation TagDecl::getOuterLocStart() const {
3339 return getTemplateOrInnerLocStart(this);
3340}
3341
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003342SourceRange TagDecl::getSourceRange() const {
3343 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003344 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003345}
3346
Rafael Espindola8db352d2013-10-17 15:37:26 +00003347TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00003348
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00003349void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer50ce8352013-09-17 23:57:10 +00003350 NamedDeclOrQualifier = TDD;
Reid Klecknercae82a22014-04-23 22:03:04 +00003351 if (const Type *T = getTypeForDecl()) {
3352 (void)T;
Richard Smith5b21db82014-04-23 18:20:42 +00003353 assert(T->isLinkageValid());
Reid Klecknercae82a22014-04-23 22:03:04 +00003354 }
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003355 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00003356}
3357
Douglas Gregordee1be82009-01-17 00:42:38 +00003358void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003359 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00003360
David Blaikie095deba2012-11-14 01:52:05 +00003361 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
Richard Smith053f6c62014-05-16 23:01:30 +00003362 struct CXXRecordDecl::DefinitionData *Data =
John McCall67da35c2010-02-04 22:26:26 +00003363 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00003364 for (auto I : redecls())
Richard Smith64c06302014-05-22 23:19:02 +00003365 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00003366 }
Douglas Gregordee1be82009-01-17 00:42:38 +00003367}
3368
3369void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00003370 assert((!isa<CXXRecordDecl>(this) ||
3371 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3372 "definition completed but not started");
3373
John McCallf937c022011-10-07 06:10:15 +00003374 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003375 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00003376
3377 if (ASTMutationListener *L = getASTMutationListener())
3378 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00003379}
3380
John McCallf937c022011-10-07 06:10:15 +00003381TagDecl *TagDecl::getDefinition() const {
3382 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003383 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003384
3385 // If it's possible for us to have an out-of-date definition, check now.
3386 if (MayHaveOutOfDateDef) {
3387 if (IdentifierInfo *II = getIdentifier()) {
3388 if (II->isOutOfDate()) {
3389 updateOutOfDate(*II);
3390 }
3391 }
3392 }
3393
Andrew Trickba266ee2010-10-19 21:54:32 +00003394 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
3395 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003396
Aaron Ballman86c93902014-03-06 23:45:36 +00003397 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00003398 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00003399 return R;
Mike Stump11289f42009-09-09 15:08:12 +00003400
Craig Topper36250ad2014-05-12 05:36:57 +00003401 return nullptr;
Ted Kremenek21475702008-09-05 17:16:31 +00003402}
3403
Douglas Gregor14454802011-02-25 02:25:35 +00003404void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3405 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00003406 // Make sure the extended qualifier info is allocated.
3407 if (!hasExtInfo())
David Majnemer50ce8352013-09-17 23:57:10 +00003408 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00003409 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00003410 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003411 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00003412 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00003413 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00003414 if (getExtInfo()->NumTemplParamLists == 0) {
3415 getASTContext().Deallocate(getExtInfo());
Craig Topper36250ad2014-05-12 05:36:57 +00003416 NamedDeclOrQualifier = (TypedefNameDecl*)nullptr;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003417 }
3418 else
3419 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00003420 }
3421 }
3422}
3423
Abramo Bagnara60804e12011-03-18 15:16:37 +00003424void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
3425 unsigned NumTPLists,
3426 TemplateParameterList **TPLists) {
3427 assert(NumTPLists > 0);
3428 // Make sure the extended decl info is allocated.
3429 if (!hasExtInfo())
3430 // Allocate external info struct.
David Majnemer50ce8352013-09-17 23:57:10 +00003431 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003432 // Set the template parameter lists info.
3433 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
3434}
3435
Ted Kremenek21475702008-09-05 17:16:31 +00003436//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003437// EnumDecl Implementation
3438//===----------------------------------------------------------------------===//
3439
David Blaikie68e081d2011-12-20 02:48:34 +00003440void EnumDecl::anchor() { }
3441
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003442EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3443 SourceLocation StartLoc, SourceLocation IdLoc,
3444 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00003445 EnumDecl *PrevDecl, bool IsScoped,
3446 bool IsScopedUsingClassTag, bool IsFixed) {
Richard Smith053f6c62014-05-16 23:01:30 +00003447 EnumDecl *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
Richard Smithf7981722013-11-22 09:01:48 +00003448 IsScoped, IsScopedUsingClassTag,
3449 IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003450 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00003451 C.getTypeDeclType(Enum, PrevDecl);
3452 return Enum;
3453}
3454
Douglas Gregor72172e92012-01-05 21:55:30 +00003455EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003456 EnumDecl *Enum =
3457 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3458 nullptr, nullptr, false, false, false);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003459 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3460 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003461}
3462
Alp Tokerb9fa5122014-01-06 11:31:18 +00003463SourceRange EnumDecl::getIntegerTypeRange() const {
3464 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3465 return TI->getTypeLoc().getSourceRange();
3466 return SourceRange();
3467}
3468
Douglas Gregord5058122010-02-11 01:19:42 +00003469void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00003470 QualType NewPromotionType,
3471 unsigned NumPositiveBits,
3472 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00003473 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00003474 if (!IntegerType)
3475 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00003476 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00003477 setNumPositiveBits(NumPositiveBits);
3478 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00003479 TagDecl::completeDefinition();
3480}
3481
Richard Smith7d137e32012-03-23 03:33:32 +00003482TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3483 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3484 return MSI->getTemplateSpecializationKind();
3485
3486 return TSK_Undeclared;
3487}
3488
3489void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3490 SourceLocation PointOfInstantiation) {
3491 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3492 assert(MSI && "Not an instantiated member enumeration?");
3493 MSI->setTemplateSpecializationKind(TSK);
3494 if (TSK != TSK_ExplicitSpecialization &&
3495 PointOfInstantiation.isValid() &&
3496 MSI->getPointOfInstantiation().isInvalid())
3497 MSI->setPointOfInstantiation(PointOfInstantiation);
3498}
3499
Richard Smith4b38ded2012-03-14 23:13:10 +00003500EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3501 if (SpecializationInfo)
3502 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3503
Craig Topper36250ad2014-05-12 05:36:57 +00003504 return nullptr;
Richard Smith4b38ded2012-03-14 23:13:10 +00003505}
3506
3507void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3508 TemplateSpecializationKind TSK) {
3509 assert(!SpecializationInfo && "Member enum is already a specialization");
3510 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3511}
3512
Sebastian Redl833ef452010-01-26 22:01:41 +00003513//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003514// RecordDecl Implementation
3515//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003516
Richard Smith053f6c62014-05-16 23:01:30 +00003517RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3518 DeclContext *DC, SourceLocation StartLoc,
3519 SourceLocation IdLoc, IdentifierInfo *Id,
3520 RecordDecl *PrevDecl)
3521 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003522 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003523 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003524 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00003525 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003526 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00003527 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003528}
3529
Jay Foad39c79802011-01-12 09:06:06 +00003530RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003531 SourceLocation StartLoc, SourceLocation IdLoc,
3532 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smith053f6c62014-05-16 23:01:30 +00003533 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
3534 StartLoc, IdLoc, Id, PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003535 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3536
Ted Kremenek21475702008-09-05 17:16:31 +00003537 C.getTypeDeclType(R, PrevDecl);
3538 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003539}
3540
Douglas Gregor72172e92012-01-05 21:55:30 +00003541RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003542 RecordDecl *R =
3543 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
3544 SourceLocation(), nullptr, nullptr);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003545 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3546 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003547}
3548
Douglas Gregordfcad112009-03-25 15:59:44 +00003549bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003550 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003551 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3552}
3553
Alexey Bataev39c81e22014-08-28 04:28:19 +00003554bool RecordDecl::isLambda() const {
3555 if (auto RD = dyn_cast<CXXRecordDecl>(this))
3556 return RD->isLambda();
3557 return false;
3558}
3559
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003560RecordDecl::field_iterator RecordDecl::field_begin() const {
3561 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3562 LoadFieldsFromExternalStorage();
3563
3564 return field_iterator(decl_iterator(FirstDecl));
3565}
3566
Douglas Gregorb11aad82011-02-19 18:51:44 +00003567/// completeDefinition - Notes that the definition of this type is now
3568/// complete.
3569void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003570 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003571 TagDecl::completeDefinition();
3572}
3573
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003574/// isMsStruct - Get whether or not this record uses ms_struct layout.
3575/// This which can be turned on with an attribute, pragma, or the
3576/// -mms-bitfields command-line option.
3577bool RecordDecl::isMsStruct(const ASTContext &C) const {
3578 return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3579}
3580
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003581static bool isFieldOrIndirectField(Decl::Kind K) {
3582 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3583}
3584
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003585void RecordDecl::LoadFieldsFromExternalStorage() const {
3586 ExternalASTSource *Source = getASTContext().getExternalSource();
3587 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3588
3589 // Notify that we have a RecordDecl doing some initialization.
3590 ExternalASTSource::Deserializing TheFields(Source);
3591
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003592 SmallVector<Decl*, 64> Decls;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003593 LoadedFieldsFromExternalStorage = true;
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003594 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3595 Decls)) {
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003596 case ELR_Success:
3597 break;
3598
3599 case ELR_AlreadyLoaded:
3600 case ELR_Failure:
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003601 return;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003602 }
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003603
3604#ifndef NDEBUG
3605 // Check that all decls we got were FieldDecls.
3606 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003607 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003608#endif
3609
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003610 if (Decls.empty())
3611 return;
3612
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003613 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003614 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003615}
3616
Steve Naroff415d3d52008-10-08 17:01:13 +00003617//===----------------------------------------------------------------------===//
3618// BlockDecl Implementation
3619//===----------------------------------------------------------------------===//
3620
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003621void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00003622 assert(!ParamInfo && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00003623
Steve Naroffc4b30e52009-03-13 16:56:44 +00003624 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003625 if (!NewParamInfo.empty()) {
3626 NumParams = NewParamInfo.size();
3627 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3628 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003629 }
3630}
3631
John McCall351762c2011-02-07 10:33:21 +00003632void BlockDecl::setCaptures(ASTContext &Context,
3633 const Capture *begin,
3634 const Capture *end,
3635 bool capturesCXXThis) {
John McCallc63de662011-02-02 13:00:07 +00003636 CapturesCXXThis = capturesCXXThis;
3637
3638 if (begin == end) {
John McCall351762c2011-02-07 10:33:21 +00003639 NumCaptures = 0;
Craig Topper36250ad2014-05-12 05:36:57 +00003640 Captures = nullptr;
John McCallc63de662011-02-02 13:00:07 +00003641 return;
3642 }
3643
John McCall351762c2011-02-07 10:33:21 +00003644 NumCaptures = end - begin;
3645
3646 // Avoid new Capture[] because we don't want to provide a default
3647 // constructor.
3648 size_t allocationSize = NumCaptures * sizeof(Capture);
3649 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3650 memcpy(buffer, begin, allocationSize);
3651 Captures = static_cast<Capture*>(buffer);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003652}
Sebastian Redl833ef452010-01-26 22:01:41 +00003653
John McCallce45f882011-06-15 22:51:16 +00003654bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00003655 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00003656 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00003657 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00003658 return true;
3659
3660 return false;
3661}
3662
Douglas Gregor70226da2010-12-21 16:27:07 +00003663SourceRange BlockDecl::getSourceRange() const {
3664 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3665}
Sebastian Redl833ef452010-01-26 22:01:41 +00003666
3667//===----------------------------------------------------------------------===//
3668// Other Decl Allocation/Deallocation Method Implementations
3669//===----------------------------------------------------------------------===//
3670
David Blaikie68e081d2011-12-20 02:48:34 +00003671void TranslationUnitDecl::anchor() { }
3672
Sebastian Redl833ef452010-01-26 22:01:41 +00003673TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Craig Topper36250ad2014-05-12 05:36:57 +00003674 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00003675}
3676
David Blaikie68e081d2011-12-20 02:48:34 +00003677void LabelDecl::anchor() { }
3678
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003679LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003680 SourceLocation IdentL, IdentifierInfo *II) {
Craig Topper36250ad2014-05-12 05:36:57 +00003681 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003682}
3683
3684LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3685 SourceLocation IdentL, IdentifierInfo *II,
3686 SourceLocation GnuLabelL) {
3687 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Craig Topper36250ad2014-05-12 05:36:57 +00003688 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003689}
3690
Douglas Gregor72172e92012-01-05 21:55:30 +00003691LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003692 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
3693 SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00003694}
3695
David Blaikie68e081d2011-12-20 02:48:34 +00003696void ValueDecl::anchor() { }
3697
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003698bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00003699 for (const auto *I : attrs())
3700 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003701 return true;
3702
3703 return isWeakImported();
3704}
3705
David Blaikie68e081d2011-12-20 02:48:34 +00003706void ImplicitParamDecl::anchor() { }
3707
Sebastian Redl833ef452010-01-26 22:01:41 +00003708ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003709 SourceLocation IdLoc,
3710 IdentifierInfo *Id,
3711 QualType Type) {
Richard Smith053f6c62014-05-16 23:01:30 +00003712 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00003713}
3714
Richard Smithf7981722013-11-22 09:01:48 +00003715ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00003716 unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003717 return new (C, ID) ImplicitParamDecl(C, nullptr, SourceLocation(), nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00003718 QualType());
Douglas Gregor72172e92012-01-05 21:55:30 +00003719}
3720
Sebastian Redl833ef452010-01-26 22:01:41 +00003721FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003722 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003723 const DeclarationNameInfo &NameInfo,
3724 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003725 StorageClass SC,
Richard Smithf7981722013-11-22 09:01:48 +00003726 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00003727 bool hasWrittenPrototype,
3728 bool isConstexprSpecified) {
Richard Smithf7981722013-11-22 09:01:48 +00003729 FunctionDecl *New =
Richard Smith053f6c62014-05-16 23:01:30 +00003730 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
3731 SC, isInlineSpecified, isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00003732 New->HasWrittenPrototype = hasWrittenPrototype;
3733 return New;
3734}
3735
Douglas Gregor72172e92012-01-05 21:55:30 +00003736FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003737 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00003738 DeclarationNameInfo(), QualType(), nullptr,
Richard Smithf7981722013-11-22 09:01:48 +00003739 SC_None, false, false);
Douglas Gregor72172e92012-01-05 21:55:30 +00003740}
3741
Sebastian Redl833ef452010-01-26 22:01:41 +00003742BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00003743 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00003744}
3745
Douglas Gregor72172e92012-01-05 21:55:30 +00003746BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003747 return new (C, ID) BlockDecl(nullptr, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00003748}
3749
Ben Langmuir37943a72013-05-03 19:00:33 +00003750CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
3751 unsigned NumParams) {
Richard Smithf7981722013-11-22 09:01:48 +00003752 return new (C, DC, NumParams * sizeof(ImplicitParamDecl *))
3753 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003754}
3755
Ben Langmuirce914fc2013-05-03 19:20:19 +00003756CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00003757 unsigned NumParams) {
3758 return new (C, ID, NumParams * sizeof(ImplicitParamDecl *))
Craig Topper36250ad2014-05-12 05:36:57 +00003759 CapturedDecl(nullptr, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00003760}
3761
Sebastian Redl833ef452010-01-26 22:01:41 +00003762EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3763 SourceLocation L,
3764 IdentifierInfo *Id, QualType T,
3765 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00003766 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00003767}
3768
Douglas Gregor72172e92012-01-05 21:55:30 +00003769EnumConstantDecl *
3770EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003771 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
3772 QualType(), nullptr, llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00003773}
3774
David Blaikie68e081d2011-12-20 02:48:34 +00003775void IndirectFieldDecl::anchor() { }
3776
Benjamin Kramer39593702010-11-21 14:11:41 +00003777IndirectFieldDecl *
3778IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3779 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3780 unsigned CHS) {
Richard Smithf7981722013-11-22 09:01:48 +00003781 return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003782}
3783
Douglas Gregor72172e92012-01-05 21:55:30 +00003784IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3785 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003786 return new (C, ID) IndirectFieldDecl(nullptr, SourceLocation(),
3787 DeclarationName(), QualType(), nullptr,
3788 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00003789}
3790
Douglas Gregorbe996932010-09-01 20:41:53 +00003791SourceRange EnumConstantDecl::getSourceRange() const {
3792 SourceLocation End = getLocation();
3793 if (Init)
3794 End = Init->getLocEnd();
3795 return SourceRange(getLocation(), End);
3796}
3797
David Blaikie68e081d2011-12-20 02:48:34 +00003798void TypeDecl::anchor() { }
3799
Sebastian Redl833ef452010-01-26 22:01:41 +00003800TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003801 SourceLocation StartLoc, SourceLocation IdLoc,
3802 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00003803 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00003804}
3805
David Blaikie68e081d2011-12-20 02:48:34 +00003806void TypedefNameDecl::anchor() { }
3807
Douglas Gregor72172e92012-01-05 21:55:30 +00003808TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003809 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00003810 nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00003811}
3812
Richard Smithdda56e42011-04-15 14:24:37 +00003813TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3814 SourceLocation StartLoc,
3815 SourceLocation IdLoc, IdentifierInfo *Id,
3816 TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00003817 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00003818}
3819
Douglas Gregor72172e92012-01-05 21:55:30 +00003820TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003821 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
3822 SourceLocation(), nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00003823}
3824
Abramo Bagnaraea947882011-03-08 16:41:52 +00003825SourceRange TypedefDecl::getSourceRange() const {
3826 SourceLocation RangeEnd = getLocation();
3827 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3828 if (typeIsPostfix(TInfo->getType()))
3829 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3830 }
3831 return SourceRange(getLocStart(), RangeEnd);
3832}
3833
Richard Smithdda56e42011-04-15 14:24:37 +00003834SourceRange TypeAliasDecl::getSourceRange() const {
3835 SourceLocation RangeEnd = getLocStart();
3836 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3837 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3838 return SourceRange(getLocStart(), RangeEnd);
3839}
3840
David Blaikie68e081d2011-12-20 02:48:34 +00003841void FileScopeAsmDecl::anchor() { }
3842
Sebastian Redl833ef452010-01-26 22:01:41 +00003843FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00003844 StringLiteral *Str,
3845 SourceLocation AsmLoc,
3846 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00003847 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00003848}
Douglas Gregorba345522011-12-02 23:23:56 +00003849
Richard Smithf7981722013-11-22 09:01:48 +00003850FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00003851 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003852 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
3853 SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00003854}
3855
Michael Han84324352013-02-22 17:15:32 +00003856void EmptyDecl::anchor() {}
3857
3858EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00003859 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00003860}
3861
3862EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003863 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00003864}
3865
Douglas Gregorba345522011-12-02 23:23:56 +00003866//===----------------------------------------------------------------------===//
3867// ImportDecl Implementation
3868//===----------------------------------------------------------------------===//
3869
3870/// \brief Retrieve the number of module identifiers needed to name the given
3871/// module.
3872static unsigned getNumModuleIdentifiers(Module *Mod) {
3873 unsigned Result = 1;
3874 while (Mod->Parent) {
3875 Mod = Mod->Parent;
3876 ++Result;
3877 }
3878 return Result;
3879}
3880
Douglas Gregor22d09742012-01-03 18:04:46 +00003881ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003882 Module *Imported,
3883 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00003884 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003885 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003886{
3887 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3888 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3889 memcpy(StoredLocs, IdentifierLocs.data(),
3890 IdentifierLocs.size() * sizeof(SourceLocation));
3891}
3892
Douglas Gregor22d09742012-01-03 18:04:46 +00003893ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003894 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00003895 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003896 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003897{
3898 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3899}
3900
Richard Smithf7981722013-11-22 09:01:48 +00003901ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003902 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00003903 ArrayRef<SourceLocation> IdentifierLocs) {
Richard Smithf7981722013-11-22 09:01:48 +00003904 return new (C, DC, IdentifierLocs.size() * sizeof(SourceLocation))
3905 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00003906}
3907
Richard Smithf7981722013-11-22 09:01:48 +00003908ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003909 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00003910 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00003911 SourceLocation EndLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00003912 ImportDecl *Import =
3913 new (C, DC, sizeof(SourceLocation)) ImportDecl(DC, StartLoc,
3914 Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00003915 Import->setImplicit();
3916 return Import;
3917}
3918
Douglas Gregor72172e92012-01-05 21:55:30 +00003919ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3920 unsigned NumLocations) {
Richard Smithf7981722013-11-22 09:01:48 +00003921 return new (C, ID, NumLocations * sizeof(SourceLocation))
3922 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00003923}
3924
3925ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3926 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003927 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00003928
3929 const SourceLocation *StoredLocs
3930 = reinterpret_cast<const SourceLocation *>(this + 1);
Craig Topper5fc8fc22014-08-27 06:28:36 +00003931 return llvm::makeArrayRef(StoredLocs,
3932 getNumModuleIdentifiers(getImportedModule()));
Douglas Gregorba345522011-12-02 23:23:56 +00003933}
3934
3935SourceRange ImportDecl::getSourceRange() const {
3936 if (!ImportedAndComplete.getInt())
3937 return SourceRange(getLocation(),
3938 *reinterpret_cast<const SourceLocation *>(this + 1));
3939
3940 return SourceRange(getLocation(), getIdentifierLocs().back());
3941}