blob: 946d1bae21efb61055205a9629ed43b9f6161931 [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"
Kostya Serebryany293dc9b2014-10-16 20:54:52 +000032#include "clang/Frontend/FrontendDiagnostic.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000033#include "llvm/Support/ErrorHandling.h"
David Blaikie9c70e042011-09-21 18:16:56 +000034#include <algorithm>
35
Chris Lattner6d9a6852006-10-25 05:11:20 +000036using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000037
Richard Smith0b87e072013-10-07 08:02:11 +000038Decl *clang::getPrimaryMergedDecl(Decl *D) {
39 return D->getASTContext().getPrimaryMergedDecl(D);
40}
41
Richard Smith73b21d82014-09-03 02:33:22 +000042// Defined here so that it can be inlined into its direct callers.
43bool Decl::isOutOfLine() const {
44 return !getLexicalDeclContext()->Equals(getDeclContext());
45}
46
Richard Smith42413142015-05-15 20:05:43 +000047TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
48 : Decl(TranslationUnit, nullptr, SourceLocation()),
49 DeclContext(TranslationUnit), Ctx(ctx), AnonymousNamespace(nullptr) {
50 Hidden = Ctx.getLangOpts().ModulesLocalVisibility;
51}
52
Chris Lattner88f70d62008-03-15 05:43:15 +000053//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000054// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000055//===----------------------------------------------------------------------===//
56
John McCalldf25c432013-02-16 00:17:33 +000057// Visibility rules aren't rigorously externally specified, but here
58// are the basic principles behind what we implement:
59//
60// 1. An explicit visibility attribute is generally a direct expression
61// of the user's intent and should be honored. Only the innermost
62// visibility attribute applies. If no visibility attribute applies,
63// global visibility settings are considered.
64//
65// 2. There is one caveat to the above: on or in a template pattern,
66// an explicit visibility attribute is just a default rule, and
67// visibility can be decreased by the visibility of template
68// arguments. But this, too, has an exception: an attribute on an
69// explicit specialization or instantiation causes all the visibility
70// restrictions of the template arguments to be ignored.
71//
72// 3. A variable that does not otherwise have explicit visibility can
73// be restricted by the visibility of its type.
74//
75// 4. A visibility restriction is explicit if it comes from an
76// attribute (or something like it), not a global visibility setting.
77// When emitting a reference to an external symbol, visibility
78// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +000079//
80// 5. When computing the visibility of a non-type, including a
81// non-type member of a class, only non-type visibility restrictions
82// are considered: the 'visibility' attribute, global value-visibility
83// settings, and a few special cases like __private_extern.
84//
85// 6. When computing the visibility of a type, including a type member
86// of a class, only type visibility restrictions are considered:
87// the 'type_visibility' attribute and global type-visibility settings.
88// However, a 'visibility' attribute counts as a 'type_visibility'
89// attribute on any declaration that only has the former.
90//
91// The visibility of a "secondary" entity, like a template argument,
92// is computed using the kind of that entity, not the kind of the
93// primary entity for which we are computing visibility. For example,
94// the visibility of a specialization of either of these templates:
95// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
96// template <class T, bool (&compare)(T, X)> class matcher;
97// is restricted according to the type visibility of the argument 'T',
98// the type visibility of 'bool(&)(T,X)', and the value visibility of
99// the argument function 'compare'. That 'has_match' is a value
100// and 'matcher' is a type only matters when looking for attributes
101// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +0000102
John McCall5f46c482013-02-21 23:42:58 +0000103const unsigned IgnoreExplicitVisibilityBit = 2;
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000104const unsigned IgnoreAllVisibilityBit = 4;
John McCall5f46c482013-02-21 23:42:58 +0000105
John McCalldf25c432013-02-16 00:17:33 +0000106/// Kinds of LV computation. The linkage side of the computation is
107/// always the same, but different things can change how visibility is
108/// computed.
109enum LVComputationKind {
John McCall5f46c482013-02-21 23:42:58 +0000110 /// Do an LV computation for, ultimately, a type.
111 /// Visibility may be restricted by type visibility settings and
112 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000113 LVForType = NamedDecl::VisibilityForType,
John McCalldf25c432013-02-16 00:17:33 +0000114
John McCall5f46c482013-02-21 23:42:58 +0000115 /// Do an LV computation for, ultimately, a non-type declaration.
116 /// Visibility may be restricted by value visibility settings and
117 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000118 LVForValue = NamedDecl::VisibilityForValue,
119
John McCall5f46c482013-02-21 23:42:58 +0000120 /// Do an LV computation for, ultimately, a type that already has
121 /// some sort of explicit visibility. Visibility may only be
122 /// restricted by the visibility of template arguments.
123 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
John McCalld041a9b2013-02-20 01:54:26 +0000124
John McCall5f46c482013-02-21 23:42:58 +0000125 /// Do an LV computation for, ultimately, a non-type declaration
126 /// that already has some sort of explicit visibility. Visibility
127 /// may only be restricted by the visibility of template arguments.
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000128 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
129
130 /// Do an LV computation when we only care about the linkage.
131 LVForLinkageOnly =
132 LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
John McCalldf25c432013-02-16 00:17:33 +0000133};
134
John McCalld041a9b2013-02-20 01:54:26 +0000135/// Does this computation kind permit us to consider additional
136/// visibility settings from attributes and the like?
137static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000138 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
John McCalld041a9b2013-02-20 01:54:26 +0000139}
140
141/// Given an LVComputationKind, return one of the same type/value sort
142/// that records that it already has explicit visibility.
143static LVComputationKind
144withExplicitVisibilityAlready(LVComputationKind oldKind) {
145 LVComputationKind newKind =
John McCall5f46c482013-02-21 23:42:58 +0000146 static_cast<LVComputationKind>(unsigned(oldKind) |
147 IgnoreExplicitVisibilityBit);
John McCalld041a9b2013-02-20 01:54:26 +0000148 assert(oldKind != LVForType || newKind == LVForExplicitType);
149 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
150 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
151 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
152 return newKind;
153}
154
David Blaikie05785d12013-02-20 22:23:23 +0000155static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
156 LVComputationKind kind) {
John McCalld041a9b2013-02-20 01:54:26 +0000157 assert(!hasExplicitVisibilityAlready(kind) &&
158 "asking for explicit visibility when we shouldn't be");
159 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
160}
161
John McCalldf25c432013-02-16 00:17:33 +0000162/// Is the given declaration a "type" or a "value" for the purposes of
163/// visibility computation?
164static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000165 return isa<TypeDecl>(D) ||
166 isa<ClassTemplateDecl>(D) ||
167 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000168}
169
John McCall5f46c482013-02-21 23:42:58 +0000170/// Does the given declaration have member specialization information,
171/// and if so, is it an explicit specialization?
172template <class T> static typename
Benjamin Kramered2f4762014-03-07 14:30:23 +0000173std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-02-21 23:42:58 +0000174isExplicitMemberSpecialization(const T *D) {
175 if (const MemberSpecializationInfo *member =
176 D->getMemberSpecializationInfo()) {
177 return member->isExplicitSpecialization();
178 }
179 return false;
180}
181
182/// For templates, this question is easier: a member template can't be
183/// explicitly instantiated, so there's a single bit indicating whether
184/// or not this is an explicit member specialization.
185static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
186 return D->isMemberSpecialization();
187}
188
John McCalld041a9b2013-02-20 01:54:26 +0000189/// Given a visibility attribute, return the explicit visibility
190/// associated with it.
191template <class T>
192static Visibility getVisibilityFromAttr(const T *attr) {
193 switch (attr->getVisibility()) {
194 case T::Default:
195 return DefaultVisibility;
196 case T::Hidden:
197 return HiddenVisibility;
198 case T::Protected:
199 return ProtectedVisibility;
200 }
201 llvm_unreachable("bad visibility kind");
202}
203
John McCalldf25c432013-02-16 00:17:33 +0000204/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000205static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000206 NamedDecl::ExplicitVisibilityKind kind) {
207 // If we're ultimately computing the visibility of a type, look for
208 // a 'type_visibility' attribute before looking for 'visibility'.
209 if (kind == NamedDecl::VisibilityForType) {
210 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
211 return getVisibilityFromAttr(A);
212 }
213 }
214
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000215 // If this declaration has an explicit visibility attribute, use it.
216 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000217 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000218 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000219
220 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
221 // implies visibility(default).
Douglas Gregore8bbc122011-09-02 00:18:52 +0000222 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000223 for (const auto *A : D->specific_attrs<AvailabilityAttr>())
224 if (A->getPlatform()->getName().equals("macosx"))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000225 return DefaultVisibility;
226 }
227
David Blaikie7a30dc52013-02-21 01:47:18 +0000228 return None;
John McCall457a04e2010-10-22 21:05:15 +0000229}
230
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000231static LinkageInfo
232getLVForType(const Type &T, LVComputationKind computation) {
233 if (computation == LVForLinkageOnly)
234 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
235 return T.getLinkageAndVisibility();
236}
237
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000238/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000239/// template parameter list. For visibility purposes, template
240/// parameters are part of the signature of a template.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000241static LinkageInfo
David Majnemerc7b85c42014-04-23 05:16:48 +0000242getLVForTemplateParameterList(const TemplateParameterList *Params,
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000243 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000244 LinkageInfo LV;
David Majnemerc7b85c42014-04-23 05:16:48 +0000245 for (const NamedDecl *P : *Params) {
John McCalldf25c432013-02-16 00:17:33 +0000246 // Template type parameters are the most common and never
247 // contribute to visibility, pack or not.
David Majnemerc7b85c42014-04-23 05:16:48 +0000248 if (isa<TemplateTypeParmDecl>(P))
John McCalldf25c432013-02-16 00:17:33 +0000249 continue;
250
251 // Non-type template parameters can be restricted by the value type, e.g.
252 // template <enum X> class A { ... };
253 // We have to be careful here, though, because we can be dealing with
254 // dependent types.
David Majnemerc7b85c42014-04-23 05:16:48 +0000255 if (const NonTypeTemplateParmDecl *NTTP =
256 dyn_cast<NonTypeTemplateParmDecl>(P)) {
John McCalldf25c432013-02-16 00:17:33 +0000257 // Handle the non-pack case first.
258 if (!NTTP->isExpandedParameterPack()) {
259 if (!NTTP->getType()->isDependentType()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000260 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000261 }
262 continue;
263 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000264
John McCalldf25c432013-02-16 00:17:33 +0000265 // Look at all the types in an expanded pack.
266 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
267 QualType type = NTTP->getExpansionType(i);
268 if (!type->isDependentType())
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000269 LV.merge(type->getLinkageAndVisibility());
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000270 }
John McCalldf25c432013-02-16 00:17:33 +0000271 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000272 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000273
John McCalldf25c432013-02-16 00:17:33 +0000274 // Template template parameters can be restricted by their
275 // template parameters, recursively.
David Majnemerc7b85c42014-04-23 05:16:48 +0000276 const TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(P);
John McCalldf25c432013-02-16 00:17:33 +0000277
278 // Handle the non-pack case first.
279 if (!TTP->isExpandedParameterPack()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000280 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
281 computation));
John McCalldf25c432013-02-16 00:17:33 +0000282 continue;
283 }
284
285 // Look at all expansions in an expanded pack.
286 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
287 i != n; ++i) {
288 LV.merge(getLVForTemplateParameterList(
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000289 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000290 }
291 }
292
John McCall457a04e2010-10-22 21:05:15 +0000293 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000294}
295
Rafael Espindola19de5612013-01-12 06:42:30 +0000296/// getLVForDecl - Get the linkage and visibility for the given declaration.
John McCalldf25c432013-02-16 00:17:33 +0000297static LinkageInfo getLVForDecl(const NamedDecl *D,
298 LVComputationKind computation);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000299
Eli Friedman7e346a82013-07-01 20:22:57 +0000300static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
Craig Topper36250ad2014-05-12 05:36:57 +0000301 const Decl *Ret = nullptr;
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000302 const DeclContext *DC = D->getDeclContext();
303 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman7e346a82013-07-01 20:22:57 +0000304 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
305 Ret = cast<Decl>(DC);
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000306 DC = DC->getParent();
307 }
308 return Ret;
309}
310
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000311/// \brief Get the most restrictive linkage for the types and
312/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000313///
314/// Note that we don't take an LVComputationKind because we always
315/// want to honor the visibility of template arguments in the same way.
David Majnemerc7b85c42014-04-23 05:16:48 +0000316static LinkageInfo getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
317 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000318 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000319
David Majnemerc7b85c42014-04-23 05:16:48 +0000320 for (const TemplateArgument &Arg : Args) {
321 switch (Arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000322 case TemplateArgument::Null:
323 case TemplateArgument::Integral:
324 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000325 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000326
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000327 case TemplateArgument::Type:
David Majnemerc7b85c42014-04-23 05:16:48 +0000328 LV.merge(getLVForType(*Arg.getAsType(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000329 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000330
331 case TemplateArgument::Declaration:
David Majnemerc7b85c42014-04-23 05:16:48 +0000332 if (NamedDecl *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
John McCalldf25c432013-02-16 00:17:33 +0000333 assert(!usesTypeVisibility(ND));
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000334 LV.merge(getLVForDecl(ND, computation));
John McCalldf25c432013-02-16 00:17:33 +0000335 }
336 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +0000337
338 case TemplateArgument::NullPtr:
David Majnemerc7b85c42014-04-23 05:16:48 +0000339 LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility());
John McCalldf25c432013-02-16 00:17:33 +0000340 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000341
342 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000343 case TemplateArgument::TemplateExpansion:
David Majnemerc7b85c42014-04-23 05:16:48 +0000344 if (TemplateDecl *Template =
345 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000346 LV.merge(getLVForDecl(Template, computation));
John McCalldf25c432013-02-16 00:17:33 +0000347 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000348
349 case TemplateArgument::Pack:
David Majnemerc7b85c42014-04-23 05:16:48 +0000350 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000351 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000352 }
John McCalldf25c432013-02-16 00:17:33 +0000353 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000354 }
355
John McCall457a04e2010-10-22 21:05:15 +0000356 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000357}
358
Rafael Espindola2f869a32012-01-14 00:30:36 +0000359static LinkageInfo
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000360getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
361 LVComputationKind computation) {
362 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall8823c652010-08-13 08:35:10 +0000363}
364
John McCall5f46c482013-02-21 23:42:58 +0000365static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
366 const FunctionTemplateSpecializationInfo *specInfo) {
367 // Include visibility from the template parameters and arguments
368 // only if this is not an explicit instantiation or specialization
369 // with direct explicit visibility. (Implicit instantiations won't
370 // have a direct attribute.)
371 if (!specInfo->isExplicitInstantiationOrSpecialization())
372 return true;
373
374 return !fn->hasAttr<VisibilityAttr>();
375}
376
John McCalldf25c432013-02-16 00:17:33 +0000377/// Merge in template-related linkage and visibility for the given
378/// function template specialization.
379///
380/// We don't need a computation kind here because we can assume
381/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000382///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000383/// \param[out] LV the computation to use for the parent
John McCall5f46c482013-02-21 23:42:58 +0000384static void
385mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000386 const FunctionTemplateSpecializationInfo *specInfo,
387 LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000388 bool considerVisibility =
389 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000390
391 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000392 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000393 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000394 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000395 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
396
397 // Merge information from the template arguments.
398 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000399 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCalldf25c432013-02-16 00:17:33 +0000400 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000401}
402
John McCall5f46c482013-02-21 23:42:58 +0000403/// Does the given declaration have a direct visibility attribute
404/// that would match the given rules?
405static bool hasDirectVisibilityAttribute(const NamedDecl *D,
406 LVComputationKind computation) {
407 switch (computation) {
408 case LVForType:
409 case LVForExplicitType:
410 if (D->hasAttr<TypeVisibilityAttr>())
411 return true;
412 // fallthrough
413 case LVForValue:
414 case LVForExplicitValue:
415 if (D->hasAttr<VisibilityAttr>())
416 return true;
417 return false;
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000418 case LVForLinkageOnly:
419 return false;
John McCall5f46c482013-02-21 23:42:58 +0000420 }
421 llvm_unreachable("bad visibility computation kind");
422}
423
John McCalld041a9b2013-02-20 01:54:26 +0000424/// Should we consider visibility associated with the template
425/// arguments and parameters of the given class template specialization?
426static bool shouldConsiderTemplateVisibility(
427 const ClassTemplateSpecializationDecl *spec,
428 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000429 // Include visibility from the template parameters and arguments
430 // only if this is not an explicit instantiation or specialization
431 // with direct explicit visibility (and note that implicit
432 // instantiations won't have a direct attribute).
433 //
434 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000435 // for an explicit specialization when computing the visibility of a
436 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000437 //
438 // This is a bit complex; let's unpack it.
439 //
440 // An explicit class specialization is an independent, top-level
441 // declaration. As such, if it or any of its members has an
442 // explicit visibility attribute, that must directly express the
443 // user's intent, and we should honor it. The same logic applies to
444 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000445
446 // Fast path: if this is not an explicit instantiation or
447 // specialization, we always want to consider template-related
448 // visibility restrictions.
449 if (!spec->isExplicitInstantiationOrSpecialization())
450 return true;
451
452 // This is the 'member thereof' check.
453 if (spec->isExplicitSpecialization() &&
454 hasExplicitVisibilityAlready(computation))
455 return false;
456
John McCall5f46c482013-02-21 23:42:58 +0000457 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000458}
459
460/// Merge in template-related linkage and visibility for the given
461/// class template specialization.
462static void mergeTemplateLV(LinkageInfo &LV,
463 const ClassTemplateSpecializationDecl *spec,
464 LVComputationKind computation) {
465 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000466
467 // Merge information from the template parameters, but ignore
468 // visibility if we're only considering template arguments.
469
John McCalld041a9b2013-02-20 01:54:26 +0000470 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000471 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000472 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000473 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000474 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000475
476 // Merge information from the template arguments. We ignore
477 // template-argument visibility if we've got an explicit
478 // instantiation with a visibility attribute.
479 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000480 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000481 if (considerVisibility)
482 LV.mergeVisibility(argsLV);
483 LV.mergeExternalVisibility(argsLV);
John McCallb8c604a2011-06-27 23:06:04 +0000484}
485
Larisse Voufo5899e192014-07-02 23:08:34 +0000486/// Should we consider visibility associated with the template
487/// arguments and parameters of the given variable template
488/// specialization? As usual, follow class template specialization
489/// logic up to initialization.
490static bool shouldConsiderTemplateVisibility(
491 const VarTemplateSpecializationDecl *spec,
492 LVComputationKind computation) {
493 // Include visibility from the template parameters and arguments
494 // only if this is not an explicit instantiation or specialization
495 // with direct explicit visibility (and note that implicit
496 // instantiations won't have a direct attribute).
497 if (!spec->isExplicitInstantiationOrSpecialization())
498 return true;
499
500 // An explicit variable specialization is an independent, top-level
501 // declaration. As such, if it has an explicit visibility attribute,
502 // that must directly express the user's intent, and we should honor
503 // it.
504 if (spec->isExplicitSpecialization() &&
505 hasExplicitVisibilityAlready(computation))
506 return false;
507
508 return !hasDirectVisibilityAttribute(spec, computation);
509}
510
511/// Merge in template-related linkage and visibility for the given
512/// variable template specialization. As usual, follow class template
513/// specialization logic up to initialization.
514static void mergeTemplateLV(LinkageInfo &LV,
515 const VarTemplateSpecializationDecl *spec,
516 LVComputationKind computation) {
517 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
518
519 // Merge information from the template parameters, but ignore
520 // visibility if we're only considering template arguments.
521
522 VarTemplateDecl *temp = spec->getSpecializedTemplate();
523 LinkageInfo tempLV =
524 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
525 LV.mergeMaybeWithVisibility(tempLV,
526 considerVisibility && !hasExplicitVisibilityAlready(computation));
527
528 // Merge information from the template arguments. We ignore
529 // template-argument visibility if we've got an explicit
530 // instantiation with a visibility attribute.
531 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
532 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
533 if (considerVisibility)
534 LV.mergeVisibility(argsLV);
535 LV.mergeExternalVisibility(argsLV);
536}
537
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000538static bool useInlineVisibilityHidden(const NamedDecl *D) {
539 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000540 const LangOptions &Opts = D->getASTContext().getLangOpts();
541 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000542 return false;
543
544 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
545 if (!FD)
546 return false;
547
548 TemplateSpecializationKind TSK = TSK_Undeclared;
549 if (FunctionTemplateSpecializationInfo *spec
550 = FD->getTemplateSpecializationInfo()) {
551 TSK = spec->getTemplateSpecializationKind();
552 } else if (MemberSpecializationInfo *MSI =
553 FD->getMemberSpecializationInfo()) {
554 TSK = MSI->getTemplateSpecializationKind();
555 }
556
Craig Topper36250ad2014-05-12 05:36:57 +0000557 const FunctionDecl *Def = nullptr;
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000558 // InlineVisibilityHidden only applies to definitions, and
559 // isInlined() only gives meaningful answers on definitions
560 // anyway.
561 return TSK != TSK_ExplicitInstantiationDeclaration &&
562 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000563 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000564}
565
Rafael Espindola593537a2013-05-05 20:15:21 +0000566template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000567 const T *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +0000568 return First->isInExternCContext();
Rafael Espindolaf4187652013-02-14 01:18:37 +0000569}
570
Richard Smith03c05032014-02-17 23:34:47 +0000571static bool isSingleLineLanguageLinkage(const Decl &D) {
Rafael Espindola327be3c2013-04-26 01:30:23 +0000572 if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Richard Smith03c05032014-02-17 23:34:47 +0000573 if (!SD->hasBraces())
Rafael Espindola327be3c2013-04-26 01:30:23 +0000574 return true;
575 return false;
576}
577
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000578static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
John McCalldf25c432013-02-16 00:17:33 +0000579 LVComputationKind computation) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000580 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000581 "Not a name having namespace scope");
582 ASTContext &Context = D->getASTContext();
583
584 // C++ [basic.link]p3:
585 // A name having namespace scope (3.3.6) has internal linkage if it
586 // is the name of
587 // - an object, reference, function or function template that is
588 // explicitly declared static; or,
589 // (This bullet corresponds to C99 6.2.2p3.)
590 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
591 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000592 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000593 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000594
Richard Smithdc0ef452012-10-19 06:37:48 +0000595 // - a non-volatile object or reference that is explicitly declared const
596 // or constexpr and neither explicitly declared extern nor previously
597 // declared to have external linkage; or (there is no equivalent in C99)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000598 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000599 Var->getType().isConstQualified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000600 !Var->getType().isVolatileQualified()) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000601 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000602 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000603 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000604
605 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000606 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000607 !isSingleLineLanguageLinkage(*Var))
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000608 return LinkageInfo::internal();
609 }
610
611 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
612 PrevVar = PrevVar->getPreviousDecl()) {
613 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
614 Var->getStorageClass() == SC_None)
615 return PrevVar->getLinkageAndVisibility();
616 // Explicitly declared static.
617 if (PrevVar->getStorageClass() == SC_Static)
618 return LinkageInfo::internal();
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000619 }
Alp Tokera2794f92014-01-22 07:29:52 +0000620 } else if (const FunctionDecl *Function = D->getAsFunction()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000621 // C++ [temp]p4:
622 // A non-member function template can have internal linkage; any
623 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000624
625 // Explicitly declared static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000626 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000627 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
David Majnemer18fac3b2014-12-10 22:58:14 +0000628 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
629 // - a data member of an anonymous union.
630 const VarDecl *VD = IFD->getVarDecl();
631 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
632 return getLVForNamespaceScopeDecl(VD, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000633 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000634 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000635
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000636 if (D->isInAnonymousNamespace()) {
637 const VarDecl *Var = dyn_cast<VarDecl>(D);
638 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
Rafael Espindola593537a2013-05-05 20:15:21 +0000639 if ((!Var || !isFirstInExternCContext(Var)) &&
640 (!Func || !isFirstInExternCContext(Func)))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000641 return LinkageInfo::uniqueExternal();
642 }
John McCallb7139c42010-10-28 04:18:25 +0000643
John McCall457a04e2010-10-22 21:05:15 +0000644 // Set up the defaults.
645
646 // C99 6.2.2p5:
647 // If the declaration of an identifier for an object has file
648 // scope and no storage-class specifier, its linkage is
649 // external.
John McCallc273f242010-10-30 11:50:40 +0000650 LinkageInfo LV;
651
John McCalld041a9b2013-02-20 01:54:26 +0000652 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000653 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000654 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000655 } else {
656 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000657 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000658 for (const DeclContext *DC = D->getDeclContext();
659 !isa<TranslationUnitDecl>(DC);
660 DC = DC->getParent()) {
661 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
662 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000663 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000664 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000665 break;
666 }
667 }
668 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000669
John McCalldf25c432013-02-16 00:17:33 +0000670 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000671 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000672 // Use global type/value visibility as appropriate.
673 Visibility globalVisibility;
674 if (computation == LVForValue) {
Larisse Voufo404e1422015-02-04 02:34:32 +0000675 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
John McCallb4a99d32013-02-19 01:57:35 +0000676 } else {
677 assert(computation == LVForType);
678 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
679 }
680 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000681
682 // If we're paying attention to global visibility, apply
683 // -finline-visibility-hidden if this is an inline method.
684 if (useInlineVisibilityHidden(D))
685 LV.mergeVisibility(HiddenVisibility, true);
686 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000687 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000688
Douglas Gregorf73b2822009-11-25 22:24:25 +0000689 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000690
Douglas Gregorf73b2822009-11-25 22:24:25 +0000691 // A name having namespace scope has external linkage if it is the
692 // name of
693 //
694 // - an object or reference, unless it has internal linkage; or
695 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000696 // GCC applies the following optimization to variables and static
697 // data members, but not to functions:
698 //
John McCall457a04e2010-10-22 21:05:15 +0000699 // Modify the variable's LV by the LV of its type unless this is
700 // C or extern "C". This follows from [basic.link]p9:
701 // A type without linkage shall not be used as the type of a
702 // variable or function with external linkage unless
703 // - the entity has C language linkage, or
704 // - the entity is declared within an unnamed namespace, or
705 // - the entity is not used or is defined in the same
706 // translation unit.
707 // and [basic.link]p10:
708 // ...the types specified by all declarations referring to a
709 // given variable or function shall be identical...
710 // C does not have an equivalent rule.
711 //
John McCall5fe84122010-10-26 04:59:26 +0000712 // Ignore this if we've got an explicit attribute; the user
713 // probably knows what they're doing.
714 //
John McCall457a04e2010-10-22 21:05:15 +0000715 // Note that we don't want to make the variable non-external
716 // because of this, but unique-external linkage suits us.
Rafael Espindola593537a2013-05-05 20:15:21 +0000717 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000718 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Rafael Espindola4a5da442013-02-27 02:56:45 +0000719 if (TypeLV.getLinkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000720 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000721 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000722 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000723 }
724
John McCall23032652010-11-02 18:38:13 +0000725 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000726 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000727
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000728 // Note that Sema::MergeVarDecl already takes care of implementing
729 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
730 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000731
Larisse Voufo5899e192014-07-02 23:08:34 +0000732 // As per function and class template specializations (below),
733 // consider LV for the template and template arguments. We're at file
734 // scope, so we do not need to worry about nested specializations.
735 if (const VarTemplateSpecializationDecl *spec
736 = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
737 mergeTemplateLV(LV, spec, computation);
738 }
739
Douglas Gregorf73b2822009-11-25 22:24:25 +0000740 // - a function, unless it has internal linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000741 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000742 // In theory, we can modify the function's LV by the LV of its
743 // type unless it has C linkage (see comment above about variables
744 // for justification). In practice, GCC doesn't do this, so it's
745 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000746
John McCall23032652010-11-02 18:38:13 +0000747 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000748 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000749
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000750 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
751 // merging storage classes and visibility attributes, so we don't have to
752 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000753
John McCallf768aa72011-02-10 06:50:24 +0000754 // In C++, then if the type of the function uses a type with
755 // unique-external linkage, it's not legally usable from outside
756 // this translation unit. However, we should use the C linkage
757 // rules instead for extern "C" declarations.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000758 if (Context.getLangOpts().CPlusPlus &&
Richard Smith50f4afc2013-05-12 23:17:59 +0000759 !Function->isInExternCContext()) {
760 // Only look at the type-as-written. If this function has an auto-deduced
761 // return type, we can't compute the linkage of that type because it could
762 // require looking at the linkage of this function, and we don't need this
763 // for correctness because the type is not part of the function's
764 // signature.
Faisal Valid2598e92013-10-08 04:15:04 +0000765 // FIXME: This is a hack. We should be able to solve this circularity and
766 // the one in getLVForClassMember for Functions some other way.
Richard Smith50f4afc2013-05-12 23:17:59 +0000767 QualType TypeAsWritten = Function->getType();
768 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
769 TypeAsWritten = TSI->getType();
770 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
771 return LinkageInfo::uniqueExternal();
772 }
John McCallf768aa72011-02-10 06:50:24 +0000773
John McCall5f46c482013-02-21 23:42:58 +0000774 // Consider LV from the template and the template arguments.
775 // We're at file scope, so we do not need to worry about nested
776 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000777 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000778 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000779 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000780 }
781
Douglas Gregorf73b2822009-11-25 22:24:25 +0000782 // - a named class (Clause 9), or an unnamed class defined in a
783 // typedef declaration in which the class has the typedef name
784 // for linkage purposes (7.1.3); or
785 // - a named enumeration (7.2), or an unnamed enumeration
786 // defined in a typedef declaration in which the enumeration
787 // has the typedef name for linkage purposes (7.1.3); or
John McCall457a04e2010-10-22 21:05:15 +0000788 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
789 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000790 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000791 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000792
John McCall457a04e2010-10-22 21:05:15 +0000793 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000794 // linkage of the template and template arguments. We're at file
795 // scope, so we do not need to worry about nested specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000796 if (const ClassTemplateSpecializationDecl *spec
John McCall457a04e2010-10-22 21:05:15 +0000797 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000798 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000799 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000800
801 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000802 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000803 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000804 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000805 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000806 return LinkageInfo::none();
807 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000808
809 // - a template, unless it is a function template that has
810 // internal linkage (Clause 14);
John McCall8bc6d5b2011-03-04 10:39:25 +0000811 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000812 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000813 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000814 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000815 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
816
Douglas Gregorf73b2822009-11-25 22:24:25 +0000817 // - a namespace (7.3), unless it is declared within an unnamed
818 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000819 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
820 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000821
John McCall457a04e2010-10-22 21:05:15 +0000822 // By extension, we assign external linkage to Objective-C
823 // interfaces.
824 } else if (isa<ObjCInterfaceDecl>(D)) {
825 // fallout
826
827 // Everything not covered here has no linkage.
828 } else {
Richard Smith2516ba22014-08-11 18:35:44 +0000829 // FIXME: A typedef declaration has linkage if it gives a type a name for
830 // linkage purposes.
John McCallc273f242010-10-30 11:50:40 +0000831 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000832 }
833
834 // If we ended up with non-external linkage, visibility should
835 // always be default.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000836 if (LV.getLinkage() != ExternalLinkage)
837 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000838
John McCall457a04e2010-10-22 21:05:15 +0000839 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000840}
841
John McCalldf25c432013-02-16 00:17:33 +0000842static LinkageInfo getLVForClassMember(const NamedDecl *D,
843 LVComputationKind computation) {
John McCall457a04e2010-10-22 21:05:15 +0000844 // Only certain class members have linkage. Note that fields don't
845 // really have linkage, but it's convenient to say they do for the
846 // purposes of calculating linkage of pointer-to-data-member
847 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000848 //
849 // Templates also don't officially have linkage, but since we ignore
850 // the C++ standard and look at template arguments when determining
851 // linkage and visibility of a template specialization, we might hit
852 // a template template argument that way. If we do, we need to
853 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000854 if (!(isa<CXXMethodDecl>(D) ||
855 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000856 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000857 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000858 isa<TagDecl>(D) ||
859 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000860 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000861
John McCall07072662010-11-02 01:45:15 +0000862 LinkageInfo LV;
863
John McCall07072662010-11-02 01:45:15 +0000864 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000865 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000866 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000867 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000868 // If we're paying attention to global visibility, apply
869 // -finline-visibility-hidden if this is an inline method.
870 //
871 // Note that we do this before merging information about
872 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000873 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000874 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000875 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000876
877 // If this class member has an explicit visibility attribute, the only
878 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000879 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000880 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000881 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000882 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000883
John McCall5f46c482013-02-21 23:42:58 +0000884 LinkageInfo classLV =
885 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
John McCall8823c652010-08-13 08:35:10 +0000886 // If the class already has unique-external linkage, we can't improve.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000887 if (classLV.getLinkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000888 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000889
Rafael Espindolae6190db2013-05-28 02:22:10 +0000890 if (!isExternallyVisible(classLV.getLinkage()))
891 return LinkageInfo::none();
892
893
John McCall5f46c482013-02-21 23:42:58 +0000894 // Otherwise, don't merge in classLV yet, because in certain cases
895 // we need to completely ignore the visibility from it.
896
897 // Specifically, if this decl exists and has an explicit attribute.
Craig Topper36250ad2014-05-12 05:36:57 +0000898 const NamedDecl *explicitSpecSuppressor = nullptr;
John McCall5f46c482013-02-21 23:42:58 +0000899
John McCall8823c652010-08-13 08:35:10 +0000900 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000901 // If the type of the function uses a type with unique-external
902 // linkage, it's not legally usable from outside this translation unit.
Nico Weber38267342015-04-22 03:44:51 +0000903 // But only look at the type-as-written. If this function has an
904 // auto-deduced return type, we can't compute the linkage of that type
905 // because it could require looking at the linkage of this function, and we
906 // don't need this for correctness because the type is not part of the
907 // function's signature.
908 // FIXME: This is a hack. We should be able to solve this circularity and
909 // the one in getLVForNamespaceScopeDecl for Functions some other way.
Faisal Valid2598e92013-10-08 04:15:04 +0000910 {
911 QualType TypeAsWritten = MD->getType();
912 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
913 TypeAsWritten = TSI->getType();
914 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
915 return LinkageInfo::uniqueExternal();
916 }
John McCall457a04e2010-10-22 21:05:15 +0000917 // If this is a method template specialization, use the linkage for
918 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000919 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000920 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000921 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000922 if (spec->isExplicitSpecialization()) {
923 explicitSpecSuppressor = MD;
924 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
925 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
926 }
927 } else if (isExplicitMemberSpecialization(MD)) {
928 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000929 }
John McCall457a04e2010-10-22 21:05:15 +0000930
John McCall37bb6c92010-10-29 22:22:43 +0000931 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCallb8c604a2011-06-27 23:06:04 +0000932 if (const ClassTemplateSpecializationDecl *spec
John McCall37bb6c92010-10-29 22:22:43 +0000933 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000934 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000935 if (spec->isExplicitSpecialization()) {
936 explicitSpecSuppressor = spec;
937 } else {
938 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
939 if (isExplicitMemberSpecialization(temp)) {
940 explicitSpecSuppressor = temp->getTemplatedDecl();
941 }
942 }
943 } else if (isExplicitMemberSpecialization(RD)) {
944 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000945 }
946
John McCall37bb6c92010-10-29 22:22:43 +0000947 // Static data members.
948 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000949 if (const VarTemplateSpecializationDecl *spec
950 = dyn_cast<VarTemplateSpecializationDecl>(VD))
951 mergeTemplateLV(LV, spec, computation);
952
John McCall36cd5cc2010-10-30 09:18:49 +0000953 // Modify the variable's linkage by its type, but ignore the
954 // type's visibility unless it's a definition.
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000955 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000956 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
957 LV.mergeVisibility(typeLV);
958 LV.mergeExternalVisibility(typeLV);
John McCall5f46c482013-02-21 23:42:58 +0000959
960 if (isExplicitMemberSpecialization(VD)) {
961 explicitSpecSuppressor = VD;
962 }
John McCalldf25c432013-02-16 00:17:33 +0000963
964 // Template members.
965 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
966 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +0000967 (!LV.isVisibilityExplicit() &&
968 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000969 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000970 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000971 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000972 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +0000973
974 if (const RedeclarableTemplateDecl *redeclTemp =
975 dyn_cast<RedeclarableTemplateDecl>(temp)) {
976 if (isExplicitMemberSpecialization(redeclTemp)) {
977 explicitSpecSuppressor = temp->getTemplatedDecl();
978 }
979 }
John McCall37bb6c92010-10-29 22:22:43 +0000980 }
981
John McCall5f46c482013-02-21 23:42:58 +0000982 // We should never be looking for an attribute directly on a template.
983 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
984
985 // If this member is an explicit member specialization, and it has
986 // an explicit attribute, ignore visibility from the parent.
987 bool considerClassVisibility = true;
988 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +0000989 // optimization: hasDVA() is true only with explicit visibility.
990 LV.isVisibilityExplicit() &&
991 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +0000992 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
993 considerClassVisibility = false;
994 }
995
996 // Finally, merge in information from the class.
997 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +0000998 return LV;
John McCall8823c652010-08-13 08:35:10 +0000999}
1000
David Blaikie68e081d2011-12-20 02:48:34 +00001001void NamedDecl::anchor() { }
1002
Rafael Espindolaecf63c62013-05-29 04:55:30 +00001003static LinkageInfo computeLVForDecl(const NamedDecl *D,
1004 LVComputationKind computation);
1005
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001006bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001007 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001008 return true;
John McCalld396b972011-02-08 19:01:05 +00001009
Rafael Espindolaecf63c62013-05-29 04:55:30 +00001010 return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
Rafael Espindola50df3a02013-05-25 17:16:20 +00001011 getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +00001012}
1013
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001014ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1015 StringRef name = getName();
1016 if (name.empty()) return SFF_None;
1017
1018 if (name.front() == 'C')
1019 if (name == "CFStringCreateWithFormat" ||
1020 name == "CFStringCreateWithFormatAndArguments" ||
1021 name == "CFStringAppendFormat" ||
1022 name == "CFStringAppendFormatAndArguments")
1023 return SFF_CFString;
1024 return SFF_None;
1025}
1026
Rafael Espindola3ae00052013-05-13 00:12:11 +00001027Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +00001028 // We don't care about visibility here, so ask for the cheapest
1029 // possible visibility analysis.
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001030 return getLVForDecl(this, LVForLinkageOnly).getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001031}
1032
John McCallc273f242010-10-30 11:50:40 +00001033LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCalldf25c432013-02-16 00:17:33 +00001034 LVComputationKind computation =
1035 (usesTypeVisibility(this) ? LVForType : LVForValue);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001036 return getLVForDecl(this, computation);
John McCall033caa52010-10-29 00:29:13 +00001037}
Ted Kremenek926d8602010-04-20 23:15:35 +00001038
Rafael Espindola9ad61122013-11-26 16:09:08 +00001039static Optional<Visibility>
1040getExplicitVisibilityAux(const NamedDecl *ND,
1041 NamedDecl::ExplicitVisibilityKind kind,
1042 bool IsMostRecent) {
1043 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1044
Rafael Espindola3a52c442013-02-26 19:33:14 +00001045 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001046 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001047 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001048
Rafael Espindola3a52c442013-02-26 19:33:14 +00001049 // If this is a member class of a specialization of a class template
1050 // and the corresponding decl has explicit visibility, use that.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001051 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +00001052 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1053 if (InstantiatedFrom)
1054 return getVisibilityOf(InstantiatedFrom, kind);
1055 }
1056
1057 // If there wasn't explicit visibility there, and this is a
1058 // specialization of a class template, check for visibility
1059 // on the pattern.
1060 if (const ClassTemplateSpecializationDecl *spec
Rafael Espindola9ad61122013-11-26 16:09:08 +00001061 = dyn_cast<ClassTemplateSpecializationDecl>(ND))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001062 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1063 kind);
1064
1065 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +00001066 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +00001067 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1068 if (MostRecent != ND)
1069 return getExplicitVisibilityAux(MostRecent, kind, true);
1070 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001071
Rafael Espindola9ad61122013-11-26 16:09:08 +00001072 if (const VarDecl *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +00001073 if (Var->isStaticDataMember()) {
1074 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1075 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001076 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +00001077 }
1078
David Majnemer35b02bc2014-04-29 07:32:26 +00001079 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1080 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1081 kind);
1082
David Blaikie7a30dc52013-02-21 01:47:18 +00001083 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +00001084 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001085 // Also handle function template specializations.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001086 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001087 // If the function is a specialization of a template with an
1088 // explicit visibility attribute, use that.
1089 if (FunctionTemplateSpecializationInfo *templateInfo
1090 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +00001091 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1092 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001093
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001094 // If the function is a member of a specialization of a class template
1095 // and the corresponding decl has explicit visibility, use that.
1096 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1097 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001098 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001099
David Blaikie7a30dc52013-02-21 01:47:18 +00001100 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001101 }
1102
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001103 // The visibility of a template is stored in the templated decl.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001104 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001105 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001106
David Blaikie7a30dc52013-02-21 01:47:18 +00001107 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001108}
1109
Rafael Espindola9ad61122013-11-26 16:09:08 +00001110Optional<Visibility>
1111NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1112 return getExplicitVisibilityAux(this, kind, false);
1113}
1114
Eli Friedman7e346a82013-07-01 20:22:57 +00001115static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
1116 LVComputationKind computation) {
1117 // This lambda has its linkage/visibility determined by its owner.
1118 if (ContextDecl) {
1119 if (isa<ParmVarDecl>(ContextDecl))
1120 DC = ContextDecl->getDeclContext()->getRedeclContext();
1121 else
1122 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1123 }
Faisal Vali98b8e182013-09-29 20:27:06 +00001124
Eli Friedman7e346a82013-07-01 20:22:57 +00001125 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
1126 return getLVForDecl(ND, computation);
Faisal Vali98b8e182013-09-29 20:27:06 +00001127
Eli Friedman7e346a82013-07-01 20:22:57 +00001128 return LinkageInfo::external();
1129}
1130
John McCalldf25c432013-02-16 00:17:33 +00001131static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1132 LVComputationKind computation) {
1133 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1134 if (Function->isInAnonymousNamespace() &&
Rafael Espindola593537a2013-05-05 20:15:21 +00001135 !Function->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001136 return LinkageInfo::uniqueExternal();
1137
1138 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001139 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCalldf25c432013-02-16 00:17:33 +00001140 return LinkageInfo::internal();
1141
1142 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001143 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001144 if (Optional<Visibility> Vis =
1145 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001146 LV.mergeVisibility(*Vis, true);
1147 }
1148
1149 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1150 // merging storage classes and visibility attributes, so we don't have to
1151 // look at previous decls in here.
1152
1153 return LV;
1154 }
1155
1156 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001157 if (Var->hasExternalStorage()) {
Rafael Espindola593537a2013-05-05 20:15:21 +00001158 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001159 return LinkageInfo::uniqueExternal();
1160
John McCalldf25c432013-02-16 00:17:33 +00001161 LinkageInfo LV;
1162 if (Var->getStorageClass() == SC_PrivateExtern)
1163 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001164 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001165 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001166 LV.mergeVisibility(*Vis, true);
1167 }
1168
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001169 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1170 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1171 if (PrevLV.getLinkage())
1172 LV.setLinkage(PrevLV.getLinkage());
1173 LV.mergeVisibility(PrevLV);
1174 }
1175
John McCalldf25c432013-02-16 00:17:33 +00001176 return LV;
1177 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001178
1179 if (!Var->isStaticLocal())
1180 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001181 }
1182
Rafael Espindolaa4184182013-06-17 20:04:51 +00001183 ASTContext &Context = D->getASTContext();
1184 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001185 return LinkageInfo::none();
1186
Eli Friedman7e346a82013-07-01 20:22:57 +00001187 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1188 if (!OuterD)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001189 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001190
Eli Friedman7e346a82013-07-01 20:22:57 +00001191 LinkageInfo LV;
1192 if (const BlockDecl *BD = dyn_cast<BlockDecl>(OuterD)) {
1193 if (!BD->getBlockManglingNumber())
1194 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001195
Eli Friedman7e346a82013-07-01 20:22:57 +00001196 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1197 BD->getBlockManglingContextDecl(), computation);
1198 } else {
1199 const FunctionDecl *FD = cast<FunctionDecl>(OuterD);
1200 if (!FD->isInlined() &&
David Majnemer9963ade2014-12-16 04:52:14 +00001201 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
Eli Friedman7e346a82013-07-01 20:22:57 +00001202 return LinkageInfo::none();
1203
1204 LV = getLVForDecl(FD, computation);
1205 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001206 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001207 return LinkageInfo::none();
1208 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1209 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001210}
1211
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001212static inline const CXXRecordDecl*
1213getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1214 const CXXRecordDecl *Ret = Record;
1215 while (Record && Record->isLambda()) {
1216 Ret = Record;
1217 if (!Record->getParent()) break;
1218 // Get the Containing Class of this Lambda Class
1219 Record = dyn_cast_or_null<CXXRecordDecl>(
1220 Record->getParent()->getParent());
1221 }
1222 return Ret;
1223}
1224
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001225static LinkageInfo computeLVForDecl(const NamedDecl *D,
1226 LVComputationKind computation) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001227 // Objective-C: treat all Objective-C declarations as having external
1228 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001229 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001230 default:
1231 break;
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001232 case Decl::ParmVar:
1233 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001234 case Decl::TemplateTemplateParm: // count these as external
1235 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001236 case Decl::ObjCAtDefsField:
1237 case Decl::ObjCCategory:
1238 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001239 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001240 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001241 case Decl::ObjCMethod:
1242 case Decl::ObjCProperty:
1243 case Decl::ObjCPropertyImpl:
1244 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +00001245 return LinkageInfo::external();
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001246
1247 case Decl::CXXRecord: {
1248 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1249 if (Record->isLambda()) {
1250 if (!Record->getLambdaManglingNumber()) {
1251 // This lambda has no mangling number, so it's internal.
1252 return LinkageInfo::internal();
1253 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001254
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001255 // This lambda has its linkage/visibility determined:
1256 // - either by the outermost lambda if that lambda has no mangling
1257 // number.
1258 // - or by the parent of the outer most lambda
1259 // This prevents infinite recursion in settings such as nested lambdas
1260 // used in NSDMI's, for e.g.
1261 // struct L {
1262 // int t{};
1263 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1264 // };
1265 const CXXRecordDecl *OuterMostLambda =
1266 getOutermostEnclosingLambda(Record);
1267 if (!OuterMostLambda->getLambdaManglingNumber())
1268 return LinkageInfo::internal();
1269
1270 return getLVForClosure(
1271 OuterMostLambda->getDeclContext()->getRedeclContext(),
1272 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001273 }
1274
1275 break;
1276 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001277 }
1278
Douglas Gregorf73b2822009-11-25 22:24:25 +00001279 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001280 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCalldf25c432013-02-16 00:17:33 +00001281 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001282
1283 // C++ [basic.link]p5:
1284 // In addition, a member function, static data member, a named
1285 // class or enumeration of class scope, or an unnamed class or
1286 // enumeration defined in a class-scope typedef declaration such
1287 // that the class or enumeration has the typedef name for linkage
1288 // purposes (7.1.3), has external linkage if the name of the class
1289 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001290 if (D->getDeclContext()->isRecord())
John McCalldf25c432013-02-16 00:17:33 +00001291 return getLVForClassMember(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001292
1293 // C++ [basic.link]p6:
1294 // The name of a function declared in block scope and the name of
1295 // an object declared by a block scope extern declaration have
1296 // linkage. If there is a visible declaration of an entity with
1297 // linkage having the same name and type, ignoring entities
1298 // declared outside the innermost enclosing namespace scope, the
1299 // block scope declaration declares that same entity and receives
1300 // the linkage of the previous declaration. If there is more than
1301 // one such matching entity, the program is ill-formed. Otherwise,
1302 // if no matching entity is found, the block scope entity receives
1303 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001304 if (D->getDeclContext()->isFunctionOrMethod())
1305 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001306
1307 // C++ [basic.link]p6:
1308 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001309 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001310}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001311
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001312namespace clang {
1313class LinkageComputer {
1314public:
1315 static LinkageInfo getLVForDecl(const NamedDecl *D,
1316 LVComputationKind computation) {
1317 if (computation == LVForLinkageOnly && D->hasCachedLinkage())
1318 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1319
1320 LinkageInfo LV = computeLVForDecl(D, computation);
1321 if (D->hasCachedLinkage())
1322 assert(D->getCachedLinkage() == LV.getLinkage());
1323
1324 D->setCachedLinkage(LV.getLinkage());
1325
1326#ifndef NDEBUG
1327 // In C (because of gnu inline) and in c++ with microsoft extensions an
1328 // static can follow an extern, so we can have two decls with different
1329 // linkages.
1330 const LangOptions &Opts = D->getASTContext().getLangOpts();
1331 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1332 return LV;
1333
1334 // We have just computed the linkage for this decl. By induction we know
1335 // that all other computed linkages match, check that the one we just
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001336 // computed also does.
Craig Topper36250ad2014-05-12 05:36:57 +00001337 NamedDecl *Old = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +00001338 for (auto I : D->redecls()) {
1339 NamedDecl *T = cast<NamedDecl>(I);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001340 if (T == D)
1341 continue;
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001342 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001343 Old = T;
1344 break;
1345 }
1346 }
1347 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1348#endif
1349
1350 return LV;
1351 }
1352};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001353}
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001354
1355static LinkageInfo getLVForDecl(const NamedDecl *D,
1356 LVComputationKind computation) {
1357 return clang::LinkageComputer::getLVForDecl(D, computation);
1358}
1359
Douglas Gregor2ada0482009-02-04 17:27:36 +00001360std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001361 std::string QualName;
1362 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001363 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001364 return OS.str();
1365}
1366
1367void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1368 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1369}
1370
1371void NamedDecl::printQualifiedName(raw_ostream &OS,
1372 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001373 const DeclContext *Ctx = getDeclContext();
1374
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001375 if (Ctx->isFunctionOrMethod()) {
1376 printName(OS);
1377 return;
1378 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001379
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001380 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001381 ContextsTy Contexts;
1382
1383 // Collect contexts.
1384 while (Ctx && isa<NamedDecl>(Ctx)) {
1385 Contexts.push_back(Ctx);
1386 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001387 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001388
1389 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1390 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00001391 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001392 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001393 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001394 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00001395 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1396 TemplateArgs.data(),
1397 TemplateArgs.size(),
1398 P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001399 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Richard Smith46dd5bb2014-05-30 22:16:51 +00001400 if (P.SuppressUnwrittenScope &&
1401 (ND->isAnonymousNamespace() || ND->isInline()))
1402 continue;
Sam Weinig07d211e2009-12-24 23:15:03 +00001403 if (ND->isAnonymousNamespace())
David Blaikieabe1a392014-04-02 05:58:29 +00001404 OS << "(anonymous namespace)";
Sam Weinig07d211e2009-12-24 23:15:03 +00001405 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001406 OS << *ND;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001407 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1408 if (!RD->getIdentifier())
David Blaikieabe1a392014-04-02 05:58:29 +00001409 OS << "(anonymous " << RD->getKindName() << ')';
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001410 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001411 OS << *RD;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001412 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Craig Topper36250ad2014-05-12 05:36:57 +00001413 const FunctionProtoType *FT = nullptr;
Sam Weinigb999f682009-12-28 03:19:38 +00001414 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001415 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001416
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001417 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001418 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001419 unsigned NumParams = FD->getNumParams();
1420 for (unsigned i = 0; i < NumParams; ++i) {
1421 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001422 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001423 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001424 }
1425
1426 if (FT->isVariadic()) {
1427 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001428 OS << ", ";
1429 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001430 }
1431 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001432 OS << ')';
1433 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001434 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001435 }
1436 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001437 }
1438
John McCalla2a3f7d2010-03-16 21:48:18 +00001439 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001440 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001441 else
David Blaikieabe1a392014-04-02 05:58:29 +00001442 OS << "(anonymous)";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001443}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001444
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001445void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1446 const PrintingPolicy &Policy,
1447 bool Qualified) const {
1448 if (Qualified)
1449 printQualifiedName(OS, Policy);
1450 else
1451 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001452}
1453
Richard Smithe8292b12015-02-10 03:28:10 +00001454static bool isKindReplaceableBy(Decl::Kind OldK, Decl::Kind NewK) {
1455 // For method declarations, we never replace.
1456 if (ObjCMethodDecl::classofKind(NewK))
1457 return false;
1458
1459 if (OldK == NewK)
1460 return true;
1461
1462 // A compatibility alias for a class can be replaced by an interface.
1463 if (ObjCCompatibleAliasDecl::classofKind(OldK) &&
1464 ObjCInterfaceDecl::classofKind(NewK))
1465 return true;
1466
1467 // A typedef-declaration, alias-declaration, or Objective-C class declaration
1468 // can replace another declaration of the same type. Semantic analysis checks
1469 // that we have matching types.
1470 if ((TypedefNameDecl::classofKind(OldK) ||
1471 ObjCInterfaceDecl::classofKind(OldK)) &&
1472 (TypedefNameDecl::classofKind(NewK) ||
1473 ObjCInterfaceDecl::classofKind(NewK)))
1474 return true;
1475
1476 // Otherwise, a kind mismatch implies that the declaration is not replaced.
1477 return false;
1478}
1479
1480template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1481 return true;
1482}
1483static bool isRedeclarableImpl(...) { return false; }
1484static bool isRedeclarable(Decl::Kind K) {
1485 switch (K) {
1486#define DECL(Type, Base) \
1487 case Decl::Type: \
1488 return isRedeclarableImpl((Type##Decl *)nullptr);
1489#define ABSTRACT_DECL(DECL)
1490#include "clang/AST/DeclNodes.inc"
1491 }
1492 llvm_unreachable("unknown decl kind");
1493}
1494
1495bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001496 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1497
Richard Smithfe620d22015-03-05 23:24:12 +00001498 // Never replace one imported declaration with another; we need both results
1499 // when re-exporting.
1500 if (OldD->isFromASTFile() && isFromASTFile())
1501 return false;
1502
Richard Smithe8292b12015-02-10 03:28:10 +00001503 if (!isKindReplaceableBy(OldD->getKind(), getKind()))
1504 return false;
1505
1506 // Inline namespaces can give us two declarations with the same
1507 // name and kind in the same scope but different contexts; we should
1508 // keep both declarations in this case.
1509 if (!this->getDeclContext()->getRedeclContext()->Equals(
1510 OldD->getDeclContext()->getRedeclContext()))
1511 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001512
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001513 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1514 // For function declarations, we keep track of redeclarations.
Richard Smithe8292b12015-02-10 03:28:10 +00001515 // FIXME: This returns false for functions that should in fact be replaced.
1516 // Instead, perform some kind of type check?
1517 if (FD->getPreviousDecl() != OldD)
1518 return false;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001519
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001520 // For function templates, the underlying function declarations are linked.
Richard Smithe8292b12015-02-10 03:28:10 +00001521 if (const FunctionTemplateDecl *FunctionTemplate =
1522 dyn_cast<FunctionTemplateDecl>(this))
1523 return FunctionTemplate->getTemplatedDecl()->declarationReplaces(
1524 cast<FunctionTemplateDecl>(OldD)->getTemplatedDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001525
Richard Smithe8292b12015-02-10 03:28:10 +00001526 // Using shadow declarations can be overloaded on their target declarations
1527 // if they introduce functions.
1528 // FIXME: If our target replaces the old target, can we replace the old
1529 // shadow declaration?
1530 if (auto *USD = dyn_cast<UsingShadowDecl>(this))
1531 if (USD->getTargetDecl() != cast<UsingShadowDecl>(OldD)->getTargetDecl())
1532 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001533
Richard Smithe8292b12015-02-10 03:28:10 +00001534 // Using declarations can be overloaded if they introduce functions.
1535 if (auto *UD = dyn_cast<UsingDecl>(this)) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001536 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001537 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001538 Context.getCanonicalNestedNameSpecifier(
Richard Smithe8292b12015-02-10 03:28:10 +00001539 cast<UsingDecl>(OldD)->getQualifier());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001540 }
Richard Smithe8292b12015-02-10 03:28:10 +00001541 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001542 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001543 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001544 Context.getCanonicalNestedNameSpecifier(
1545 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1546 }
1547
Richard Smithe8292b12015-02-10 03:28:10 +00001548 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1549 // We want to keep it, unless it nominates same namespace.
1550 if (auto *UD = dyn_cast<UsingDirectiveDecl>(this))
1551 return UD->getNominatedNamespace()->getOriginalNamespace() ==
1552 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1553 ->getOriginalNamespace();
Richard Smithbaf3ca52014-03-17 21:46:03 +00001554
Richard Smithe8292b12015-02-10 03:28:10 +00001555 if (!IsKnownNewer && isRedeclarable(getKind())) {
1556 // Check whether this is actually newer than OldD. We want to keep the
1557 // newer declaration. This loop will usually only iterate once, because
1558 // OldD is usually the previous declaration.
1559 for (auto D : redecls()) {
1560 if (D == OldD)
1561 break;
1562
1563 // If we reach the canonical declaration, then OldD is not actually older
1564 // than this one.
1565 //
1566 // FIXME: In this case, we should not add this decl to the lookup table.
1567 if (D->isCanonicalDecl())
1568 return false;
1569 }
1570 }
1571
1572 // It's a newer declaration of the same kind of declaration in the same scope,
1573 // and not an overload: we want this decl instead of the existing one.
1574 return true;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001575}
1576
Douglas Gregoreddf4332009-02-24 20:03:32 +00001577bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001578 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001579}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001580
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001581NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001582 NamedDecl *ND = this;
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001583 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1584 ND = UD->getTargetDecl();
1585
1586 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1587 return AD->getClassInterface();
1588
1589 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001590}
1591
John McCalla8ae2222010-04-06 21:38:20 +00001592bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001593 if (!isCXXClassMember())
1594 return false;
1595
John McCalla8ae2222010-04-06 21:38:20 +00001596 const NamedDecl *D = this;
1597 if (isa<UsingShadowDecl>(D))
1598 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1599
John McCall5e77d762013-04-16 07:28:30 +00001600 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001601 return true;
Alp Tokera2794f92014-01-22 07:29:52 +00001602 if (const CXXMethodDecl *MD =
1603 dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1604 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001605 return false;
1606}
1607
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001608//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001609// DeclaratorDecl Implementation
1610//===----------------------------------------------------------------------===//
1611
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001612template <typename DeclT>
1613static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1614 if (decl->getNumTemplateParameterLists() > 0)
1615 return decl->getTemplateParameterList(0)->getTemplateLoc();
1616 else
1617 return decl->getInnerLocStart();
1618}
1619
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001620SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001621 TypeSourceInfo *TSI = getTypeSourceInfo();
1622 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001623 return SourceLocation();
1624}
1625
Douglas Gregor14454802011-02-25 02:25:35 +00001626void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1627 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001628 // Make sure the extended decl info is allocated.
1629 if (!hasExtInfo()) {
1630 // Save (non-extended) type source info pointer.
1631 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1632 // Allocate external info struct.
1633 DeclInfo = new (getASTContext()) ExtInfo;
1634 // Restore savedTInfo into (extended) decl info.
1635 getExtInfo()->TInfo = savedTInfo;
1636 }
1637 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001638 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001639 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001640 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001641 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001642 if (getExtInfo()->NumTemplParamLists == 0) {
1643 // Save type source info pointer.
1644 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1645 // Deallocate the extended decl info.
1646 getASTContext().Deallocate(getExtInfo());
1647 // Restore savedTInfo into (non-extended) decl info.
1648 DeclInfo = savedTInfo;
1649 }
1650 else
1651 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001652 }
1653 }
1654}
1655
Abramo Bagnara60804e12011-03-18 15:16:37 +00001656void
1657DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1658 unsigned NumTPLists,
1659 TemplateParameterList **TPLists) {
1660 assert(NumTPLists > 0);
1661 // Make sure the extended decl info is allocated.
1662 if (!hasExtInfo()) {
1663 // Save (non-extended) type source info pointer.
1664 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1665 // Allocate external info struct.
1666 DeclInfo = new (getASTContext()) ExtInfo;
1667 // Restore savedTInfo into (extended) decl info.
1668 getExtInfo()->TInfo = savedTInfo;
1669 }
1670 // Set the template parameter lists info.
1671 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1672}
1673
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001674SourceLocation DeclaratorDecl::getOuterLocStart() const {
1675 return getTemplateOrInnerLocStart(this);
1676}
1677
Abramo Bagnaraea947882011-03-08 16:41:52 +00001678namespace {
1679
1680// Helper function: returns true if QT is or contains a type
1681// having a postfix component.
1682bool typeIsPostfix(clang::QualType QT) {
1683 while (true) {
1684 const Type* T = QT.getTypePtr();
1685 switch (T->getTypeClass()) {
1686 default:
1687 return false;
1688 case Type::Pointer:
1689 QT = cast<PointerType>(T)->getPointeeType();
1690 break;
1691 case Type::BlockPointer:
1692 QT = cast<BlockPointerType>(T)->getPointeeType();
1693 break;
1694 case Type::MemberPointer:
1695 QT = cast<MemberPointerType>(T)->getPointeeType();
1696 break;
1697 case Type::LValueReference:
1698 case Type::RValueReference:
1699 QT = cast<ReferenceType>(T)->getPointeeType();
1700 break;
1701 case Type::PackExpansion:
1702 QT = cast<PackExpansionType>(T)->getPattern();
1703 break;
1704 case Type::Paren:
1705 case Type::ConstantArray:
1706 case Type::DependentSizedArray:
1707 case Type::IncompleteArray:
1708 case Type::VariableArray:
1709 case Type::FunctionProto:
1710 case Type::FunctionNoProto:
1711 return true;
1712 }
1713 }
1714}
1715
1716} // namespace
1717
1718SourceRange DeclaratorDecl::getSourceRange() const {
1719 SourceLocation RangeEnd = getLocation();
1720 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001721 // If the declaration has no name or the type extends past the name take the
1722 // end location of the type.
1723 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001724 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1725 }
1726 return SourceRange(getOuterLocStart(), RangeEnd);
1727}
1728
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001729void
Douglas Gregor20527e22010-06-15 17:44:38 +00001730QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1731 unsigned NumTPLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001732 TemplateParameterList **TPLists) {
Craig Topper36250ad2014-05-12 05:36:57 +00001733 assert((NumTPLists == 0 || TPLists != nullptr) &&
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001734 "Empty array of template parameters with positive size!");
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001735
1736 // Free previous template parameters (if any).
1737 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001738 Context.Deallocate(TemplParamLists);
Craig Topper36250ad2014-05-12 05:36:57 +00001739 TemplParamLists = nullptr;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001740 NumTemplParamLists = 0;
1741 }
1742 // Set info on matched template parameter lists (if any).
1743 if (NumTPLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001744 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001745 NumTemplParamLists = NumTPLists;
Benjamin Kramer67e6a542015-04-05 18:55:02 +00001746 std::copy(TPLists, TPLists + NumTPLists, TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001747 }
1748}
1749
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001750//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001751// VarDecl Implementation
1752//===----------------------------------------------------------------------===//
1753
Sebastian Redl833ef452010-01-26 22:01:41 +00001754const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1755 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001756 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001757 case SC_Auto: return "auto";
1758 case SC_Extern: return "extern";
1759 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1760 case SC_PrivateExtern: return "__private_extern__";
1761 case SC_Register: return "register";
1762 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001763 }
1764
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001765 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001766}
1767
Richard Smith053f6c62014-05-16 23:01:30 +00001768VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1769 SourceLocation StartLoc, SourceLocation IdLoc,
1770 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1771 StorageClass SC)
1772 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1773 redeclarable_base(C), Init() {
Benjamin Kramera939c232014-03-15 18:54:13 +00001774 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1775 "VarDeclBitfields too large!");
1776 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1777 "ParmVarDeclBitfields too large!");
David Majnemerfa7bc782015-05-19 00:57:16 +00001778 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1779 "NonParmVarDeclBitfields too large!");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001780 AllBits = 0;
1781 VarDeclBits.SClass = SC;
1782 // Everything else is implicitly initialized to false.
1783}
1784
Abramo Bagnaradff19302011-03-08 08:55:46 +00001785VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1786 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001787 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001788 StorageClass S) {
Richard Smith053f6c62014-05-16 23:01:30 +00001789 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001790}
1791
Douglas Gregor72172e92012-01-05 21:55:30 +00001792VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00001793 return new (C, ID)
1794 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1795 QualType(), nullptr, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001796}
1797
Douglas Gregorbf62d642010-12-06 18:36:25 +00001798void VarDecl::setStorageClass(StorageClass SC) {
1799 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001800 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001801}
1802
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001803VarDecl::TLSKind VarDecl::getTLSKind() const {
1804 switch (VarDeclBits.TSCSpec) {
1805 case TSCS_unspecified:
Samuel Antaof8b50122015-07-13 22:54:53 +00001806 if (!hasAttr<ThreadAttr>() &&
1807 !(getASTContext().getLangOpts().OpenMPUseTLS &&
1808 getASTContext().getTargetInfo().isTLSSupported() &&
1809 hasAttr<OMPThreadPrivateDeclAttr>()))
David Majnemer1b5baff2015-05-14 05:19:23 +00001810 return TLS_None;
Samuel Antaof8b50122015-07-13 22:54:53 +00001811 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1812 LangOptions::MSVC2015)) ||
1813 hasAttr<OMPThreadPrivateDeclAttr>())
David Majnemer1b5baff2015-05-14 05:19:23 +00001814 ? TLS_Dynamic
1815 : TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001816 case TSCS___thread: // Fall through.
1817 case TSCS__Thread_local:
Samuel Antaof8b50122015-07-13 22:54:53 +00001818 return TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001819 case TSCS_thread_local:
1820 return TLS_Dynamic;
1821 }
1822 llvm_unreachable("Unknown thread storage class specifier!");
1823}
1824
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001825SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001826 if (const Expr *Init = getInit()) {
1827 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001828 // If Init is implicit, ignore its source range and fallback on
1829 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1830 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001831 return SourceRange(getOuterLocStart(), InitEnd);
1832 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001833 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001834}
1835
Rafael Espindola88510672013-01-04 21:18:45 +00001836template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001837static LanguageLinkage getDeclLanguageLinkage(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001838 // C++ [dcl.link]p1: All function types, function names with external linkage,
1839 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001840 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001841 return NoLanguageLinkage;
1842
1843 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001844 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001845 ASTContext &Context = D.getASTContext();
1846 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001847 return CLanguageLinkage;
1848
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001849 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1850 // language linkage of the names of class members and the function type of
1851 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001852 const DeclContext *DC = D.getDeclContext();
1853 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001854 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001855
1856 // If the first decl is in an extern "C" context, any other redeclaration
1857 // will have C language linkage. If the first one is not in an extern "C"
1858 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00001859 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00001860 return CLanguageLinkage;
1861 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001862}
1863
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001864template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001865static bool isDeclExternC(const T &D) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001866 // Since the context is ignored for class members, they can only have C++
1867 // language linkage or no language linkage.
1868 const DeclContext *DC = D.getDeclContext();
1869 if (DC->isRecord()) {
1870 assert(D.getASTContext().getLangOpts().CPlusPlus);
1871 return false;
1872 }
1873
1874 return D.getLanguageLinkage() == CLanguageLinkage;
1875}
1876
Rafael Espindolaf4187652013-02-14 01:18:37 +00001877LanguageLinkage VarDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00001878 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001879}
1880
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001881bool VarDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00001882 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001883}
1884
Rafael Espindola593537a2013-05-05 20:15:21 +00001885bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001886 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001887}
1888
1889bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001890 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001891}
1892
Rafael Espindola8db352d2013-10-17 15:37:26 +00001893VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00001894
Nico Weber7f5015a2015-04-15 21:53:00 +00001895VarDecl::DefinitionKind
1896VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001897 // C++ [basic.def]p2:
1898 // A declaration is a definition unless [...] it contains the 'extern'
1899 // specifier or a linkage-specification and neither an initializer [...],
1900 // it declares a static data member in a class declaration [...].
Richard Smith8809a0c2013-09-27 20:14:12 +00001901 // C++1y [temp.expl.spec]p15:
1902 // An explicit specialization of a static data member or an explicit
1903 // specialization of a static data member template is a definition if the
1904 // declaration includes an initializer; otherwise, it is a declaration.
1905 //
1906 // FIXME: How do you declare (but not define) a partial specialization of
1907 // a static data member template outside the containing class?
Sebastian Redl35351a92010-01-31 22:27:38 +00001908 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00001909 if (isOutOfLine() &&
1910 (hasInit() ||
1911 // If the first declaration is out-of-line, this may be an
1912 // instantiation of an out-of-line partial specialization of a variable
1913 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00001914 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00001915 ? getTemplateSpecializationKind() == TSK_Undeclared
1916 : getTemplateSpecializationKind() !=
1917 TSK_ExplicitSpecialization) ||
1918 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00001919 return Definition;
1920 else
1921 return DeclarationOnly;
1922 }
1923 // C99 6.7p5:
1924 // A definition of an identifier is a declaration for that identifier that
1925 // [...] causes storage to be reserved for that object.
1926 // Note: that applies for all non-file-scope objects.
1927 // C99 6.9.2p1:
1928 // If the declaration of an identifier for an object has file scope and an
1929 // initializer, the declaration is an external definition for the identifier
1930 if (hasInit())
1931 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00001932
David Majnemerdd0bed12015-05-14 05:19:20 +00001933 if (hasAttr<AliasAttr>())
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001934 return Definition;
1935
David Majnemerdd0bed12015-05-14 05:19:20 +00001936 if (const auto *SAA = getAttr<SelectAnyAttr>())
1937 if (!SAA->isInherited())
1938 return Definition;
1939
Richard Smith8809a0c2013-09-27 20:14:12 +00001940 // A variable template specialization (other than a static data member
1941 // template or an explicit specialization) is a declaration until we
1942 // instantiate its initializer.
1943 if (isa<VarTemplateSpecializationDecl>(this) &&
1944 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1945 return DeclarationOnly;
1946
Nico Weber608e7682015-04-15 23:04:24 +00001947 if (hasExternalStorage())
Sebastian Redl35351a92010-01-31 22:27:38 +00001948 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00001949
Rafael Espindolabff59562013-04-25 12:11:36 +00001950 // [dcl.link] p7:
1951 // A declaration directly contained in a linkage-specification is treated
1952 // as if it contains the extern specifier for the purpose of determining
1953 // the linkage of the declared name and whether it is a definition.
Nico Weber608e7682015-04-15 23:04:24 +00001954 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00001955 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00001956
Sebastian Redl35351a92010-01-31 22:27:38 +00001957 // C99 6.9.2p2:
1958 // A declaration of an object that has file scope without an initializer,
1959 // and without a storage class specifier or the scs 'static', constitutes
1960 // a tentative definition.
1961 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001962 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00001963 return TentativeDefinition;
1964
1965 // What's left is (in C, block-scope) declarations without initializers or
1966 // external storage. These are definitions.
1967 return Definition;
1968}
1969
Sebastian Redl35351a92010-01-31 22:27:38 +00001970VarDecl *VarDecl::getActingDefinition() {
1971 DefinitionKind Kind = isThisDeclarationADefinition();
1972 if (Kind != TentativeDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00001973 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00001974
Craig Topper36250ad2014-05-12 05:36:57 +00001975 VarDecl *LastTentative = nullptr;
Rafael Espindola8db352d2013-10-17 15:37:26 +00001976 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001977 for (auto I : First->redecls()) {
1978 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00001979 if (Kind == Definition)
Craig Topper36250ad2014-05-12 05:36:57 +00001980 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00001981 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00001982 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00001983 }
1984 return LastTentative;
1985}
1986
Daniel Dunbar9d355812012-03-09 01:51:51 +00001987VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001988 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001989 for (auto I : First->redecls()) {
1990 if (I->isThisDeclarationADefinition(C) == Definition)
1991 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00001992 }
Craig Topper36250ad2014-05-12 05:36:57 +00001993 return nullptr;
Sebastian Redl5ca79842010-02-01 20:16:42 +00001994}
1995
Daniel Dunbar9d355812012-03-09 01:51:51 +00001996VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00001997 DefinitionKind Kind = DeclarationOnly;
1998
Rafael Espindola8db352d2013-10-17 15:37:26 +00001999 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002000 for (auto I : First->redecls()) {
2001 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00002002 if (Kind == Definition)
2003 break;
2004 }
John McCall37bb6c92010-10-29 22:22:43 +00002005
2006 return Kind;
2007}
2008
Sebastian Redl5ca79842010-02-01 20:16:42 +00002009const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002010 for (auto I : redecls()) {
2011 if (auto Expr = I->getInit()) {
2012 D = I;
2013 return Expr;
2014 }
Sebastian Redl833ef452010-01-26 22:01:41 +00002015 }
Craig Topper36250ad2014-05-12 05:36:57 +00002016 return nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002017}
2018
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002019bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002020 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002021 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00002022
2023 if (!isStaticDataMember())
2024 return false;
2025
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002026 // If this static data member was instantiated from a static data member of
2027 // a class template, check whether that static data member was defined
2028 // out-of-line.
2029 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2030 return VD->isOutOfLine();
2031
2032 return false;
2033}
2034
Douglas Gregor1d957a32009-10-27 18:42:08 +00002035VarDecl *VarDecl::getOutOfLineDefinition() {
2036 if (!isStaticDataMember())
Craig Topper36250ad2014-05-12 05:36:57 +00002037 return nullptr;
2038
Aaron Ballman86c93902014-03-06 23:45:36 +00002039 for (auto RD : redecls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002040 if (RD->getLexicalDeclContext()->isFileContext())
Aaron Ballman86c93902014-03-06 23:45:36 +00002041 return RD;
Douglas Gregor1d957a32009-10-27 18:42:08 +00002042 }
Craig Topper36250ad2014-05-12 05:36:57 +00002043
2044 return nullptr;
Douglas Gregor1d957a32009-10-27 18:42:08 +00002045}
2046
Douglas Gregord5058122010-02-11 01:19:42 +00002047void VarDecl::setInit(Expr *I) {
Sebastian Redl833ef452010-01-26 22:01:41 +00002048 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
2049 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00002050 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00002051 }
2052
2053 Init = I;
2054}
2055
Daniel Dunbar9d355812012-03-09 01:51:51 +00002056bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002057 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00002058
Richard Smith35ecb362012-03-02 04:14:40 +00002059 if (!Lang.CPlusPlus)
2060 return false;
2061
2062 // In C++11, any variable of reference type can be used in a constant
2063 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002064 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00002065 return true;
2066
2067 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00002068 // not require the variable to be non-volatile, but we consider this to be a
2069 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00002070 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00002071 return false;
2072
2073 // In C++, const, non-volatile variables of integral or enumeration types
2074 // can be used in constant expressions.
2075 if (getType()->isIntegralOrEnumerationType())
2076 return true;
2077
Richard Smith35ecb362012-03-02 04:14:40 +00002078 // Additionally, in C++11, non-volatile constexpr variables can be used in
2079 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002080 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00002081}
2082
Richard Smithd0b4dd62011-12-19 06:19:21 +00002083/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2084/// form, which contains extra information on the evaluated value of the
2085/// initializer.
2086EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2087 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
2088 if (!Eval) {
2089 Stmt *S = Init.get<Stmt *>();
Manuel Klimeka7328992013-06-03 13:51:33 +00002090 // Note: EvaluatedStmt contains an APValue, which usually holds
2091 // resources not allocated from the ASTContext. We need to do some
2092 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2093 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002094 Eval = new (getASTContext()) EvaluatedStmt;
2095 Eval->Value = S;
2096 Init = Eval;
2097 }
2098 return Eval;
2099}
2100
Richard Smithdafff942012-01-14 04:30:29 +00002101APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002102 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00002103 return evaluateValue(Notes);
2104}
2105
Manuel Klimeka7328992013-06-03 13:51:33 +00002106namespace {
2107// Destroy an APValue that was allocated in an ASTContext.
2108void DestroyAPValue(void* UntypedValue) {
2109 static_cast<APValue*>(UntypedValue)->~APValue();
2110}
2111} // namespace
2112
Richard Smithdafff942012-01-14 04:30:29 +00002113APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002114 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002115 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2116
2117 // We only produce notes indicating why an initializer is non-constant the
2118 // first time it is evaluated. FIXME: The notes won't always be emitted the
2119 // first time we try evaluation, so might not be produced at all.
2120 if (Eval->WasEvaluated)
Craig Topper36250ad2014-05-12 05:36:57 +00002121 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002122
2123 const Expr *Init = cast<Expr>(Eval->Value);
2124 assert(!Init->isValueDependent());
2125
2126 if (Eval->IsEvaluating) {
2127 // FIXME: Produce a diagnostic for self-initialization.
2128 Eval->CheckedICE = true;
2129 Eval->IsICE = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002130 return nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002131 }
2132
2133 Eval->IsEvaluating = true;
2134
2135 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2136 this, Notes);
2137
Manuel Klimeka7328992013-06-03 13:51:33 +00002138 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2139 // or that it's empty (so that there's nothing to clean up) if evaluation
2140 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002141 if (!Result)
2142 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00002143 else if (Eval->Evaluated.needsCleanup())
2144 getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002145
2146 Eval->IsEvaluating = false;
2147 Eval->WasEvaluated = true;
2148
2149 // In C++11, we have determined whether the initializer was a constant
2150 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002151 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002152 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00002153 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002154 }
2155
Craig Topper36250ad2014-05-12 05:36:57 +00002156 return Result ? &Eval->Evaluated : nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002157}
2158
2159bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00002160 // Initializers of weak variables are never ICEs.
2161 if (isWeak())
2162 return false;
2163
Richard Smithd0b4dd62011-12-19 06:19:21 +00002164 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2165 if (Eval->CheckedICE)
2166 // We have already checked whether this subexpression is an
2167 // integral constant expression.
2168 return Eval->IsICE;
2169
2170 const Expr *Init = cast<Expr>(Eval->Value);
2171 assert(!Init->isValueDependent());
2172
2173 // In C++11, evaluate the initializer to check whether it's a constant
2174 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002175 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002176 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002177 evaluateValue(Notes);
2178 return Eval->IsICE;
2179 }
2180
2181 // It's an ICE whether or not the definition we found is
2182 // out-of-line. See DR 721 and the discussion in Clang PR
2183 // 6206 for details.
2184
2185 if (Eval->CheckingICE)
2186 return false;
2187 Eval->CheckingICE = true;
2188
2189 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2190 Eval->CheckingICE = false;
2191 Eval->CheckedICE = true;
2192 return Eval->IsICE;
2193}
2194
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002195VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002196 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002197 return cast<VarDecl>(MSI->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002198
2199 return nullptr;
Douglas Gregor86d142a2009-10-08 07:24:58 +00002200}
2201
Douglas Gregor3c74d412009-10-14 20:14:33 +00002202TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002203 if (const VarTemplateSpecializationDecl *Spec =
2204 dyn_cast<VarTemplateSpecializationDecl>(this))
2205 return Spec->getSpecializationKind();
2206
Sebastian Redl35351a92010-01-31 22:27:38 +00002207 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002208 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002209
Douglas Gregor86d142a2009-10-08 07:24:58 +00002210 return TSK_Undeclared;
2211}
2212
Richard Smith8809a0c2013-09-27 20:14:12 +00002213SourceLocation VarDecl::getPointOfInstantiation() const {
2214 if (const VarTemplateSpecializationDecl *Spec =
2215 dyn_cast<VarTemplateSpecializationDecl>(this))
2216 return Spec->getPointOfInstantiation();
2217
2218 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2219 return MSI->getPointOfInstantiation();
2220
2221 return SourceLocation();
2222}
2223
Larisse Voufo39a1e502013-08-06 01:03:05 +00002224VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2225 return getASTContext().getTemplateOrSpecializationInfo(this)
2226 .dyn_cast<VarTemplateDecl *>();
2227}
2228
2229void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2230 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2231}
2232
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002233MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002234 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002235 // FIXME: Remove ?
2236 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2237 return getASTContext().getTemplateOrSpecializationInfo(this)
2238 .dyn_cast<MemberSpecializationInfo *>();
Craig Topper36250ad2014-05-12 05:36:57 +00002239 return nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002240}
2241
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002242void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2243 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002244 assert((isa<VarTemplateSpecializationDecl>(this) ||
2245 getMemberSpecializationInfo()) &&
2246 "not a variable or static data member template specialization");
2247
Larisse Voufo39a1e502013-08-06 01:03:05 +00002248 if (VarTemplateSpecializationDecl *Spec =
2249 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2250 Spec->setSpecializationKind(TSK);
2251 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2252 Spec->getPointOfInstantiation().isInvalid())
2253 Spec->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002254 }
2255
2256 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2257 MSI->setTemplateSpecializationKind(TSK);
2258 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2259 MSI->getPointOfInstantiation().isInvalid())
2260 MSI->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002261 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002262}
2263
2264void
2265VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2266 TemplateSpecializationKind TSK) {
2267 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2268 "Previous template or instantiation?");
2269 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002270}
2271
Sebastian Redl833ef452010-01-26 22:01:41 +00002272//===----------------------------------------------------------------------===//
2273// ParmVarDecl Implementation
2274//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002275
Sebastian Redl833ef452010-01-26 22:01:41 +00002276ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002277 SourceLocation StartLoc,
2278 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002279 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002280 StorageClass S, Expr *DefArg) {
Richard Smith053f6c62014-05-16 23:01:30 +00002281 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smithf7981722013-11-22 09:01:48 +00002282 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002283}
2284
Reid Kleckner8a365022013-06-24 17:51:48 +00002285QualType ParmVarDecl::getOriginalType() const {
2286 TypeSourceInfo *TSI = getTypeSourceInfo();
2287 QualType T = TSI ? TSI->getType() : getType();
2288 if (const DecayedType *DT = dyn_cast<DecayedType>(T))
2289 return DT->getOriginalType();
2290 return T;
2291}
2292
Douglas Gregor72172e92012-01-05 21:55:30 +00002293ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00002294 return new (C, ID)
2295 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2296 nullptr, QualType(), nullptr, SC_None, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00002297}
2298
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002299SourceRange ParmVarDecl::getSourceRange() const {
2300 if (!hasInheritedDefaultArg()) {
2301 SourceRange ArgRange = getDefaultArgRange();
2302 if (ArgRange.isValid())
2303 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2304 }
2305
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002306 // DeclaratorDecl considers the range of postfix types as overlapping with the
2307 // declaration name, but this is not the case with parameters in ObjC methods.
2308 if (isa<ObjCMethodDecl>(getDeclContext()))
2309 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2310
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002311 return DeclaratorDecl::getSourceRange();
2312}
2313
Sebastian Redl833ef452010-01-26 22:01:41 +00002314Expr *ParmVarDecl::getDefaultArg() {
2315 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2316 assert(!hasUninstantiatedDefaultArg() &&
2317 "Default argument is not yet instantiated!");
2318
2319 Expr *Arg = getInit();
John McCall5d413782010-12-06 08:20:24 +00002320 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002321 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002322
Sebastian Redl833ef452010-01-26 22:01:41 +00002323 return Arg;
2324}
2325
Sebastian Redl833ef452010-01-26 22:01:41 +00002326SourceRange ParmVarDecl::getDefaultArgRange() const {
2327 if (const Expr *E = getInit())
2328 return E->getSourceRange();
2329
2330 if (hasUninstantiatedDefaultArg())
2331 return getUninstantiatedDefaultArg()->getSourceRange();
2332
2333 return SourceRange();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002334}
2335
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00002336bool ParmVarDecl::isParameterPack() const {
2337 return isa<PackExpansionType>(getType());
2338}
2339
Ted Kremenek540017e2011-10-06 05:00:56 +00002340void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2341 getASTContext().setParameterIndex(this, parameterIndex);
2342 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2343}
2344
2345unsigned ParmVarDecl::getParameterIndexLarge() const {
2346 return getASTContext().getParameterIndex(this);
2347}
2348
Nuno Lopes394ec982008-12-17 23:39:55 +00002349//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002350// FunctionDecl Implementation
2351//===----------------------------------------------------------------------===//
2352
Benjamin Kramer9170e912013-02-22 15:46:01 +00002353void FunctionDecl::getNameForDiagnostic(
2354 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2355 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002356 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2357 if (TemplateArgs)
Benjamin Kramer9170e912013-02-22 15:46:01 +00002358 TemplateSpecializationType::PrintTemplateArgumentList(
2359 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002360}
2361
Ted Kremenek186a0742010-04-29 16:49:01 +00002362bool FunctionDecl::isVariadic() const {
2363 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
2364 return FT->isVariadic();
2365 return false;
2366}
2367
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002368bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002369 for (auto I : redecls()) {
Francois Pichet1c229c02011-04-22 22:18:13 +00002370 if (I->Body || I->IsLateTemplateParsed) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002371 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002372 return true;
2373 }
2374 }
2375
2376 return false;
2377}
2378
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002379bool FunctionDecl::hasTrivialBody() const
2380{
2381 Stmt *S = getBody();
2382 if (!S) {
2383 // Since we don't have a body for this function, we don't know if it's
2384 // trivial or not.
2385 return false;
2386 }
2387
2388 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2389 return true;
2390 return false;
2391}
2392
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002393bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002394 for (auto I : redecls()) {
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002395 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
2396 I->hasAttr<AliasAttr>()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002397 Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002398 return true;
2399 }
2400 }
2401
2402 return false;
2403}
2404
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002405Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002406 if (!hasBody(Definition))
Craig Topper36250ad2014-05-12 05:36:57 +00002407 return nullptr;
Rafael Espindola44503012013-10-19 01:37:17 +00002408
2409 if (Definition->Body)
2410 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002411
Craig Topper36250ad2014-05-12 05:36:57 +00002412 return nullptr;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002413}
2414
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002415void FunctionDecl::setBody(Stmt *B) {
2416 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002417 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002418 EndRangeLoc = B->getLocEnd();
2419}
2420
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002421void FunctionDecl::setPure(bool P) {
2422 IsPure = P;
2423 if (P)
2424 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2425 Parent->markedVirtualFunctionPure();
2426}
2427
Richard Smith8d0dc312013-07-21 23:12:18 +00002428template<std::size_t Len>
2429static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2430 IdentifierInfo *II = ND->getIdentifier();
2431 return II && II->isStr(Str);
2432}
2433
Douglas Gregor16618f22009-09-12 00:17:51 +00002434bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002435 const TranslationUnitDecl *tunit =
2436 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2437 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002438 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002439 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002440}
2441
David Majnemerc729b0b2013-09-16 22:44:20 +00002442bool FunctionDecl::isMSVCRTEntryPoint() const {
2443 const TranslationUnitDecl *TUnit =
2444 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2445 if (!TUnit)
2446 return false;
2447
2448 // Even though we aren't really targeting MSVCRT if we are freestanding,
2449 // semantic analysis for these functions remains the same.
2450
2451 // MSVCRT entry points only exist on MSVCRT targets.
2452 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2453 return false;
2454
2455 // Nameless functions like constructors cannot be entry points.
2456 if (!getIdentifier())
2457 return false;
2458
2459 return llvm::StringSwitch<bool>(getName())
2460 .Cases("main", // an ANSI console app
2461 "wmain", // a Unicode console App
2462 "WinMain", // an ANSI GUI app
2463 "wWinMain", // a Unicode GUI app
2464 "DllMain", // a DLL
2465 true)
2466 .Default(false);
2467}
2468
John McCall53ffd372011-05-15 17:49:20 +00002469bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2470 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2471 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2472 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2473 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2474 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2475
Richard Smithf6004412014-01-19 23:25:37 +00002476 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2477 return false;
John McCall53ffd372011-05-15 17:49:20 +00002478
2479 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002480 if (proto->getNumParams() != 2 || proto->isVariadic())
2481 return false;
John McCall53ffd372011-05-15 17:49:20 +00002482
2483 ASTContext &Context =
2484 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2485 ->getASTContext();
2486
2487 // The result type and first argument type are constant across all
2488 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002489 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002490}
2491
Richard Smith8d0dc312013-07-21 23:12:18 +00002492bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2493 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2494 return false;
2495 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2496 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2497 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2498 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2499 return false;
2500
2501 if (isa<CXXRecordDecl>(getDeclContext()))
2502 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002503
2504 // This can only fail for an invalid 'operator new' declaration.
2505 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2506 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002507
2508 const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
Nick Lewycky6fb99b92014-06-07 00:43:57 +00002509 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 2 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002510 return false;
2511
2512 // If this is a single-parameter function, it must be a replaceable global
2513 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002514 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002515 return true;
2516
2517 // Otherwise, we're looking for a second parameter whose type is
Richard Smith1cdec012013-09-29 04:40:38 +00002518 // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
Alp Toker9cacbab2014-01-20 20:26:09 +00002519 QualType Ty = FPT->getParamType(1);
Richard Smith1cdec012013-09-29 04:40:38 +00002520 ASTContext &Ctx = getASTContext();
Richard Smithb47c36f2013-11-05 09:12:18 +00002521 if (Ctx.getLangOpts().SizedDeallocation &&
2522 Ctx.hasSameType(Ty, Ctx.getSizeType()))
Richard Smith1cdec012013-09-29 04:40:38 +00002523 return true;
Richard Smith8d0dc312013-07-21 23:12:18 +00002524 if (!Ty->isReferenceType())
2525 return false;
2526 Ty = Ty->getPointeeType();
2527 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2528 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002529 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Richard Trieuc771d5d2014-05-28 02:16:01 +00002530 return RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace();
Richard Smith8d0dc312013-07-21 23:12:18 +00002531}
2532
Rafael Espindolaf4187652013-02-14 01:18:37 +00002533LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00002534 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002535}
2536
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002537bool FunctionDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00002538 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002539}
2540
Rafael Espindola593537a2013-05-05 20:15:21 +00002541bool FunctionDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002542 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002543}
2544
2545bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002546 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002547}
2548
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002549bool FunctionDecl::isGlobal() const {
2550 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2551 return Method->isStatic();
2552
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002553 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002554 return false;
2555
Mike Stump11289f42009-09-09 15:08:12 +00002556 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002557 DC->isNamespace();
2558 DC = DC->getParent()) {
2559 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2560 if (!Namespace->getDeclName())
2561 return false;
2562 break;
2563 }
2564 }
2565
2566 return true;
2567}
2568
Richard Smith10876ef2013-01-17 01:30:42 +00002569bool FunctionDecl::isNoReturn() const {
2570 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
Richard Smithdebc59d2013-01-30 05:45:05 +00002571 hasAttr<C11NoReturnAttr>() ||
Richard Smith10876ef2013-01-17 01:30:42 +00002572 getType()->getAs<FunctionType>()->getNoReturnAttr();
2573}
2574
Sebastian Redl833ef452010-01-26 22:01:41 +00002575void
2576FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002577 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002578
2579 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2580 FunctionTemplateDecl *PrevFunTmpl
Craig Topper36250ad2014-05-12 05:36:57 +00002581 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002582 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00002583 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002584 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002585
Axel Naumannfbc7b982011-11-08 18:21:06 +00002586 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002587 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002588}
2589
Rafael Espindola8db352d2013-10-17 15:37:26 +00002590FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002591
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002592/// \brief Returns a value indicating whether this function
2593/// corresponds to a builtin function.
2594///
2595/// The function corresponds to a built-in function if it is
2596/// declared at translation scope or within an extern "C" block and
2597/// its name matches with the name of a builtin. The returned value
2598/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002599/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002600/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002601unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002602 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002603 return 0;
2604
2605 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002606 if (!BuiltinID)
2607 return 0;
2608
2609 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00002610 if (Context.getLangOpts().CPlusPlus) {
2611 const LinkageSpecDecl *LinkageDecl = dyn_cast<LinkageSpecDecl>(
2612 getFirstDecl()->getDeclContext());
2613 // In C++, the first declaration of a builtin is always inside an implicit
2614 // extern "C".
2615 // FIXME: A recognised library function may not be directly in an extern "C"
2616 // declaration, for instance "extern "C" { namespace std { decl } }".
David Majnemerba3e5ec2015-03-13 18:26:17 +00002617 if (!LinkageDecl) {
2618 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
2619 Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2620 isInStdNamespace())
2621 return Builtin::BI__GetExceptionInfo;
2622 return 0;
2623 }
2624 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
Warren Hunt445d83e2013-11-01 23:46:51 +00002625 return 0;
2626 }
2627
2628 // If the function is marked "overloadable", it has a different mangled name
2629 // and is not the C library function.
Aaron Ballman9ead1242013-12-19 02:39:40 +00002630 if (hasAttr<OverloadableAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00002631 return 0;
2632
Douglas Gregore711f702009-02-14 18:57:46 +00002633 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2634 return BuiltinID;
2635
2636 // This function has the name of a known C library
2637 // function. Determine whether it actually refers to the C library
2638 // function or whether it just has the same name.
2639
Douglas Gregora908e7f2009-02-17 03:23:10 +00002640 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002641 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002642 return 0;
2643
Warren Hunt445d83e2013-11-01 23:46:51 +00002644 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002645}
2646
2647
Chris Lattner47c0d002009-04-25 06:03:53 +00002648/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002649/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002650/// after it has been created.
2651unsigned FunctionDecl::getNumParams() const {
Reid Kleckner0503a872013-12-05 01:23:43 +00002652 const FunctionProtoType *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002653 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002654}
2655
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002656void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002657 ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00002658 assert(!ParamInfo && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002659 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002660
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002661 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002662 if (!NewParamInfo.empty()) {
2663 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2664 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002665 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002666}
Chris Lattner41943152007-01-25 04:52:46 +00002667
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002668void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
James Molloy6f8780b2012-02-29 10:24:19 +00002669 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2670
2671 if (!NewDecls.empty()) {
2672 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2673 std::copy(NewDecls.begin(), NewDecls.end(), A);
Craig Topper5fc8fc22014-08-27 06:28:36 +00002674 DeclsInPrototypeScope = llvm::makeArrayRef(A, NewDecls.size());
Serge Pavlova8261472014-06-25 17:09:41 +00002675 // Move declarations introduced in prototype to the function context.
2676 for (auto I : NewDecls) {
2677 DeclContext *DC = I->getDeclContext();
2678 // Forward-declared reference to an enumeration is not added to
2679 // declaration scope, so skip declaration that is absent from its
2680 // declaration contexts.
2681 if (DC->containsDecl(I)) {
2682 DC->removeDecl(I);
2683 I->setDeclContext(this);
2684 addDecl(I);
2685 }
2686 }
James Molloy6f8780b2012-02-29 10:24:19 +00002687 }
2688}
2689
Chris Lattner58258242008-04-10 02:22:51 +00002690/// getMinRequiredArguments - Returns the minimum number of arguments
2691/// needed to call this function. This may be fewer than the number of
2692/// function parameters, if some of the parameters have default
Richard Smith91151782014-04-01 19:18:16 +00002693/// arguments (in C++) or are parameter packs (C++11).
Chris Lattner58258242008-04-10 02:22:51 +00002694unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002695 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002696 return getNumParams();
Chris Lattner58258242008-04-10 02:22:51 +00002697
Richard Smith91151782014-04-01 19:18:16 +00002698 unsigned NumRequiredArgs = 0;
2699 for (auto *Param : params())
2700 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2701 ++NumRequiredArgs;
Chris Lattner58258242008-04-10 02:22:51 +00002702 return NumRequiredArgs;
2703}
2704
David Majnemer54e3ba52014-04-02 23:17:29 +00002705/// \brief The combination of the extern and inline keywords under MSVC forces
2706/// the function to be required.
2707///
2708/// Note: This function assumes that we will only get called when isInlined()
2709/// would return true for this FunctionDecl.
2710bool FunctionDecl::isMSExternInline() const {
2711 assert(isInlined() && "expected to get called on an inlined function!");
2712
2713 const ASTContext &Context = getASTContext();
Hans Wennborgb0f2f142014-05-15 22:07:49 +00002714 if (!Context.getLangOpts().MSVCCompat && !hasAttr<DLLExportAttr>())
David Majnemer54e3ba52014-04-02 23:17:29 +00002715 return false;
2716
David Majnemer73768702015-03-20 00:02:27 +00002717 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
2718 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002719 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002720 return true;
2721
2722 return false;
2723}
2724
2725static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
2726 if (Redecl->getStorageClass() != SC_Extern)
2727 return false;
2728
2729 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
2730 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002731 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002732 return false;
2733
2734 return true;
2735}
2736
Eli Friedman1b125c32012-02-07 03:50:18 +00002737static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2738 // Only consider file-scope declarations in this test.
2739 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2740 return false;
2741
2742 // Only consider explicit declarations; the presence of a builtin for a
2743 // libcall shouldn't affect whether a definition is externally visible.
2744 if (Redecl->isImplicit())
2745 return false;
2746
2747 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2748 return true; // Not an inline definition
2749
2750 return false;
2751}
2752
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002753/// \brief For a function declaration in C or C++, determine whether this
2754/// declaration causes the definition to be externally visible.
2755///
David Majnemer54e3ba52014-04-02 23:17:29 +00002756/// For instance, this determines if adding the current declaration to the set
Eli Friedman1b125c32012-02-07 03:50:18 +00002757/// of redeclarations of the given functions causes
2758/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002759bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2760 assert(!doesThisDeclarationHaveABody() &&
2761 "Must have a declaration without a body.");
2762
2763 ASTContext &Context = getASTContext();
2764
David Majnemer54e3ba52014-04-02 23:17:29 +00002765 if (Context.getLangOpts().MSVCCompat) {
2766 const FunctionDecl *Definition;
2767 if (hasBody(Definition) && Definition->isInlined() &&
2768 redeclForcesDefMSVC(this))
2769 return true;
2770 }
2771
David Blaikiebbafb8a2012-03-11 07:00:24 +00002772 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002773 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2774 // an externally visible definition.
2775 //
2776 // FIXME: What happens if gnu_inline gets added on after the first
2777 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002778 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002779 return false;
2780
2781 const FunctionDecl *Prev = this;
2782 bool FoundBody = false;
2783 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002784 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002785
2786 if (Prev->Body) {
2787 // If it's not the case that both 'inline' and 'extern' are
2788 // specified on the definition, then it is always externally visible.
2789 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002790 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002791 return false;
2792 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002793 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002794 return false;
2795 }
2796 }
2797 return FoundBody;
2798 }
2799
David Blaikiebbafb8a2012-03-11 07:00:24 +00002800 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002801 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002802
2803 // C99 6.7.4p6:
2804 // [...] If all of the file scope declarations for a function in a
2805 // translation unit include the inline function specifier without extern,
2806 // then the definition in that translation unit is an inline definition.
2807 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002808 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002809 const FunctionDecl *Prev = this;
2810 bool FoundBody = false;
2811 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002812 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002813 if (RedeclForcesDefC99(Prev))
2814 return false;
2815 }
2816 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002817}
2818
Alp Tokerd0787eb2014-07-02 01:47:15 +00002819SourceRange FunctionDecl::getReturnTypeSourceRange() const {
2820 const TypeSourceInfo *TSI = getTypeSourceInfo();
2821 if (!TSI)
2822 return SourceRange();
Alp Tokerf5b10792014-07-02 12:55:58 +00002823 FunctionTypeLoc FTL =
2824 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
2825 if (!FTL)
Alp Tokerd0787eb2014-07-02 01:47:15 +00002826 return SourceRange();
2827
Alp Tokerf5b10792014-07-02 12:55:58 +00002828 // Skip self-referential return types.
2829 const SourceManager &SM = getASTContext().getSourceManager();
2830 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
2831 SourceLocation Boundary = getNameInfo().getLocStart();
2832 if (RTRange.isInvalid() || Boundary.isInvalid() ||
2833 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
2834 return SourceRange();
Alp Tokerd0787eb2014-07-02 01:47:15 +00002835
Alp Tokerf5b10792014-07-02 12:55:58 +00002836 return RTRange;
Alp Tokerd0787eb2014-07-02 01:47:15 +00002837}
2838
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002839bool FunctionDecl::hasUnusedResultAttr() const {
2840 QualType RetType = getReturnType();
2841 if (RetType->isRecordType()) {
2842 const CXXRecordDecl *Ret = RetType->getAsCXXRecordDecl();
2843 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(this);
2844 if (Ret && Ret->hasAttr<WarnUnusedResultAttr>() &&
2845 !(MD && MD->getCorrespondingMethodInClass(Ret, true)))
2846 return true;
2847 }
2848 return hasAttr<WarnUnusedResultAttr>();
2849}
2850
Richard Smithf3814ad2013-01-25 00:08:28 +00002851/// \brief For an inline function definition in C, or for a gnu_inline function
2852/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002853///
2854/// Inline function definitions are always available for inlining optimizations.
2855/// However, depending on the language dialect, declaration specifiers, and
2856/// attributes, the definition of an inline function may or may not be
2857/// "externally" visible to other translation units in the program.
2858///
2859/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00002860/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00002861/// inline definition becomes externally visible (C99 6.7.4p6).
2862///
2863/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2864/// definition, we use the GNU semantics for inline, which are nearly the
2865/// opposite of C99 semantics. In particular, "inline" by itself will create
2866/// an externally visible symbol, but "extern inline" will not create an
2867/// externally visible symbol.
2868bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002869 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002870 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00002871 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00002872
David Blaikiebbafb8a2012-03-11 07:00:24 +00002873 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002874 // Note: If you change the logic here, please change
2875 // doesDeclarationForceExternallyVisibleDefinition as well.
2876 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00002877 // If it's not the case that both 'inline' and 'extern' are
2878 // specified on the definition, then this inline definition is
2879 // externally visible.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002880 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00002881 return true;
2882
2883 // If any declaration is 'inline' but not 'extern', then this definition
2884 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00002885 for (auto Redecl : redecls()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00002886 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002887 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00002888 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00002889 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00002890
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002891 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002892 }
Eli Friedman1b125c32012-02-07 03:50:18 +00002893
Richard Smithf3814ad2013-01-25 00:08:28 +00002894 // The rest of this function is C-only.
2895 assert(!Context.getLangOpts().CPlusPlus &&
2896 "should not use C inline rules in C++");
2897
Douglas Gregor299d76e2009-09-13 07:46:26 +00002898 // C99 6.7.4p6:
2899 // [...] If all of the file scope declarations for a function in a
2900 // translation unit include the inline function specifier without extern,
2901 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00002902 for (auto Redecl : redecls()) {
2903 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00002904 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002905 }
2906
2907 // C99 6.7.4p6:
2908 // An inline definition does not provide an external definition for the
2909 // function, and does not forbid an external definition in another
2910 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002911 return false;
2912}
2913
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002914/// getOverloadedOperator - Which C++ overloaded operator this
2915/// function represents, if any.
2916OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00002917 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2918 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002919 else
2920 return OO_None;
2921}
2922
Alexis Huntc88db062010-01-13 09:01:02 +00002923/// getLiteralIdentifier - The literal suffix identifier this function
2924/// represents, if any.
2925const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2926 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2927 return getDeclName().getCXXLiteralIdentifier();
2928 else
Craig Topper36250ad2014-05-12 05:36:57 +00002929 return nullptr;
Alexis Huntc88db062010-01-13 09:01:02 +00002930}
2931
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002932FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2933 if (TemplateOrSpecialization.isNull())
2934 return TK_NonTemplate;
2935 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2936 return TK_FunctionTemplate;
2937 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2938 return TK_MemberSpecialization;
2939 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2940 return TK_FunctionTemplateSpecialization;
2941 if (TemplateOrSpecialization.is
2942 <DependentFunctionTemplateSpecializationInfo*>())
2943 return TK_DependentFunctionTemplateSpecialization;
2944
David Blaikie83d382b2011-09-23 05:06:16 +00002945 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002946}
2947
Douglas Gregord801b062009-10-07 23:56:10 +00002948FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002949 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00002950 return cast<FunctionDecl>(Info->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002951
2952 return nullptr;
Douglas Gregord801b062009-10-07 23:56:10 +00002953}
2954
2955void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002956FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2957 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00002958 TemplateSpecializationKind TSK) {
2959 assert(TemplateOrSpecialization.isNull() &&
2960 "Member function is already a specialization");
2961 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002962 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00002963 TemplateOrSpecialization = Info;
2964}
2965
Douglas Gregorafca3b42009-10-27 20:53:28 +00002966bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00002967 // If the function is invalid, it can't be implicitly instantiated.
2968 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00002969 return false;
2970
2971 switch (getTemplateSpecializationKind()) {
2972 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00002973 case TSK_ExplicitInstantiationDefinition:
2974 return false;
2975
2976 case TSK_ImplicitInstantiation:
2977 return true;
2978
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002979 // It is possible to instantiate TSK_ExplicitSpecialization kind
2980 // if the FunctionDecl has a class scope specialization pattern.
2981 case TSK_ExplicitSpecialization:
Craig Topper36250ad2014-05-12 05:36:57 +00002982 return getClassScopeSpecializationPattern() != nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002983
Douglas Gregorafca3b42009-10-27 20:53:28 +00002984 case TSK_ExplicitInstantiationDeclaration:
2985 // Handled below.
2986 break;
2987 }
2988
2989 // Find the actual template from which we will instantiate.
2990 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002991 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00002992 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002993 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00002994
2995 // C++0x [temp.explicit]p9:
2996 // Except for inline functions, other explicit instantiation declarations
2997 // have the effect of suppressing the implicit instantiation of the entity
2998 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002999 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00003000 return true;
3001
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003002 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00003003}
3004
3005bool FunctionDecl::isTemplateInstantiation() const {
3006 switch (getTemplateSpecializationKind()) {
3007 case TSK_Undeclared:
3008 case TSK_ExplicitSpecialization:
3009 return false;
3010 case TSK_ImplicitInstantiation:
3011 case TSK_ExplicitInstantiationDeclaration:
3012 case TSK_ExplicitInstantiationDefinition:
3013 return true;
3014 }
3015 llvm_unreachable("All TSK values handled.");
3016}
Douglas Gregorafca3b42009-10-27 20:53:28 +00003017
3018FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003019 // Handle class scope explicit specialization special case.
3020 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3021 return getClassScopeSpecializationPattern();
Faisal Valib90b2112014-04-03 16:32:21 +00003022
3023 // If this is a generic lambda call operator specialization, its
3024 // instantiation pattern is always its primary template's pattern
3025 // even if its primary template was instantiated from another
3026 // member template (which happens with nested generic lambdas).
3027 // Since a lambda's call operator's body is transformed eagerly,
3028 // we don't have to go hunting for a prototype definition template
3029 // (i.e. instantiated-from-member-template) to use as an instantiation
3030 // pattern.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003031
Faisal Valib90b2112014-04-03 16:32:21 +00003032 if (isGenericLambdaCallOperatorSpecialization(
3033 dyn_cast<CXXMethodDecl>(this))) {
3034 assert(getPrimaryTemplate() && "A generic lambda specialization must be "
3035 "generated from a primary call operator "
3036 "template");
3037 assert(getPrimaryTemplate()->getTemplatedDecl()->getBody() &&
3038 "A generic lambda call operator template must always have a body - "
3039 "even if instantiated from a prototype (i.e. as written) member "
3040 "template");
3041 return getPrimaryTemplate()->getTemplatedDecl();
3042 }
3043
Douglas Gregorafca3b42009-10-27 20:53:28 +00003044 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3045 while (Primary->getInstantiatedFromMemberTemplate()) {
3046 // If we have hit a point where the user provided a specialization of
3047 // this template, we're done looking.
3048 if (Primary->isMemberSpecialization())
3049 break;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003050 Primary = Primary->getInstantiatedFromMemberTemplate();
3051 }
3052
3053 return Primary->getTemplatedDecl();
3054 }
3055
3056 return getInstantiatedFromMemberFunction();
3057}
3058
Douglas Gregor70d83e22009-06-29 17:30:29 +00003059FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00003060 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003061 = TemplateOrSpecialization
3062 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00003063 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00003064 }
Craig Topper36250ad2014-05-12 05:36:57 +00003065 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003066}
3067
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003068FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3069 return getASTContext().getClassScopeSpecializationPattern(this);
3070}
3071
Douglas Gregor70d83e22009-06-29 17:30:29 +00003072const TemplateArgumentList *
3073FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00003074 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00003075 = TemplateOrSpecialization
3076 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003077 return Info->TemplateArguments;
3078 }
Craig Topper36250ad2014-05-12 05:36:57 +00003079 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003080}
3081
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00003082const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003083FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3084 if (FunctionTemplateSpecializationInfo *Info
3085 = TemplateOrSpecialization
3086 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3087 return Info->TemplateArgumentsAsWritten;
3088 }
Craig Topper36250ad2014-05-12 05:36:57 +00003089 return nullptr;
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003090}
3091
Mike Stump11289f42009-09-09 15:08:12 +00003092void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003093FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3094 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003095 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003096 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003097 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00003098 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3099 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003100 assert(TSK != TSK_Undeclared &&
3101 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00003102 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003103 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003104 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00003105 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3106 TemplateArgs,
3107 TemplateArgsAsWritten,
3108 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003109 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00003110 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003111}
3112
John McCallb9c78482010-04-08 09:05:18 +00003113void
3114FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3115 const UnresolvedSetImpl &Templates,
3116 const TemplateArgumentListInfo &TemplateArgs) {
3117 assert(TemplateOrSpecialization.isNull());
3118 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
John McCall900d9802010-04-13 22:18:28 +00003119 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
James Y Knight53c76162015-07-17 18:21:37 +00003120 Size += Templates.size() * sizeof(FunctionTemplateDecl *);
John McCallb9c78482010-04-08 09:05:18 +00003121 void *Buffer = Context.Allocate(Size);
3122 DependentFunctionTemplateSpecializationInfo *Info =
3123 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
3124 TemplateArgs);
3125 TemplateOrSpecialization = Info;
3126}
3127
3128DependentFunctionTemplateSpecializationInfo::
3129DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3130 const TemplateArgumentListInfo &TArgs)
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003131 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
Benjamin Kramer1d4ffd72015-04-02 12:25:07 +00003132 static_assert(sizeof(*this) % llvm::AlignOf<void *>::Alignment == 0,
3133 "Trailing data is unaligned!");
John McCallb9c78482010-04-08 09:05:18 +00003134
James Y Knight53c76162015-07-17 18:21:37 +00003135 NumTemplates = Ts.size();
3136 NumArgs = TArgs.size();
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003137
John McCallb9c78482010-04-08 09:05:18 +00003138 FunctionTemplateDecl **TsArray =
3139 const_cast<FunctionTemplateDecl**>(getTemplates());
3140 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3141 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3142
3143 TemplateArgumentLoc *ArgsArray =
3144 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
3145 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3146 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3147}
3148
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003149TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00003150 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003151 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00003152 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00003153 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00003154 if (FTSInfo)
3155 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00003156
Douglas Gregord801b062009-10-07 23:56:10 +00003157 MemberSpecializationInfo *MSInfo
3158 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3159 if (MSInfo)
3160 return MSInfo->getTemplateSpecializationKind();
3161
3162 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003163}
3164
Mike Stump11289f42009-09-09 15:08:12 +00003165void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003166FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3167 SourceLocation PointOfInstantiation) {
3168 if (FunctionTemplateSpecializationInfo *FTSInfo
3169 = TemplateOrSpecialization.dyn_cast<
3170 FunctionTemplateSpecializationInfo*>()) {
3171 FTSInfo->setTemplateSpecializationKind(TSK);
3172 if (TSK != TSK_ExplicitSpecialization &&
3173 PointOfInstantiation.isValid() &&
3174 FTSInfo->getPointOfInstantiation().isInvalid())
3175 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3176 } else if (MemberSpecializationInfo *MSInfo
3177 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3178 MSInfo->setTemplateSpecializationKind(TSK);
3179 if (TSK != TSK_ExplicitSpecialization &&
3180 PointOfInstantiation.isValid() &&
3181 MSInfo->getPointOfInstantiation().isInvalid())
3182 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3183 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003184 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003185}
3186
3187SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00003188 if (FunctionTemplateSpecializationInfo *FTSInfo
3189 = TemplateOrSpecialization.dyn_cast<
3190 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003191 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00003192 else if (MemberSpecializationInfo *MSInfo
3193 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003194 return MSInfo->getPointOfInstantiation();
3195
3196 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00003197}
3198
Douglas Gregor6411b922009-09-11 20:15:17 +00003199bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00003200 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00003201 return true;
3202
3203 // If this function was instantiated from a member function of a
3204 // class template, check whether that member function was defined out-of-line.
3205 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3206 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003207 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003208 return Definition->isOutOfLine();
3209 }
3210
3211 // If this function was instantiated from a function template,
3212 // check whether that function template was defined out-of-line.
3213 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3214 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003215 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003216 return Definition->isOutOfLine();
3217 }
3218
3219 return false;
3220}
3221
Abramo Bagnaraea947882011-03-08 16:41:52 +00003222SourceRange FunctionDecl::getSourceRange() const {
3223 return SourceRange(getOuterLocStart(), EndRangeLoc);
3224}
3225
Anna Zaks28db7ce2012-01-18 02:45:01 +00003226unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00003227 IdentifierInfo *FnInfo = getIdentifier();
3228
3229 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00003230 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003231
3232 // Builtin handling.
3233 switch (getBuiltinID()) {
3234 case Builtin::BI__builtin_memset:
3235 case Builtin::BI__builtin___memset_chk:
3236 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003237 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003238
3239 case Builtin::BI__builtin_memcpy:
3240 case Builtin::BI__builtin___memcpy_chk:
3241 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003242 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003243
3244 case Builtin::BI__builtin_memmove:
3245 case Builtin::BI__builtin___memmove_chk:
3246 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003247 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003248
3249 case Builtin::BIstrlcpy:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003250 case Builtin::BI__builtin___strlcpy_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003251 return Builtin::BIstrlcpy;
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003252
Anna Zaks201d4892012-01-13 21:52:01 +00003253 case Builtin::BIstrlcat:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003254 case Builtin::BI__builtin___strlcat_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003255 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003256
3257 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003258 case Builtin::BImemcmp:
3259 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003260
3261 case Builtin::BI__builtin_strncpy:
3262 case Builtin::BI__builtin___strncpy_chk:
3263 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003264 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003265
3266 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003267 case Builtin::BIstrncmp:
3268 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003269
3270 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003271 case Builtin::BIstrncasecmp:
3272 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003273
3274 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003275 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003276 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003277 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003278
3279 case Builtin::BI__builtin_strndup:
3280 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003281 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003282
Anna Zaks314cd092012-02-01 19:08:57 +00003283 case Builtin::BI__builtin_strlen:
3284 case Builtin::BIstrlen:
3285 return Builtin::BIstrlen;
3286
Anna Zaks201d4892012-01-13 21:52:01 +00003287 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003288 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003289 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003290 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003291 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003292 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003293 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003294 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003295 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003296 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003297 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003298 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003299 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003300 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003301 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003302 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003303 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003304 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003305 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003306 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003307 else if (FnInfo->isStr("strlen"))
3308 return Builtin::BIstrlen;
Anna Zaks201d4892012-01-13 21:52:01 +00003309 }
3310 break;
3311 }
Anna Zaks22122702012-01-17 00:37:07 +00003312 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003313}
3314
Chris Lattner59a25942008-03-31 00:36:02 +00003315//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003316// FieldDecl Implementation
3317//===----------------------------------------------------------------------===//
3318
Jay Foad39c79802011-01-12 09:06:06 +00003319FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003320 SourceLocation StartLoc, SourceLocation IdLoc,
3321 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003322 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003323 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003324 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3325 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003326}
3327
Douglas Gregor72172e92012-01-05 21:55:30 +00003328FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003329 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3330 SourceLocation(), nullptr, QualType(), nullptr,
3331 nullptr, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00003332}
3333
Sebastian Redl833ef452010-01-26 22:01:41 +00003334bool FieldDecl::isAnonymousStructOrUnion() const {
3335 if (!isImplicit() || getDeclName())
3336 return false;
3337
3338 if (const RecordType *Record = getType()->getAs<RecordType>())
3339 return Record->getDecl()->isAnonymousStructOrUnion();
3340
3341 return false;
3342}
3343
Richard Smithcaf33902011-10-10 18:28:20 +00003344unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3345 assert(isBitField() && "not a bitfield");
John McCallc90c1492014-10-10 18:44:34 +00003346 Expr *BitWidth = static_cast<Expr *>(InitStorage.getPointer());
Richard Smithcaf33902011-10-10 18:28:20 +00003347 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3348}
3349
John McCall4e819612011-01-20 07:57:12 +00003350unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00003351 const FieldDecl *Canonical = getCanonicalDecl();
3352 if (Canonical != this)
3353 return Canonical->getFieldIndex();
3354
John McCall4e819612011-01-20 07:57:12 +00003355 if (CachedFieldIndex) return CachedFieldIndex - 1;
3356
Richard Smithd62306a2011-11-10 06:34:14 +00003357 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00003358 const RecordDecl *RD = getParent();
Richard Smithd62306a2011-11-10 06:34:14 +00003359
Hans Wennborga302cd92014-08-21 16:06:57 +00003360 for (auto *Field : RD->fields()) {
3361 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3362 ++Index;
3363 }
John McCall4e819612011-01-20 07:57:12 +00003364
Richard Smithd62306a2011-11-10 06:34:14 +00003365 assert(CachedFieldIndex && "failed to find field in parent");
3366 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00003367}
3368
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003369SourceRange FieldDecl::getSourceRange() const {
John McCallc90c1492014-10-10 18:44:34 +00003370 switch (InitStorage.getInt()) {
3371 // All three of these cases store an optional Expr*.
3372 case ISK_BitWidthOrNothing:
3373 case ISK_InClassCopyInit:
3374 case ISK_InClassListInit:
3375 if (const Expr *E = static_cast<const Expr *>(InitStorage.getPointer()))
3376 return SourceRange(getInnerLocStart(), E->getLocEnd());
3377 // FALLTHROUGH
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003378
John McCallc90c1492014-10-10 18:44:34 +00003379 case ISK_CapturedVLAType:
3380 return DeclaratorDecl::getSourceRange();
3381 }
3382 llvm_unreachable("bad init storage kind");
Alexey Bataev39c81e22014-08-28 04:28:19 +00003383}
3384
3385void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
David Blaikie11ab0782014-10-31 17:18:09 +00003386 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
Alexey Bataev330de032014-10-29 12:21:55 +00003387 "capturing type in non-lambda or captured record.");
John McCallc90c1492014-10-10 18:44:34 +00003388 assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
3389 InitStorage.getPointer() == nullptr &&
Alexey Bataev39c81e22014-08-28 04:28:19 +00003390 "bit width, initializer or captured type already set");
John McCallc90c1492014-10-10 18:44:34 +00003391 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3392 ISK_CapturedVLAType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00003393}
3394
Sebastian Redl833ef452010-01-26 22:01:41 +00003395//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003396// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00003397//===----------------------------------------------------------------------===//
3398
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003399SourceLocation TagDecl::getOuterLocStart() const {
3400 return getTemplateOrInnerLocStart(this);
3401}
3402
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003403SourceRange TagDecl::getSourceRange() const {
3404 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003405 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003406}
3407
Rafael Espindola8db352d2013-10-17 15:37:26 +00003408TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00003409
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00003410void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer50ce8352013-09-17 23:57:10 +00003411 NamedDeclOrQualifier = TDD;
Reid Klecknercae82a22014-04-23 22:03:04 +00003412 if (const Type *T = getTypeForDecl()) {
3413 (void)T;
Richard Smith5b21db82014-04-23 18:20:42 +00003414 assert(T->isLinkageValid());
Reid Klecknercae82a22014-04-23 22:03:04 +00003415 }
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003416 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00003417}
3418
Douglas Gregordee1be82009-01-17 00:42:38 +00003419void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003420 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00003421
David Blaikie095deba2012-11-14 01:52:05 +00003422 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
Richard Smith053f6c62014-05-16 23:01:30 +00003423 struct CXXRecordDecl::DefinitionData *Data =
John McCall67da35c2010-02-04 22:26:26 +00003424 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00003425 for (auto I : redecls())
Richard Smith64c06302014-05-22 23:19:02 +00003426 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00003427 }
Douglas Gregordee1be82009-01-17 00:42:38 +00003428}
3429
3430void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00003431 assert((!isa<CXXRecordDecl>(this) ||
3432 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3433 "definition completed but not started");
3434
John McCallf937c022011-10-07 06:10:15 +00003435 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003436 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00003437
3438 if (ASTMutationListener *L = getASTMutationListener())
3439 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00003440}
3441
John McCallf937c022011-10-07 06:10:15 +00003442TagDecl *TagDecl::getDefinition() const {
3443 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003444 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003445
3446 // If it's possible for us to have an out-of-date definition, check now.
3447 if (MayHaveOutOfDateDef) {
3448 if (IdentifierInfo *II = getIdentifier()) {
3449 if (II->isOutOfDate()) {
3450 updateOutOfDate(*II);
3451 }
3452 }
3453 }
3454
Andrew Trickba266ee2010-10-19 21:54:32 +00003455 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
3456 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003457
Aaron Ballman86c93902014-03-06 23:45:36 +00003458 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00003459 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00003460 return R;
Mike Stump11289f42009-09-09 15:08:12 +00003461
Craig Topper36250ad2014-05-12 05:36:57 +00003462 return nullptr;
Ted Kremenek21475702008-09-05 17:16:31 +00003463}
3464
Douglas Gregor14454802011-02-25 02:25:35 +00003465void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3466 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00003467 // Make sure the extended qualifier info is allocated.
3468 if (!hasExtInfo())
David Majnemer50ce8352013-09-17 23:57:10 +00003469 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00003470 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00003471 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003472 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00003473 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00003474 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00003475 if (getExtInfo()->NumTemplParamLists == 0) {
3476 getASTContext().Deallocate(getExtInfo());
Craig Topper36250ad2014-05-12 05:36:57 +00003477 NamedDeclOrQualifier = (TypedefNameDecl*)nullptr;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003478 }
3479 else
3480 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00003481 }
3482 }
3483}
3484
Abramo Bagnara60804e12011-03-18 15:16:37 +00003485void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
3486 unsigned NumTPLists,
3487 TemplateParameterList **TPLists) {
3488 assert(NumTPLists > 0);
3489 // Make sure the extended decl info is allocated.
3490 if (!hasExtInfo())
3491 // Allocate external info struct.
David Majnemer50ce8352013-09-17 23:57:10 +00003492 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003493 // Set the template parameter lists info.
3494 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
3495}
3496
Ted Kremenek21475702008-09-05 17:16:31 +00003497//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003498// EnumDecl Implementation
3499//===----------------------------------------------------------------------===//
3500
David Blaikie68e081d2011-12-20 02:48:34 +00003501void EnumDecl::anchor() { }
3502
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003503EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3504 SourceLocation StartLoc, SourceLocation IdLoc,
3505 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00003506 EnumDecl *PrevDecl, bool IsScoped,
3507 bool IsScopedUsingClassTag, bool IsFixed) {
Richard Smith053f6c62014-05-16 23:01:30 +00003508 EnumDecl *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
Richard Smithf7981722013-11-22 09:01:48 +00003509 IsScoped, IsScopedUsingClassTag,
3510 IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003511 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00003512 C.getTypeDeclType(Enum, PrevDecl);
3513 return Enum;
3514}
3515
Douglas Gregor72172e92012-01-05 21:55:30 +00003516EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003517 EnumDecl *Enum =
3518 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3519 nullptr, nullptr, false, false, false);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003520 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3521 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003522}
3523
Alp Tokerb9fa5122014-01-06 11:31:18 +00003524SourceRange EnumDecl::getIntegerTypeRange() const {
3525 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3526 return TI->getTypeLoc().getSourceRange();
3527 return SourceRange();
3528}
3529
Douglas Gregord5058122010-02-11 01:19:42 +00003530void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00003531 QualType NewPromotionType,
3532 unsigned NumPositiveBits,
3533 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00003534 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00003535 if (!IntegerType)
3536 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00003537 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00003538 setNumPositiveBits(NumPositiveBits);
3539 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00003540 TagDecl::completeDefinition();
3541}
3542
Richard Smith7d137e32012-03-23 03:33:32 +00003543TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3544 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3545 return MSI->getTemplateSpecializationKind();
3546
3547 return TSK_Undeclared;
3548}
3549
3550void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3551 SourceLocation PointOfInstantiation) {
3552 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3553 assert(MSI && "Not an instantiated member enumeration?");
3554 MSI->setTemplateSpecializationKind(TSK);
3555 if (TSK != TSK_ExplicitSpecialization &&
3556 PointOfInstantiation.isValid() &&
3557 MSI->getPointOfInstantiation().isInvalid())
3558 MSI->setPointOfInstantiation(PointOfInstantiation);
3559}
3560
Richard Smith4b38ded2012-03-14 23:13:10 +00003561EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3562 if (SpecializationInfo)
3563 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3564
Craig Topper36250ad2014-05-12 05:36:57 +00003565 return nullptr;
Richard Smith4b38ded2012-03-14 23:13:10 +00003566}
3567
3568void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3569 TemplateSpecializationKind TSK) {
3570 assert(!SpecializationInfo && "Member enum is already a specialization");
3571 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3572}
3573
Sebastian Redl833ef452010-01-26 22:01:41 +00003574//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003575// RecordDecl Implementation
3576//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003577
Richard Smith053f6c62014-05-16 23:01:30 +00003578RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3579 DeclContext *DC, SourceLocation StartLoc,
3580 SourceLocation IdLoc, IdentifierInfo *Id,
3581 RecordDecl *PrevDecl)
3582 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003583 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003584 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003585 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00003586 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003587 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00003588 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003589}
3590
Jay Foad39c79802011-01-12 09:06:06 +00003591RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003592 SourceLocation StartLoc, SourceLocation IdLoc,
3593 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smith053f6c62014-05-16 23:01:30 +00003594 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
3595 StartLoc, IdLoc, Id, PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003596 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3597
Ted Kremenek21475702008-09-05 17:16:31 +00003598 C.getTypeDeclType(R, PrevDecl);
3599 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003600}
3601
Douglas Gregor72172e92012-01-05 21:55:30 +00003602RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003603 RecordDecl *R =
3604 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
3605 SourceLocation(), nullptr, nullptr);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003606 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3607 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003608}
3609
Douglas Gregordfcad112009-03-25 15:59:44 +00003610bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003611 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003612 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3613}
3614
Alexey Bataev39c81e22014-08-28 04:28:19 +00003615bool RecordDecl::isLambda() const {
3616 if (auto RD = dyn_cast<CXXRecordDecl>(this))
3617 return RD->isLambda();
3618 return false;
3619}
3620
Alexey Bataev330de032014-10-29 12:21:55 +00003621bool RecordDecl::isCapturedRecord() const {
3622 return hasAttr<CapturedRecordAttr>();
3623}
3624
3625void RecordDecl::setCapturedRecord() {
3626 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
3627}
3628
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003629RecordDecl::field_iterator RecordDecl::field_begin() const {
3630 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3631 LoadFieldsFromExternalStorage();
3632
3633 return field_iterator(decl_iterator(FirstDecl));
3634}
3635
Douglas Gregorb11aad82011-02-19 18:51:44 +00003636/// completeDefinition - Notes that the definition of this type is now
3637/// complete.
3638void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003639 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003640 TagDecl::completeDefinition();
3641}
3642
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003643/// isMsStruct - Get whether or not this record uses ms_struct layout.
3644/// This which can be turned on with an attribute, pragma, or the
3645/// -mms-bitfields command-line option.
3646bool RecordDecl::isMsStruct(const ASTContext &C) const {
David Majnemer8ab003a2015-02-02 19:30:52 +00003647 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003648}
3649
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003650static bool isFieldOrIndirectField(Decl::Kind K) {
3651 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3652}
3653
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003654void RecordDecl::LoadFieldsFromExternalStorage() const {
3655 ExternalASTSource *Source = getASTContext().getExternalSource();
3656 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3657
3658 // Notify that we have a RecordDecl doing some initialization.
3659 ExternalASTSource::Deserializing TheFields(Source);
3660
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003661 SmallVector<Decl*, 64> Decls;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003662 LoadedFieldsFromExternalStorage = true;
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003663 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3664 Decls)) {
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003665 case ELR_Success:
3666 break;
3667
3668 case ELR_AlreadyLoaded:
3669 case ELR_Failure:
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003670 return;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003671 }
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003672
3673#ifndef NDEBUG
3674 // Check that all decls we got were FieldDecls.
3675 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003676 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003677#endif
3678
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003679 if (Decls.empty())
3680 return;
3681
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003682 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003683 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003684}
3685
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003686bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
3687 ASTContext &Context = getASTContext();
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00003688 if (!Context.getLangOpts().Sanitize.hasOneOf(
3689 SanitizerKind::Address | SanitizerKind::KernelAddress) ||
Alexey Samsonova0416102014-11-11 01:26:14 +00003690 !Context.getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003691 return false;
Alexey Samsonov33e00e22014-10-16 23:50:26 +00003692 const auto &Blacklist = Context.getSanitizerBlacklist();
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003693 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003694 // We may be able to relax some of these requirements.
3695 int ReasonToReject = -1;
3696 if (!CXXRD || CXXRD->isExternCContext())
3697 ReasonToReject = 0; // is not C++.
3698 else if (CXXRD->hasAttr<PackedAttr>())
3699 ReasonToReject = 1; // is packed.
3700 else if (CXXRD->isUnion())
3701 ReasonToReject = 2; // is a union.
3702 else if (CXXRD->isTriviallyCopyable())
3703 ReasonToReject = 3; // is trivially copyable.
3704 else if (CXXRD->hasTrivialDestructor())
3705 ReasonToReject = 4; // has trivial destructor.
3706 else if (CXXRD->isStandardLayout())
3707 ReasonToReject = 5; // is standard layout.
Alexey Samsonov33e00e22014-10-16 23:50:26 +00003708 else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003709 ReasonToReject = 6; // is in a blacklisted file.
3710 else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(),
3711 "field-padding"))
3712 ReasonToReject = 7; // is blacklisted.
3713
3714 if (EmitRemark) {
3715 if (ReasonToReject >= 0)
3716 Context.getDiagnostics().Report(
3717 getLocation(),
3718 diag::remark_sanitize_address_insert_extra_padding_rejected)
3719 << getQualifiedNameAsString() << ReasonToReject;
3720 else
3721 Context.getDiagnostics().Report(
3722 getLocation(),
3723 diag::remark_sanitize_address_insert_extra_padding_accepted)
3724 << getQualifiedNameAsString();
3725 }
3726 return ReasonToReject < 0;
3727}
3728
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003729const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
3730 for (const auto *I : fields()) {
3731 if (I->getIdentifier())
3732 return I;
3733
3734 if (const RecordType *RT = I->getType()->getAs<RecordType>())
3735 if (const FieldDecl *NamedDataMember =
3736 RT->getDecl()->findFirstNamedDataMember())
3737 return NamedDataMember;
3738 }
3739
3740 // We didn't find a named data member.
3741 return nullptr;
3742}
3743
3744
Steve Naroff415d3d52008-10-08 17:01:13 +00003745//===----------------------------------------------------------------------===//
3746// BlockDecl Implementation
3747//===----------------------------------------------------------------------===//
3748
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003749void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00003750 assert(!ParamInfo && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00003751
Steve Naroffc4b30e52009-03-13 16:56:44 +00003752 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003753 if (!NewParamInfo.empty()) {
3754 NumParams = NewParamInfo.size();
3755 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3756 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003757 }
3758}
3759
John McCall351762c2011-02-07 10:33:21 +00003760void BlockDecl::setCaptures(ASTContext &Context,
3761 const Capture *begin,
3762 const Capture *end,
3763 bool capturesCXXThis) {
John McCallc63de662011-02-02 13:00:07 +00003764 CapturesCXXThis = capturesCXXThis;
3765
3766 if (begin == end) {
John McCall351762c2011-02-07 10:33:21 +00003767 NumCaptures = 0;
Craig Topper36250ad2014-05-12 05:36:57 +00003768 Captures = nullptr;
John McCallc63de662011-02-02 13:00:07 +00003769 return;
3770 }
3771
John McCall351762c2011-02-07 10:33:21 +00003772 NumCaptures = end - begin;
3773
3774 // Avoid new Capture[] because we don't want to provide a default
3775 // constructor.
3776 size_t allocationSize = NumCaptures * sizeof(Capture);
3777 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3778 memcpy(buffer, begin, allocationSize);
3779 Captures = static_cast<Capture*>(buffer);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003780}
Sebastian Redl833ef452010-01-26 22:01:41 +00003781
John McCallce45f882011-06-15 22:51:16 +00003782bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00003783 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00003784 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00003785 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00003786 return true;
3787
3788 return false;
3789}
3790
Douglas Gregor70226da2010-12-21 16:27:07 +00003791SourceRange BlockDecl::getSourceRange() const {
3792 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3793}
Sebastian Redl833ef452010-01-26 22:01:41 +00003794
3795//===----------------------------------------------------------------------===//
3796// Other Decl Allocation/Deallocation Method Implementations
3797//===----------------------------------------------------------------------===//
3798
David Blaikie68e081d2011-12-20 02:48:34 +00003799void TranslationUnitDecl::anchor() { }
3800
Sebastian Redl833ef452010-01-26 22:01:41 +00003801TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Craig Topper36250ad2014-05-12 05:36:57 +00003802 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00003803}
3804
Richard Smithf19e1272015-03-07 00:04:49 +00003805void ExternCContextDecl::anchor() { }
3806
3807ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
3808 TranslationUnitDecl *DC) {
3809 return new (C, DC) ExternCContextDecl(DC);
3810}
3811
David Blaikie68e081d2011-12-20 02:48:34 +00003812void LabelDecl::anchor() { }
3813
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003814LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003815 SourceLocation IdentL, IdentifierInfo *II) {
Craig Topper36250ad2014-05-12 05:36:57 +00003816 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003817}
3818
3819LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3820 SourceLocation IdentL, IdentifierInfo *II,
3821 SourceLocation GnuLabelL) {
3822 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Craig Topper36250ad2014-05-12 05:36:57 +00003823 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003824}
3825
Douglas Gregor72172e92012-01-05 21:55:30 +00003826LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003827 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
3828 SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00003829}
3830
Ehsan Akhgari31097582014-09-22 02:21:54 +00003831void LabelDecl::setMSAsmLabel(StringRef Name) {
3832 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
3833 memcpy(Buffer, Name.data(), Name.size());
3834 Buffer[Name.size()] = '\0';
3835 MSAsmName = Buffer;
3836}
3837
David Blaikie68e081d2011-12-20 02:48:34 +00003838void ValueDecl::anchor() { }
3839
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003840bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00003841 for (const auto *I : attrs())
3842 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003843 return true;
3844
3845 return isWeakImported();
3846}
3847
David Blaikie68e081d2011-12-20 02:48:34 +00003848void ImplicitParamDecl::anchor() { }
3849
Sebastian Redl833ef452010-01-26 22:01:41 +00003850ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003851 SourceLocation IdLoc,
3852 IdentifierInfo *Id,
3853 QualType Type) {
Richard Smith053f6c62014-05-16 23:01:30 +00003854 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00003855}
3856
Richard Smithf7981722013-11-22 09:01:48 +00003857ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00003858 unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003859 return new (C, ID) ImplicitParamDecl(C, nullptr, SourceLocation(), nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00003860 QualType());
Douglas Gregor72172e92012-01-05 21:55:30 +00003861}
3862
Sebastian Redl833ef452010-01-26 22:01:41 +00003863FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003864 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003865 const DeclarationNameInfo &NameInfo,
3866 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003867 StorageClass SC,
Richard Smithf7981722013-11-22 09:01:48 +00003868 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00003869 bool hasWrittenPrototype,
3870 bool isConstexprSpecified) {
Richard Smithf7981722013-11-22 09:01:48 +00003871 FunctionDecl *New =
Richard Smith053f6c62014-05-16 23:01:30 +00003872 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
3873 SC, isInlineSpecified, isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00003874 New->HasWrittenPrototype = hasWrittenPrototype;
3875 return New;
3876}
3877
Douglas Gregor72172e92012-01-05 21:55:30 +00003878FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003879 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00003880 DeclarationNameInfo(), QualType(), nullptr,
Richard Smithf7981722013-11-22 09:01:48 +00003881 SC_None, false, false);
Douglas Gregor72172e92012-01-05 21:55:30 +00003882}
3883
Sebastian Redl833ef452010-01-26 22:01:41 +00003884BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00003885 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00003886}
3887
Douglas Gregor72172e92012-01-05 21:55:30 +00003888BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003889 return new (C, ID) BlockDecl(nullptr, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00003890}
3891
Ben Langmuir37943a72013-05-03 19:00:33 +00003892CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
3893 unsigned NumParams) {
Richard Smithf7981722013-11-22 09:01:48 +00003894 return new (C, DC, NumParams * sizeof(ImplicitParamDecl *))
3895 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003896}
3897
Ben Langmuirce914fc2013-05-03 19:20:19 +00003898CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00003899 unsigned NumParams) {
3900 return new (C, ID, NumParams * sizeof(ImplicitParamDecl *))
Craig Topper36250ad2014-05-12 05:36:57 +00003901 CapturedDecl(nullptr, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00003902}
3903
Sebastian Redl833ef452010-01-26 22:01:41 +00003904EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3905 SourceLocation L,
3906 IdentifierInfo *Id, QualType T,
3907 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00003908 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00003909}
3910
Douglas Gregor72172e92012-01-05 21:55:30 +00003911EnumConstantDecl *
3912EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003913 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
3914 QualType(), nullptr, llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00003915}
3916
David Blaikie68e081d2011-12-20 02:48:34 +00003917void IndirectFieldDecl::anchor() { }
3918
Benjamin Kramer39593702010-11-21 14:11:41 +00003919IndirectFieldDecl *
3920IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3921 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3922 unsigned CHS) {
Richard Smithf7981722013-11-22 09:01:48 +00003923 return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003924}
3925
Douglas Gregor72172e92012-01-05 21:55:30 +00003926IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3927 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003928 return new (C, ID) IndirectFieldDecl(nullptr, SourceLocation(),
3929 DeclarationName(), QualType(), nullptr,
3930 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00003931}
3932
Douglas Gregorbe996932010-09-01 20:41:53 +00003933SourceRange EnumConstantDecl::getSourceRange() const {
3934 SourceLocation End = getLocation();
3935 if (Init)
3936 End = Init->getLocEnd();
3937 return SourceRange(getLocation(), End);
3938}
3939
David Blaikie68e081d2011-12-20 02:48:34 +00003940void TypeDecl::anchor() { }
3941
Sebastian Redl833ef452010-01-26 22:01:41 +00003942TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003943 SourceLocation StartLoc, SourceLocation IdLoc,
3944 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00003945 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00003946}
3947
David Blaikie68e081d2011-12-20 02:48:34 +00003948void TypedefNameDecl::anchor() { }
3949
Richard Smith42413142015-05-15 20:05:43 +00003950TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
3951 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
3952 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
3953 auto *ThisTypedef = this;
3954 if (AnyRedecl && OwningTypedef) {
3955 OwningTypedef = OwningTypedef->getCanonicalDecl();
3956 ThisTypedef = ThisTypedef->getCanonicalDecl();
3957 }
3958 if (OwningTypedef == ThisTypedef)
Richard Smitha5230222015-03-27 01:37:43 +00003959 return TT->getDecl();
Richard Smith42413142015-05-15 20:05:43 +00003960 }
Richard Smitha5230222015-03-27 01:37:43 +00003961
3962 return nullptr;
3963}
3964
Douglas Gregor72172e92012-01-05 21:55:30 +00003965TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003966 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00003967 nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00003968}
3969
Richard Smithdda56e42011-04-15 14:24:37 +00003970TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3971 SourceLocation StartLoc,
3972 SourceLocation IdLoc, IdentifierInfo *Id,
3973 TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00003974 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00003975}
3976
Douglas Gregor72172e92012-01-05 21:55:30 +00003977TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003978 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
3979 SourceLocation(), nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00003980}
3981
Abramo Bagnaraea947882011-03-08 16:41:52 +00003982SourceRange TypedefDecl::getSourceRange() const {
3983 SourceLocation RangeEnd = getLocation();
3984 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3985 if (typeIsPostfix(TInfo->getType()))
3986 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3987 }
3988 return SourceRange(getLocStart(), RangeEnd);
3989}
3990
Richard Smithdda56e42011-04-15 14:24:37 +00003991SourceRange TypeAliasDecl::getSourceRange() const {
3992 SourceLocation RangeEnd = getLocStart();
3993 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3994 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3995 return SourceRange(getLocStart(), RangeEnd);
3996}
3997
David Blaikie68e081d2011-12-20 02:48:34 +00003998void FileScopeAsmDecl::anchor() { }
3999
Sebastian Redl833ef452010-01-26 22:01:41 +00004000FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00004001 StringLiteral *Str,
4002 SourceLocation AsmLoc,
4003 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00004004 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00004005}
Douglas Gregorba345522011-12-02 23:23:56 +00004006
Richard Smithf7981722013-11-22 09:01:48 +00004007FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004008 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004009 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4010 SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00004011}
4012
Michael Han84324352013-02-22 17:15:32 +00004013void EmptyDecl::anchor() {}
4014
4015EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004016 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00004017}
4018
4019EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004020 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00004021}
4022
Douglas Gregorba345522011-12-02 23:23:56 +00004023//===----------------------------------------------------------------------===//
4024// ImportDecl Implementation
4025//===----------------------------------------------------------------------===//
4026
4027/// \brief Retrieve the number of module identifiers needed to name the given
4028/// module.
4029static unsigned getNumModuleIdentifiers(Module *Mod) {
4030 unsigned Result = 1;
4031 while (Mod->Parent) {
4032 Mod = Mod->Parent;
4033 ++Result;
4034 }
4035 return Result;
4036}
4037
Douglas Gregor22d09742012-01-03 18:04:46 +00004038ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004039 Module *Imported,
4040 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00004041 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00004042 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00004043{
4044 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
4045 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
4046 memcpy(StoredLocs, IdentifierLocs.data(),
4047 IdentifierLocs.size() * sizeof(SourceLocation));
4048}
4049
Douglas Gregor22d09742012-01-03 18:04:46 +00004050ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004051 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00004052 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00004053 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00004054{
4055 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
4056}
4057
Richard Smithf7981722013-11-22 09:01:48 +00004058ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004059 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004060 ArrayRef<SourceLocation> IdentifierLocs) {
Richard Smithf7981722013-11-22 09:01:48 +00004061 return new (C, DC, IdentifierLocs.size() * sizeof(SourceLocation))
4062 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004063}
4064
Richard Smithf7981722013-11-22 09:01:48 +00004065ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004066 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00004067 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004068 SourceLocation EndLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00004069 ImportDecl *Import =
4070 new (C, DC, sizeof(SourceLocation)) ImportDecl(DC, StartLoc,
4071 Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00004072 Import->setImplicit();
4073 return Import;
4074}
4075
Douglas Gregor72172e92012-01-05 21:55:30 +00004076ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4077 unsigned NumLocations) {
Richard Smithf7981722013-11-22 09:01:48 +00004078 return new (C, ID, NumLocations * sizeof(SourceLocation))
4079 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00004080}
4081
4082ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4083 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004084 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00004085
4086 const SourceLocation *StoredLocs
4087 = reinterpret_cast<const SourceLocation *>(this + 1);
Craig Topper5fc8fc22014-08-27 06:28:36 +00004088 return llvm::makeArrayRef(StoredLocs,
4089 getNumModuleIdentifiers(getImportedModule()));
Douglas Gregorba345522011-12-02 23:23:56 +00004090}
4091
4092SourceRange ImportDecl::getSourceRange() const {
4093 if (!ImportedAndComplete.getInt())
4094 return SourceRange(getLocation(),
4095 *reinterpret_cast<const SourceLocation *>(this + 1));
4096
4097 return SourceRange(getLocation(), getIdentifierLocs().back());
4098}