blob: e330e31d47feb6cf570afd548946510211290bd1 [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"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000021#include "clang/AST/DeclOpenMP.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/AST/DeclTemplate.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000023#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000024#include "clang/AST/ExprCXX.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000025#include "clang/AST/PrettyPrinter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000026#include "clang/AST/Stmt.h"
27#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000028#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000029#include "clang/Basic/IdentifierTable.h"
Douglas Gregorba345522011-12-02 23:23:56 +000030#include "clang/Basic/Module.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000031#include "clang/Basic/Specifiers.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000032#include "clang/Basic/TargetInfo.h"
Kostya Serebryany293dc9b2014-10-16 20:54:52 +000033#include "clang/Frontend/FrontendDiagnostic.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000034#include "llvm/Support/ErrorHandling.h"
David Blaikie9c70e042011-09-21 18:16:56 +000035#include <algorithm>
36
Chris Lattner6d9a6852006-10-25 05:11:20 +000037using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000038
Richard Smith0b87e072013-10-07 08:02:11 +000039Decl *clang::getPrimaryMergedDecl(Decl *D) {
40 return D->getASTContext().getPrimaryMergedDecl(D);
41}
42
Richard Smith73b21d82014-09-03 02:33:22 +000043// Defined here so that it can be inlined into its direct callers.
44bool Decl::isOutOfLine() const {
45 return !getLexicalDeclContext()->Equals(getDeclContext());
46}
47
Richard Smith42413142015-05-15 20:05:43 +000048TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
49 : Decl(TranslationUnit, nullptr, SourceLocation()),
50 DeclContext(TranslationUnit), Ctx(ctx), AnonymousNamespace(nullptr) {
51 Hidden = Ctx.getLangOpts().ModulesLocalVisibility;
52}
53
Chris Lattner88f70d62008-03-15 05:43:15 +000054//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000055// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000056//===----------------------------------------------------------------------===//
57
John McCalldf25c432013-02-16 00:17:33 +000058// Visibility rules aren't rigorously externally specified, but here
59// are the basic principles behind what we implement:
60//
61// 1. An explicit visibility attribute is generally a direct expression
62// of the user's intent and should be honored. Only the innermost
63// visibility attribute applies. If no visibility attribute applies,
64// global visibility settings are considered.
65//
66// 2. There is one caveat to the above: on or in a template pattern,
67// an explicit visibility attribute is just a default rule, and
68// visibility can be decreased by the visibility of template
69// arguments. But this, too, has an exception: an attribute on an
70// explicit specialization or instantiation causes all the visibility
71// restrictions of the template arguments to be ignored.
72//
73// 3. A variable that does not otherwise have explicit visibility can
74// be restricted by the visibility of its type.
75//
76// 4. A visibility restriction is explicit if it comes from an
77// attribute (or something like it), not a global visibility setting.
78// When emitting a reference to an external symbol, visibility
79// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +000080//
81// 5. When computing the visibility of a non-type, including a
82// non-type member of a class, only non-type visibility restrictions
83// are considered: the 'visibility' attribute, global value-visibility
84// settings, and a few special cases like __private_extern.
85//
86// 6. When computing the visibility of a type, including a type member
87// of a class, only type visibility restrictions are considered:
88// the 'type_visibility' attribute and global type-visibility settings.
89// However, a 'visibility' attribute counts as a 'type_visibility'
90// attribute on any declaration that only has the former.
91//
92// The visibility of a "secondary" entity, like a template argument,
93// is computed using the kind of that entity, not the kind of the
94// primary entity for which we are computing visibility. For example,
95// the visibility of a specialization of either of these templates:
96// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
97// template <class T, bool (&compare)(T, X)> class matcher;
98// is restricted according to the type visibility of the argument 'T',
99// the type visibility of 'bool(&)(T,X)', and the value visibility of
100// the argument function 'compare'. That 'has_match' is a value
101// and 'matcher' is a type only matters when looking for attributes
102// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +0000103
John McCall5f46c482013-02-21 23:42:58 +0000104const unsigned IgnoreExplicitVisibilityBit = 2;
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000105const unsigned IgnoreAllVisibilityBit = 4;
John McCall5f46c482013-02-21 23:42:58 +0000106
John McCalldf25c432013-02-16 00:17:33 +0000107/// Kinds of LV computation. The linkage side of the computation is
108/// always the same, but different things can change how visibility is
109/// computed.
110enum LVComputationKind {
John McCall5f46c482013-02-21 23:42:58 +0000111 /// Do an LV computation for, ultimately, a type.
112 /// Visibility may be restricted by type visibility settings and
113 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000114 LVForType = NamedDecl::VisibilityForType,
John McCalldf25c432013-02-16 00:17:33 +0000115
John McCall5f46c482013-02-21 23:42:58 +0000116 /// Do an LV computation for, ultimately, a non-type declaration.
117 /// Visibility may be restricted by value visibility settings and
118 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000119 LVForValue = NamedDecl::VisibilityForValue,
120
John McCall5f46c482013-02-21 23:42:58 +0000121 /// Do an LV computation for, ultimately, a type that already has
122 /// some sort of explicit visibility. Visibility may only be
123 /// restricted by the visibility of template arguments.
124 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
John McCalld041a9b2013-02-20 01:54:26 +0000125
John McCall5f46c482013-02-21 23:42:58 +0000126 /// Do an LV computation for, ultimately, a non-type declaration
127 /// that already has some sort of explicit visibility. Visibility
128 /// may only be restricted by the visibility of template arguments.
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000129 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
130
131 /// Do an LV computation when we only care about the linkage.
132 LVForLinkageOnly =
133 LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
John McCalldf25c432013-02-16 00:17:33 +0000134};
135
John McCalld041a9b2013-02-20 01:54:26 +0000136/// Does this computation kind permit us to consider additional
137/// visibility settings from attributes and the like?
138static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000139 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
John McCalld041a9b2013-02-20 01:54:26 +0000140}
141
142/// Given an LVComputationKind, return one of the same type/value sort
143/// that records that it already has explicit visibility.
144static LVComputationKind
145withExplicitVisibilityAlready(LVComputationKind oldKind) {
146 LVComputationKind newKind =
John McCall5f46c482013-02-21 23:42:58 +0000147 static_cast<LVComputationKind>(unsigned(oldKind) |
148 IgnoreExplicitVisibilityBit);
John McCalld041a9b2013-02-20 01:54:26 +0000149 assert(oldKind != LVForType || newKind == LVForExplicitType);
150 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
151 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
152 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
153 return newKind;
154}
155
David Blaikie05785d12013-02-20 22:23:23 +0000156static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
157 LVComputationKind kind) {
John McCalld041a9b2013-02-20 01:54:26 +0000158 assert(!hasExplicitVisibilityAlready(kind) &&
159 "asking for explicit visibility when we shouldn't be");
160 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
161}
162
John McCalldf25c432013-02-16 00:17:33 +0000163/// Is the given declaration a "type" or a "value" for the purposes of
164/// visibility computation?
165static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000166 return isa<TypeDecl>(D) ||
167 isa<ClassTemplateDecl>(D) ||
168 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000169}
170
John McCall5f46c482013-02-21 23:42:58 +0000171/// Does the given declaration have member specialization information,
172/// and if so, is it an explicit specialization?
173template <class T> static typename
Benjamin Kramered2f4762014-03-07 14:30:23 +0000174std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-02-21 23:42:58 +0000175isExplicitMemberSpecialization(const T *D) {
176 if (const MemberSpecializationInfo *member =
177 D->getMemberSpecializationInfo()) {
178 return member->isExplicitSpecialization();
179 }
180 return false;
181}
182
183/// For templates, this question is easier: a member template can't be
184/// explicitly instantiated, so there's a single bit indicating whether
185/// or not this is an explicit member specialization.
186static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
187 return D->isMemberSpecialization();
188}
189
John McCalld041a9b2013-02-20 01:54:26 +0000190/// Given a visibility attribute, return the explicit visibility
191/// associated with it.
192template <class T>
193static Visibility getVisibilityFromAttr(const T *attr) {
194 switch (attr->getVisibility()) {
195 case T::Default:
196 return DefaultVisibility;
197 case T::Hidden:
198 return HiddenVisibility;
199 case T::Protected:
200 return ProtectedVisibility;
201 }
202 llvm_unreachable("bad visibility kind");
203}
204
John McCalldf25c432013-02-16 00:17:33 +0000205/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000206static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000207 NamedDecl::ExplicitVisibilityKind kind) {
208 // If we're ultimately computing the visibility of a type, look for
209 // a 'type_visibility' attribute before looking for 'visibility'.
210 if (kind == NamedDecl::VisibilityForType) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000211 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000212 return getVisibilityFromAttr(A);
213 }
214 }
215
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000216 // If this declaration has an explicit visibility attribute, use it.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000217 if (const auto *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000218 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000219 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000220
221 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
222 // implies visibility(default).
Douglas Gregore8bbc122011-09-02 00:18:52 +0000223 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000224 for (const auto *A : D->specific_attrs<AvailabilityAttr>())
Manman Renccf25bb2016-06-28 20:55:30 +0000225 if (A->getPlatform()->getName().equals("macos"))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000226 return DefaultVisibility;
227 }
228
David Blaikie7a30dc52013-02-21 01:47:18 +0000229 return None;
John McCall457a04e2010-10-22 21:05:15 +0000230}
231
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000232static LinkageInfo
233getLVForType(const Type &T, LVComputationKind computation) {
234 if (computation == LVForLinkageOnly)
235 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
236 return T.getLinkageAndVisibility();
237}
238
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000239/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000240/// template parameter list. For visibility purposes, template
241/// parameters are part of the signature of a template.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000242static LinkageInfo
David Majnemerc7b85c42014-04-23 05:16:48 +0000243getLVForTemplateParameterList(const TemplateParameterList *Params,
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000244 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000245 LinkageInfo LV;
David Majnemerc7b85c42014-04-23 05:16:48 +0000246 for (const NamedDecl *P : *Params) {
John McCalldf25c432013-02-16 00:17:33 +0000247 // Template type parameters are the most common and never
248 // contribute to visibility, pack or not.
David Majnemerc7b85c42014-04-23 05:16:48 +0000249 if (isa<TemplateTypeParmDecl>(P))
John McCalldf25c432013-02-16 00:17:33 +0000250 continue;
251
252 // Non-type template parameters can be restricted by the value type, e.g.
253 // template <enum X> class A { ... };
254 // We have to be careful here, though, because we can be dealing with
255 // dependent types.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000256 if (const auto *NTTP = 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.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000276 const auto *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:
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000332 if (const auto *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
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000544 const auto *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000545 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) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000572 if (const auto *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.)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000590 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000591 // 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 Smith62f19e72016-06-25 00:15:56 +0000595 // - a non-inline, non-volatile object or reference that is explicitly
596 // declared const or constexpr and neither explicitly declared extern
597 // nor previously declared to have external linkage; or (there is no
598 // equivalent in C99)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000599 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000600 Var->getType().isConstQualified() &&
Richard Smith62f19e72016-06-25 00:15:56 +0000601 !Var->getType().isVolatileQualified() &&
602 !Var->isInline()) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000603 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000604 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000605 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000606
607 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000608 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000609 !isSingleLineLanguageLinkage(*Var))
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000610 return LinkageInfo::internal();
611 }
612
613 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
614 PrevVar = PrevVar->getPreviousDecl()) {
615 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
616 Var->getStorageClass() == SC_None)
617 return PrevVar->getLinkageAndVisibility();
618 // Explicitly declared static.
619 if (PrevVar->getStorageClass() == SC_Static)
620 return LinkageInfo::internal();
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000621 }
Alp Tokera2794f92014-01-22 07:29:52 +0000622 } else if (const FunctionDecl *Function = D->getAsFunction()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000623 // C++ [temp]p4:
624 // A non-member function template can have internal linkage; any
625 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000626
627 // Explicitly declared static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000628 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000629 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
David Majnemer18fac3b2014-12-10 22:58:14 +0000630 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
631 // - a data member of an anonymous union.
632 const VarDecl *VD = IFD->getVarDecl();
633 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
634 return getLVForNamespaceScopeDecl(VD, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000635 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000636 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000637
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000638 if (D->isInAnonymousNamespace()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000639 const auto *Var = dyn_cast<VarDecl>(D);
640 const auto *Func = dyn_cast<FunctionDecl>(D);
Richard Smith97135cc2015-11-12 22:19:45 +0000641 // FIXME: In C++11 onwards, anonymous namespaces should give decls
642 // within them internal linkage, not unique external linkage.
Rafael Espindola593537a2013-05-05 20:15:21 +0000643 if ((!Var || !isFirstInExternCContext(Var)) &&
644 (!Func || !isFirstInExternCContext(Func)))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000645 return LinkageInfo::uniqueExternal();
646 }
John McCallb7139c42010-10-28 04:18:25 +0000647
John McCall457a04e2010-10-22 21:05:15 +0000648 // Set up the defaults.
649
650 // C99 6.2.2p5:
651 // If the declaration of an identifier for an object has file
652 // scope and no storage-class specifier, its linkage is
653 // external.
John McCallc273f242010-10-30 11:50:40 +0000654 LinkageInfo LV;
655
John McCalld041a9b2013-02-20 01:54:26 +0000656 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000657 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000658 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000659 } else {
660 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000661 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000662 for (const DeclContext *DC = D->getDeclContext();
663 !isa<TranslationUnitDecl>(DC);
664 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000665 const auto *ND = dyn_cast<NamespaceDecl>(DC);
Rafael Espindola78158af2012-04-16 18:46:26 +0000666 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000667 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000668 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000669 break;
670 }
671 }
672 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000673
John McCalldf25c432013-02-16 00:17:33 +0000674 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000675 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000676 // Use global type/value visibility as appropriate.
677 Visibility globalVisibility;
678 if (computation == LVForValue) {
Larisse Voufo404e1422015-02-04 02:34:32 +0000679 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
John McCallb4a99d32013-02-19 01:57:35 +0000680 } else {
681 assert(computation == LVForType);
682 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
683 }
684 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000685
686 // If we're paying attention to global visibility, apply
687 // -finline-visibility-hidden if this is an inline method.
688 if (useInlineVisibilityHidden(D))
689 LV.mergeVisibility(HiddenVisibility, true);
690 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000691 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000692
Douglas Gregorf73b2822009-11-25 22:24:25 +0000693 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000694
Douglas Gregorf73b2822009-11-25 22:24:25 +0000695 // A name having namespace scope has external linkage if it is the
696 // name of
697 //
698 // - an object or reference, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000699 if (const auto *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000700 // GCC applies the following optimization to variables and static
701 // data members, but not to functions:
702 //
John McCall457a04e2010-10-22 21:05:15 +0000703 // Modify the variable's LV by the LV of its type unless this is
704 // C or extern "C". This follows from [basic.link]p9:
705 // A type without linkage shall not be used as the type of a
706 // variable or function with external linkage unless
707 // - the entity has C language linkage, or
708 // - the entity is declared within an unnamed namespace, or
709 // - the entity is not used or is defined in the same
710 // translation unit.
711 // and [basic.link]p10:
712 // ...the types specified by all declarations referring to a
713 // given variable or function shall be identical...
714 // C does not have an equivalent rule.
715 //
John McCall5fe84122010-10-26 04:59:26 +0000716 // Ignore this if we've got an explicit attribute; the user
717 // probably knows what they're doing.
718 //
John McCall457a04e2010-10-22 21:05:15 +0000719 // Note that we don't want to make the variable non-external
720 // because of this, but unique-external linkage suits us.
Rafael Espindola593537a2013-05-05 20:15:21 +0000721 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000722 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Rafael Espindola4a5da442013-02-27 02:56:45 +0000723 if (TypeLV.getLinkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000724 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000725 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000726 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000727 }
728
John McCall23032652010-11-02 18:38:13 +0000729 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000730 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000731
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000732 // Note that Sema::MergeVarDecl already takes care of implementing
733 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
734 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000735
Larisse Voufo5899e192014-07-02 23:08:34 +0000736 // As per function and class template specializations (below),
737 // consider LV for the template and template arguments. We're at file
738 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000739 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000740 mergeTemplateLV(LV, spec, computation);
741 }
742
Douglas Gregorf73b2822009-11-25 22:24:25 +0000743 // - a function, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000744 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000745 // In theory, we can modify the function's LV by the LV of its
746 // type unless it has C linkage (see comment above about variables
747 // for justification). In practice, GCC doesn't do this, so it's
748 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000749
John McCall23032652010-11-02 18:38:13 +0000750 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000751 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000752
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000753 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
754 // merging storage classes and visibility attributes, so we don't have to
755 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000756
John McCallf768aa72011-02-10 06:50:24 +0000757 // In C++, then if the type of the function uses a type with
758 // unique-external linkage, it's not legally usable from outside
759 // this translation unit. However, we should use the C linkage
760 // rules instead for extern "C" declarations.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000761 if (Context.getLangOpts().CPlusPlus &&
Richard Smith50f4afc2013-05-12 23:17:59 +0000762 !Function->isInExternCContext()) {
763 // Only look at the type-as-written. If this function has an auto-deduced
764 // return type, we can't compute the linkage of that type because it could
765 // require looking at the linkage of this function, and we don't need this
766 // for correctness because the type is not part of the function's
767 // signature.
Faisal Valid2598e92013-10-08 04:15:04 +0000768 // FIXME: This is a hack. We should be able to solve this circularity and
769 // the one in getLVForClassMember for Functions some other way.
Richard Smith50f4afc2013-05-12 23:17:59 +0000770 QualType TypeAsWritten = Function->getType();
771 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
772 TypeAsWritten = TSI->getType();
773 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
774 return LinkageInfo::uniqueExternal();
775 }
John McCallf768aa72011-02-10 06:50:24 +0000776
John McCall5f46c482013-02-21 23:42:58 +0000777 // Consider LV from the template and the template arguments.
778 // We're at file scope, so we do not need to worry about nested
779 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000780 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000781 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000782 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000783 }
784
Douglas Gregorf73b2822009-11-25 22:24:25 +0000785 // - a named class (Clause 9), or an unnamed class defined in a
786 // typedef declaration in which the class has the typedef name
787 // for linkage purposes (7.1.3); or
788 // - a named enumeration (7.2), or an unnamed enumeration
789 // defined in a typedef declaration in which the enumeration
790 // has the typedef name for linkage purposes (7.1.3); or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000791 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000792 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000793 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000794 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000795
John McCall457a04e2010-10-22 21:05:15 +0000796 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000797 // linkage of the template and template arguments. We're at file
798 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000799 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000800 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000801 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000802
803 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000804 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000805 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000806 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000807 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000808 return LinkageInfo::none();
809 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000810
811 // - a template, unless it is a function template that has
812 // internal linkage (Clause 14);
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000813 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000814 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000815 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000816 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000817 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
818
Douglas Gregorf73b2822009-11-25 22:24:25 +0000819 // - a namespace (7.3), unless it is declared within an unnamed
820 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000821 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
822 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000823
John McCall457a04e2010-10-22 21:05:15 +0000824 // By extension, we assign external linkage to Objective-C
825 // interfaces.
826 } else if (isa<ObjCInterfaceDecl>(D)) {
827 // fallout
828
Richard Smith97135cc2015-11-12 22:19:45 +0000829 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
830 // A typedef declaration has linkage if it gives a type a name for
831 // linkage purposes.
832 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
833 return LinkageInfo::none();
834
John McCall457a04e2010-10-22 21:05:15 +0000835 // Everything not covered here has no linkage.
836 } else {
John McCallc273f242010-10-30 11:50:40 +0000837 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000838 }
839
840 // If we ended up with non-external linkage, visibility should
841 // always be default.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000842 if (LV.getLinkage() != ExternalLinkage)
843 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000844
John McCall457a04e2010-10-22 21:05:15 +0000845 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000846}
847
John McCalldf25c432013-02-16 00:17:33 +0000848static LinkageInfo getLVForClassMember(const NamedDecl *D,
849 LVComputationKind computation) {
John McCall457a04e2010-10-22 21:05:15 +0000850 // Only certain class members have linkage. Note that fields don't
851 // really have linkage, but it's convenient to say they do for the
852 // purposes of calculating linkage of pointer-to-data-member
853 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000854 //
855 // Templates also don't officially have linkage, but since we ignore
856 // the C++ standard and look at template arguments when determining
857 // linkage and visibility of a template specialization, we might hit
858 // a template template argument that way. If we do, we need to
859 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000860 if (!(isa<CXXMethodDecl>(D) ||
861 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000862 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000863 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000864 isa<TagDecl>(D) ||
865 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000866 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000867
John McCall07072662010-11-02 01:45:15 +0000868 LinkageInfo LV;
869
John McCall07072662010-11-02 01:45:15 +0000870 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000871 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000872 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000873 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000874 // If we're paying attention to global visibility, apply
875 // -finline-visibility-hidden if this is an inline method.
876 //
877 // Note that we do this before merging information about
878 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000879 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000880 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000881 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000882
883 // If this class member has an explicit visibility attribute, the only
884 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000885 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000886 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000887 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000888 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000889
John McCall5f46c482013-02-21 23:42:58 +0000890 LinkageInfo classLV =
891 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
John McCall8823c652010-08-13 08:35:10 +0000892 // If the class already has unique-external linkage, we can't improve.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000893 if (classLV.getLinkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000894 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000895
Rafael Espindolae6190db2013-05-28 02:22:10 +0000896 if (!isExternallyVisible(classLV.getLinkage()))
897 return LinkageInfo::none();
898
899
John McCall5f46c482013-02-21 23:42:58 +0000900 // Otherwise, don't merge in classLV yet, because in certain cases
901 // we need to completely ignore the visibility from it.
902
903 // Specifically, if this decl exists and has an explicit attribute.
Craig Topper36250ad2014-05-12 05:36:57 +0000904 const NamedDecl *explicitSpecSuppressor = nullptr;
John McCall5f46c482013-02-21 23:42:58 +0000905
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000906 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000907 // If the type of the function uses a type with unique-external
908 // linkage, it's not legally usable from outside this translation unit.
Nico Weber38267342015-04-22 03:44:51 +0000909 // But only look at the type-as-written. If this function has an
910 // auto-deduced return type, we can't compute the linkage of that type
911 // because it could require looking at the linkage of this function, and we
912 // don't need this for correctness because the type is not part of the
913 // function's signature.
914 // FIXME: This is a hack. We should be able to solve this circularity and
915 // the one in getLVForNamespaceScopeDecl for Functions some other way.
Faisal Valid2598e92013-10-08 04:15:04 +0000916 {
917 QualType TypeAsWritten = MD->getType();
918 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
919 TypeAsWritten = TSI->getType();
920 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
921 return LinkageInfo::uniqueExternal();
922 }
John McCall457a04e2010-10-22 21:05:15 +0000923 // If this is a method template specialization, use the linkage for
924 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000925 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000926 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000927 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000928 if (spec->isExplicitSpecialization()) {
929 explicitSpecSuppressor = MD;
930 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
931 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
932 }
933 } else if (isExplicitMemberSpecialization(MD)) {
934 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000935 }
John McCall457a04e2010-10-22 21:05:15 +0000936
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000937 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
938 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000939 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000940 if (spec->isExplicitSpecialization()) {
941 explicitSpecSuppressor = spec;
942 } else {
943 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
944 if (isExplicitMemberSpecialization(temp)) {
945 explicitSpecSuppressor = temp->getTemplatedDecl();
946 }
947 }
948 } else if (isExplicitMemberSpecialization(RD)) {
949 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000950 }
951
John McCall37bb6c92010-10-29 22:22:43 +0000952 // Static data members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000953 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
954 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
Larisse Voufo5899e192014-07-02 23:08:34 +0000955 mergeTemplateLV(LV, spec, computation);
956
John McCall36cd5cc2010-10-30 09:18:49 +0000957 // Modify the variable's linkage by its type, but ignore the
958 // type's visibility unless it's a definition.
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000959 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000960 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
961 LV.mergeVisibility(typeLV);
962 LV.mergeExternalVisibility(typeLV);
John McCall5f46c482013-02-21 23:42:58 +0000963
964 if (isExplicitMemberSpecialization(VD)) {
965 explicitSpecSuppressor = VD;
966 }
John McCalldf25c432013-02-16 00:17:33 +0000967
968 // Template members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000969 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +0000970 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +0000971 (!LV.isVisibilityExplicit() &&
972 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000973 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000974 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000975 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000976 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +0000977
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000978 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
John McCall5f46c482013-02-21 23:42:58 +0000979 if (isExplicitMemberSpecialization(redeclTemp)) {
980 explicitSpecSuppressor = temp->getTemplatedDecl();
981 }
982 }
John McCall37bb6c92010-10-29 22:22:43 +0000983 }
984
John McCall5f46c482013-02-21 23:42:58 +0000985 // We should never be looking for an attribute directly on a template.
986 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
987
988 // If this member is an explicit member specialization, and it has
989 // an explicit attribute, ignore visibility from the parent.
990 bool considerClassVisibility = true;
991 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +0000992 // optimization: hasDVA() is true only with explicit visibility.
993 LV.isVisibilityExplicit() &&
994 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +0000995 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
996 considerClassVisibility = false;
997 }
998
999 // Finally, merge in information from the class.
1000 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +00001001 return LV;
John McCall8823c652010-08-13 08:35:10 +00001002}
1003
David Blaikie68e081d2011-12-20 02:48:34 +00001004void NamedDecl::anchor() { }
1005
Rafael Espindolaecf63c62013-05-29 04:55:30 +00001006static LinkageInfo computeLVForDecl(const NamedDecl *D,
1007 LVComputationKind computation);
1008
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001009bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001010 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001011 return true;
John McCalld396b972011-02-08 19:01:05 +00001012
Rafael Espindolaecf63c62013-05-29 04:55:30 +00001013 return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
Rafael Espindola50df3a02013-05-25 17:16:20 +00001014 getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +00001015}
1016
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001017ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1018 StringRef name = getName();
1019 if (name.empty()) return SFF_None;
1020
1021 if (name.front() == 'C')
1022 if (name == "CFStringCreateWithFormat" ||
1023 name == "CFStringCreateWithFormatAndArguments" ||
1024 name == "CFStringAppendFormat" ||
1025 name == "CFStringAppendFormatAndArguments")
1026 return SFF_CFString;
1027 return SFF_None;
1028}
1029
Rafael Espindola3ae00052013-05-13 00:12:11 +00001030Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +00001031 // We don't care about visibility here, so ask for the cheapest
1032 // possible visibility analysis.
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001033 return getLVForDecl(this, LVForLinkageOnly).getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001034}
1035
John McCallc273f242010-10-30 11:50:40 +00001036LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCalldf25c432013-02-16 00:17:33 +00001037 LVComputationKind computation =
1038 (usesTypeVisibility(this) ? LVForType : LVForValue);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001039 return getLVForDecl(this, computation);
John McCall033caa52010-10-29 00:29:13 +00001040}
Ted Kremenek926d8602010-04-20 23:15:35 +00001041
Rafael Espindola9ad61122013-11-26 16:09:08 +00001042static Optional<Visibility>
1043getExplicitVisibilityAux(const NamedDecl *ND,
1044 NamedDecl::ExplicitVisibilityKind kind,
1045 bool IsMostRecent) {
1046 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1047
Rafael Espindola3a52c442013-02-26 19:33:14 +00001048 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001049 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001050 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001051
Rafael Espindola3a52c442013-02-26 19:33:14 +00001052 // If this is a member class of a specialization of a class template
1053 // and the corresponding decl has explicit visibility, use that.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001054 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +00001055 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1056 if (InstantiatedFrom)
1057 return getVisibilityOf(InstantiatedFrom, kind);
1058 }
1059
1060 // If there wasn't explicit visibility there, and this is a
1061 // specialization of a class template, check for visibility
1062 // on the pattern.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001063 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001064 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1065 kind);
1066
1067 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +00001068 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +00001069 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1070 if (MostRecent != ND)
1071 return getExplicitVisibilityAux(MostRecent, kind, true);
1072 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001073
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001074 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +00001075 if (Var->isStaticDataMember()) {
1076 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1077 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001078 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +00001079 }
1080
David Majnemer35b02bc2014-04-29 07:32:26 +00001081 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1082 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1083 kind);
1084
David Blaikie7a30dc52013-02-21 01:47:18 +00001085 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +00001086 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001087 // Also handle function template specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001088 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001089 // If the function is a specialization of a template with an
1090 // explicit visibility attribute, use that.
1091 if (FunctionTemplateSpecializationInfo *templateInfo
1092 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +00001093 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1094 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001095
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001096 // If the function is a member of a specialization of a class template
1097 // and the corresponding decl has explicit visibility, use that.
1098 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1099 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001100 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001101
David Blaikie7a30dc52013-02-21 01:47:18 +00001102 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001103 }
1104
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001105 // The visibility of a template is stored in the templated decl.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001106 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001107 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001108
David Blaikie7a30dc52013-02-21 01:47:18 +00001109 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001110}
1111
Rafael Espindola9ad61122013-11-26 16:09:08 +00001112Optional<Visibility>
1113NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1114 return getExplicitVisibilityAux(this, kind, false);
1115}
1116
Eli Friedman7e346a82013-07-01 20:22:57 +00001117static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
1118 LVComputationKind computation) {
1119 // This lambda has its linkage/visibility determined by its owner.
1120 if (ContextDecl) {
1121 if (isa<ParmVarDecl>(ContextDecl))
1122 DC = ContextDecl->getDeclContext()->getRedeclContext();
1123 else
1124 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1125 }
Faisal Vali98b8e182013-09-29 20:27:06 +00001126
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001127 if (const auto *ND = dyn_cast<NamedDecl>(DC))
Eli Friedman7e346a82013-07-01 20:22:57 +00001128 return getLVForDecl(ND, computation);
Faisal Vali98b8e182013-09-29 20:27:06 +00001129
Eli Friedman7e346a82013-07-01 20:22:57 +00001130 return LinkageInfo::external();
1131}
1132
John McCalldf25c432013-02-16 00:17:33 +00001133static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1134 LVComputationKind computation) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001135 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001136 if (Function->isInAnonymousNamespace() &&
Rafael Espindola593537a2013-05-05 20:15:21 +00001137 !Function->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001138 return LinkageInfo::uniqueExternal();
1139
1140 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001141 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCalldf25c432013-02-16 00:17:33 +00001142 return LinkageInfo::internal();
1143
1144 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001145 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001146 if (Optional<Visibility> Vis =
1147 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001148 LV.mergeVisibility(*Vis, true);
1149 }
1150
1151 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1152 // merging storage classes and visibility attributes, so we don't have to
1153 // look at previous decls in here.
1154
1155 return LV;
1156 }
1157
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001158 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001159 if (Var->hasExternalStorage()) {
Rafael Espindola593537a2013-05-05 20:15:21 +00001160 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001161 return LinkageInfo::uniqueExternal();
1162
John McCalldf25c432013-02-16 00:17:33 +00001163 LinkageInfo LV;
1164 if (Var->getStorageClass() == SC_PrivateExtern)
1165 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001166 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001167 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001168 LV.mergeVisibility(*Vis, true);
1169 }
1170
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001171 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1172 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1173 if (PrevLV.getLinkage())
1174 LV.setLinkage(PrevLV.getLinkage());
1175 LV.mergeVisibility(PrevLV);
1176 }
1177
John McCalldf25c432013-02-16 00:17:33 +00001178 return LV;
1179 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001180
1181 if (!Var->isStaticLocal())
1182 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001183 }
1184
Rafael Espindolaa4184182013-06-17 20:04:51 +00001185 ASTContext &Context = D->getASTContext();
1186 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001187 return LinkageInfo::none();
1188
Eli Friedman7e346a82013-07-01 20:22:57 +00001189 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
Alexey Bataev0a47e652016-01-12 09:01:25 +00001190 if (!OuterD || OuterD->isInvalidDecl())
Rafael Espindola50df3a02013-05-25 17:16:20 +00001191 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001192
Eli Friedman7e346a82013-07-01 20:22:57 +00001193 LinkageInfo LV;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001194 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001195 if (!BD->getBlockManglingNumber())
1196 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001197
Eli Friedman7e346a82013-07-01 20:22:57 +00001198 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1199 BD->getBlockManglingContextDecl(), computation);
1200 } else {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001201 const auto *FD = cast<FunctionDecl>(OuterD);
Eli Friedman7e346a82013-07-01 20:22:57 +00001202 if (!FD->isInlined() &&
David Majnemer9963ade2014-12-16 04:52:14 +00001203 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
Eli Friedman7e346a82013-07-01 20:22:57 +00001204 return LinkageInfo::none();
1205
1206 LV = getLVForDecl(FD, computation);
1207 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001208 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001209 return LinkageInfo::none();
1210 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1211 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001212}
1213
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001214static inline const CXXRecordDecl*
1215getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1216 const CXXRecordDecl *Ret = Record;
1217 while (Record && Record->isLambda()) {
1218 Ret = Record;
1219 if (!Record->getParent()) break;
1220 // Get the Containing Class of this Lambda Class
1221 Record = dyn_cast_or_null<CXXRecordDecl>(
1222 Record->getParent()->getParent());
1223 }
1224 return Ret;
1225}
1226
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001227static LinkageInfo computeLVForDecl(const NamedDecl *D,
1228 LVComputationKind computation) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001229 // Internal_linkage attribute overrides other considerations.
1230 if (D->hasAttr<InternalLinkageAttr>())
1231 return LinkageInfo::internal();
1232
Ted Kremenek926d8602010-04-20 23:15:35 +00001233 // Objective-C: treat all Objective-C declarations as having external
1234 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001235 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001236 default:
1237 break;
Richard Smith97135cc2015-11-12 22:19:45 +00001238
1239 // Per C++ [basic.link]p2, only the names of objects, references,
1240 // functions, types, templates, namespaces, and values ever have linkage.
1241 //
1242 // Note that the name of a typedef, namespace alias, using declaration,
1243 // and so on are not the name of the corresponding type, namespace, or
1244 // declaration, so they do *not* have linkage.
Richard Smith97135cc2015-11-12 22:19:45 +00001245 case Decl::ImplicitParam:
1246 case Decl::Label:
1247 case Decl::NamespaceAlias:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001248 case Decl::ParmVar:
Richard Smith97135cc2015-11-12 22:19:45 +00001249 case Decl::Using:
1250 case Decl::UsingShadow:
1251 case Decl::UsingDirective:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001252 return LinkageInfo::none();
Richard Smith97135cc2015-11-12 22:19:45 +00001253
Richard Smith26210db2015-11-13 03:52:13 +00001254 case Decl::EnumConstant:
1255 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
1256 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1257
Richard Smith97135cc2015-11-12 22:19:45 +00001258 case Decl::Typedef:
1259 case Decl::TypeAlias:
1260 // A typedef declaration has linkage if it gives a type a name for
1261 // linkage purposes.
Ben Langmuir90717ad2015-11-14 03:26:14 +00001262 if (!D->getASTContext().getLangOpts().CPlusPlus ||
1263 !cast<TypedefNameDecl>(D)
Richard Smith97135cc2015-11-12 22:19:45 +00001264 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1265 return LinkageInfo::none();
1266 break;
1267
John McCall457a04e2010-10-22 21:05:15 +00001268 case Decl::TemplateTemplateParm: // count these as external
1269 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001270 case Decl::ObjCAtDefsField:
1271 case Decl::ObjCCategory:
1272 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001273 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001274 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001275 case Decl::ObjCMethod:
1276 case Decl::ObjCProperty:
1277 case Decl::ObjCPropertyImpl:
1278 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +00001279 return LinkageInfo::external();
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001280
1281 case Decl::CXXRecord: {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001282 const auto *Record = cast<CXXRecordDecl>(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001283 if (Record->isLambda()) {
1284 if (!Record->getLambdaManglingNumber()) {
1285 // This lambda has no mangling number, so it's internal.
1286 return LinkageInfo::internal();
1287 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001288
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001289 // This lambda has its linkage/visibility determined:
1290 // - either by the outermost lambda if that lambda has no mangling
1291 // number.
1292 // - or by the parent of the outer most lambda
1293 // This prevents infinite recursion in settings such as nested lambdas
1294 // used in NSDMI's, for e.g.
1295 // struct L {
1296 // int t{};
1297 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1298 // };
1299 const CXXRecordDecl *OuterMostLambda =
1300 getOutermostEnclosingLambda(Record);
1301 if (!OuterMostLambda->getLambdaManglingNumber())
1302 return LinkageInfo::internal();
1303
1304 return getLVForClosure(
1305 OuterMostLambda->getDeclContext()->getRedeclContext(),
1306 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001307 }
1308
1309 break;
1310 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001311 }
1312
Douglas Gregorf73b2822009-11-25 22:24:25 +00001313 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001314 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCalldf25c432013-02-16 00:17:33 +00001315 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001316
1317 // C++ [basic.link]p5:
1318 // In addition, a member function, static data member, a named
1319 // class or enumeration of class scope, or an unnamed class or
1320 // enumeration defined in a class-scope typedef declaration such
1321 // that the class or enumeration has the typedef name for linkage
1322 // purposes (7.1.3), has external linkage if the name of the class
1323 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001324 if (D->getDeclContext()->isRecord())
John McCalldf25c432013-02-16 00:17:33 +00001325 return getLVForClassMember(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001326
1327 // C++ [basic.link]p6:
1328 // The name of a function declared in block scope and the name of
1329 // an object declared by a block scope extern declaration have
1330 // linkage. If there is a visible declaration of an entity with
1331 // linkage having the same name and type, ignoring entities
1332 // declared outside the innermost enclosing namespace scope, the
1333 // block scope declaration declares that same entity and receives
1334 // the linkage of the previous declaration. If there is more than
1335 // one such matching entity, the program is ill-formed. Otherwise,
1336 // if no matching entity is found, the block scope entity receives
1337 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001338 if (D->getDeclContext()->isFunctionOrMethod())
1339 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001340
1341 // C++ [basic.link]p6:
1342 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001343 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001344}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001345
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001346namespace clang {
1347class LinkageComputer {
1348public:
1349 static LinkageInfo getLVForDecl(const NamedDecl *D,
1350 LVComputationKind computation) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001351 // Internal_linkage attribute overrides other considerations.
1352 if (D->hasAttr<InternalLinkageAttr>())
1353 return LinkageInfo::internal();
1354
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001355 if (computation == LVForLinkageOnly && D->hasCachedLinkage())
1356 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1357
1358 LinkageInfo LV = computeLVForDecl(D, computation);
1359 if (D->hasCachedLinkage())
1360 assert(D->getCachedLinkage() == LV.getLinkage());
1361
1362 D->setCachedLinkage(LV.getLinkage());
1363
1364#ifndef NDEBUG
1365 // In C (because of gnu inline) and in c++ with microsoft extensions an
1366 // static can follow an extern, so we can have two decls with different
1367 // linkages.
1368 const LangOptions &Opts = D->getASTContext().getLangOpts();
1369 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1370 return LV;
1371
1372 // We have just computed the linkage for this decl. By induction we know
1373 // that all other computed linkages match, check that the one we just
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001374 // computed also does.
Craig Topper36250ad2014-05-12 05:36:57 +00001375 NamedDecl *Old = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +00001376 for (auto I : D->redecls()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001377 auto *T = cast<NamedDecl>(I);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001378 if (T == D)
1379 continue;
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001380 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001381 Old = T;
1382 break;
1383 }
1384 }
1385 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1386#endif
1387
1388 return LV;
1389 }
1390};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001391}
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001392
1393static LinkageInfo getLVForDecl(const NamedDecl *D,
1394 LVComputationKind computation) {
1395 return clang::LinkageComputer::getLVForDecl(D, computation);
1396}
1397
Richard Smith7873de02016-08-11 22:25:46 +00001398void NamedDecl::printName(raw_ostream &os) const {
1399 os << Name;
1400}
1401
Douglas Gregor2ada0482009-02-04 17:27:36 +00001402std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001403 std::string QualName;
1404 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001405 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001406 return OS.str();
1407}
1408
1409void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1410 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1411}
1412
1413void NamedDecl::printQualifiedName(raw_ostream &OS,
1414 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001415 const DeclContext *Ctx = getDeclContext();
1416
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001417 if (Ctx->isFunctionOrMethod()) {
1418 printName(OS);
1419 return;
1420 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001421
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001422 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001423 ContextsTy Contexts;
1424
1425 // Collect contexts.
1426 while (Ctx && isa<NamedDecl>(Ctx)) {
1427 Contexts.push_back(Ctx);
1428 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001429 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001430
David Majnemerf7e36092016-06-23 00:15:04 +00001431 for (const DeclContext *DC : reverse(Contexts)) {
1432 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001433 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001434 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
David Majnemer6fbeee32016-07-07 04:43:07 +00001435 TemplateSpecializationType::PrintTemplateArgumentList(
1436 OS, TemplateArgs.asArray(), P);
David Majnemerf7e36092016-06-23 00:15:04 +00001437 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
Richard Smith46dd5bb2014-05-30 22:16:51 +00001438 if (P.SuppressUnwrittenScope &&
1439 (ND->isAnonymousNamespace() || ND->isInline()))
1440 continue;
Reid Kleckner60103382015-12-16 02:04:40 +00001441 if (ND->isAnonymousNamespace()) {
1442 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1443 : "(anonymous namespace)");
1444 }
Sam Weinig07d211e2009-12-24 23:15:03 +00001445 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001446 OS << *ND;
David Majnemerf7e36092016-06-23 00:15:04 +00001447 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001448 if (!RD->getIdentifier())
David Blaikieabe1a392014-04-02 05:58:29 +00001449 OS << "(anonymous " << RD->getKindName() << ')';
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001450 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001451 OS << *RD;
David Majnemerf7e36092016-06-23 00:15:04 +00001452 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
Craig Topper36250ad2014-05-12 05:36:57 +00001453 const FunctionProtoType *FT = nullptr;
Sam Weinigb999f682009-12-28 03:19:38 +00001454 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001455 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001456
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001457 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001458 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001459 unsigned NumParams = FD->getNumParams();
1460 for (unsigned i = 0; i < NumParams; ++i) {
1461 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001462 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001463 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001464 }
1465
1466 if (FT->isVariadic()) {
1467 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001468 OS << ", ";
1469 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001470 }
1471 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001472 OS << ')';
David Majnemerf7e36092016-06-23 00:15:04 +00001473 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
Alexander Kornienko4f355322015-11-09 16:45:17 +00001474 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1475 // enumerator is declared in the scope that immediately contains
1476 // the enum-specifier. Each scoped enumerator is declared in the
1477 // scope of the enumeration.
1478 if (ED->isScoped() || ED->getIdentifier())
1479 OS << *ED;
1480 else
1481 continue;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001482 } else {
David Majnemerf7e36092016-06-23 00:15:04 +00001483 OS << *cast<NamedDecl>(DC);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001484 }
1485 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001486 }
1487
Richard Smith7873de02016-08-11 22:25:46 +00001488 if (getDeclName() || isa<DecompositionDecl>(this))
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001489 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001490 else
David Blaikieabe1a392014-04-02 05:58:29 +00001491 OS << "(anonymous)";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001492}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001493
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001494void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1495 const PrintingPolicy &Policy,
1496 bool Qualified) const {
1497 if (Qualified)
1498 printQualifiedName(OS, Policy);
1499 else
1500 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001501}
1502
Richard Smithe8292b12015-02-10 03:28:10 +00001503template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1504 return true;
1505}
1506static bool isRedeclarableImpl(...) { return false; }
1507static bool isRedeclarable(Decl::Kind K) {
1508 switch (K) {
1509#define DECL(Type, Base) \
1510 case Decl::Type: \
1511 return isRedeclarableImpl((Type##Decl *)nullptr);
1512#define ABSTRACT_DECL(DECL)
1513#include "clang/AST/DeclNodes.inc"
1514 }
1515 llvm_unreachable("unknown decl kind");
1516}
1517
1518bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001519 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1520
Richard Smithfe620d22015-03-05 23:24:12 +00001521 // Never replace one imported declaration with another; we need both results
1522 // when re-exporting.
1523 if (OldD->isFromASTFile() && isFromASTFile())
1524 return false;
1525
Richard Smith5cd86f82015-11-03 03:13:11 +00001526 // A kind mismatch implies that the declaration is not replaced.
1527 if (OldD->getKind() != getKind())
Richard Smithe8292b12015-02-10 03:28:10 +00001528 return false;
1529
Richard Smith5cd86f82015-11-03 03:13:11 +00001530 // For method declarations, we never replace. (Why?)
1531 if (isa<ObjCMethodDecl>(this))
1532 return false;
1533
1534 // For parameters, pick the newer one. This is either an error or (in
1535 // Objective-C) permitted as an extension.
1536 if (isa<ParmVarDecl>(this))
1537 return true;
1538
Richard Smithe8292b12015-02-10 03:28:10 +00001539 // Inline namespaces can give us two declarations with the same
1540 // name and kind in the same scope but different contexts; we should
1541 // keep both declarations in this case.
1542 if (!this->getDeclContext()->getRedeclContext()->Equals(
1543 OldD->getDeclContext()->getRedeclContext()))
1544 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001545
Richard Smith5cd86f82015-11-03 03:13:11 +00001546 // Using declarations can be replaced if they import the same name from the
1547 // same context.
Richard Smithe8292b12015-02-10 03:28:10 +00001548 if (auto *UD = dyn_cast<UsingDecl>(this)) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001549 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001550 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001551 Context.getCanonicalNestedNameSpecifier(
Richard Smithe8292b12015-02-10 03:28:10 +00001552 cast<UsingDecl>(OldD)->getQualifier());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001553 }
Richard Smithe8292b12015-02-10 03:28:10 +00001554 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001555 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001556 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001557 Context.getCanonicalNestedNameSpecifier(
1558 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1559 }
1560
Richard Smithe8292b12015-02-10 03:28:10 +00001561 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
Richard Smith5cd86f82015-11-03 03:13:11 +00001562 // They can be replaced if they nominate the same namespace.
1563 // FIXME: Is this true even if they have different module visibility?
Richard Smithe8292b12015-02-10 03:28:10 +00001564 if (auto *UD = dyn_cast<UsingDirectiveDecl>(this))
1565 return UD->getNominatedNamespace()->getOriginalNamespace() ==
1566 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1567 ->getOriginalNamespace();
Richard Smithbaf3ca52014-03-17 21:46:03 +00001568
Richard Smith5cd86f82015-11-03 03:13:11 +00001569 if (isRedeclarable(getKind())) {
1570 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1571 return false;
1572
1573 if (IsKnownNewer)
1574 return true;
1575
Richard Smithe8292b12015-02-10 03:28:10 +00001576 // Check whether this is actually newer than OldD. We want to keep the
1577 // newer declaration. This loop will usually only iterate once, because
1578 // OldD is usually the previous declaration.
1579 for (auto D : redecls()) {
1580 if (D == OldD)
1581 break;
1582
1583 // If we reach the canonical declaration, then OldD is not actually older
1584 // than this one.
1585 //
1586 // FIXME: In this case, we should not add this decl to the lookup table.
1587 if (D->isCanonicalDecl())
1588 return false;
1589 }
Richard Smith5cd86f82015-11-03 03:13:11 +00001590
1591 // It's a newer declaration of the same kind of declaration in the same
1592 // scope: we want this decl instead of the existing one.
1593 return true;
Richard Smithe8292b12015-02-10 03:28:10 +00001594 }
1595
Richard Smith5cd86f82015-11-03 03:13:11 +00001596 // In all other cases, we need to keep both declarations in case they have
1597 // different visibility. Any attempt to use the name will result in an
1598 // ambiguity if more than one is visible.
1599 return false;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001600}
1601
Douglas Gregoreddf4332009-02-24 20:03:32 +00001602bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001603 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001604}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001605
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001606NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001607 NamedDecl *ND = this;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001608 while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001609 ND = UD->getTargetDecl();
1610
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001611 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001612 return AD->getClassInterface();
1613
Richard Smithf2005d32015-12-29 23:34:32 +00001614 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1615 return AD->getNamespace();
1616
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001617 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001618}
1619
John McCalla8ae2222010-04-06 21:38:20 +00001620bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001621 if (!isCXXClassMember())
1622 return false;
1623
John McCalla8ae2222010-04-06 21:38:20 +00001624 const NamedDecl *D = this;
1625 if (isa<UsingShadowDecl>(D))
1626 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1627
John McCall5e77d762013-04-16 07:28:30 +00001628 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001629 return true;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001630 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
Alp Tokera2794f92014-01-22 07:29:52 +00001631 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001632 return false;
1633}
1634
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001635//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001636// DeclaratorDecl Implementation
1637//===----------------------------------------------------------------------===//
1638
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001639template <typename DeclT>
1640static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1641 if (decl->getNumTemplateParameterLists() > 0)
1642 return decl->getTemplateParameterList(0)->getTemplateLoc();
1643 else
1644 return decl->getInnerLocStart();
1645}
1646
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001647SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001648 TypeSourceInfo *TSI = getTypeSourceInfo();
1649 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001650 return SourceLocation();
1651}
1652
Douglas Gregor14454802011-02-25 02:25:35 +00001653void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1654 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001655 // Make sure the extended decl info is allocated.
1656 if (!hasExtInfo()) {
1657 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001658 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
John McCall3e11ebe2010-03-15 10:12:16 +00001659 // Allocate external info struct.
1660 DeclInfo = new (getASTContext()) ExtInfo;
1661 // Restore savedTInfo into (extended) decl info.
1662 getExtInfo()->TInfo = savedTInfo;
1663 }
1664 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001665 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001666 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001667 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001668 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001669 if (getExtInfo()->NumTemplParamLists == 0) {
1670 // Save type source info pointer.
1671 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1672 // Deallocate the extended decl info.
1673 getASTContext().Deallocate(getExtInfo());
1674 // Restore savedTInfo into (non-extended) decl info.
1675 DeclInfo = savedTInfo;
1676 }
1677 else
1678 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001679 }
1680 }
1681}
1682
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001683void DeclaratorDecl::setTemplateParameterListsInfo(
1684 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1685 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00001686 // Make sure the extended decl info is allocated.
1687 if (!hasExtInfo()) {
1688 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001689 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
Abramo Bagnara60804e12011-03-18 15:16:37 +00001690 // Allocate external info struct.
1691 DeclInfo = new (getASTContext()) ExtInfo;
1692 // Restore savedTInfo into (extended) decl info.
1693 getExtInfo()->TInfo = savedTInfo;
1694 }
1695 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001696 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00001697}
1698
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001699SourceLocation DeclaratorDecl::getOuterLocStart() const {
1700 return getTemplateOrInnerLocStart(this);
1701}
1702
Abramo Bagnaraea947882011-03-08 16:41:52 +00001703namespace {
1704
1705// Helper function: returns true if QT is or contains a type
1706// having a postfix component.
1707bool typeIsPostfix(clang::QualType QT) {
1708 while (true) {
1709 const Type* T = QT.getTypePtr();
1710 switch (T->getTypeClass()) {
1711 default:
1712 return false;
1713 case Type::Pointer:
1714 QT = cast<PointerType>(T)->getPointeeType();
1715 break;
1716 case Type::BlockPointer:
1717 QT = cast<BlockPointerType>(T)->getPointeeType();
1718 break;
1719 case Type::MemberPointer:
1720 QT = cast<MemberPointerType>(T)->getPointeeType();
1721 break;
1722 case Type::LValueReference:
1723 case Type::RValueReference:
1724 QT = cast<ReferenceType>(T)->getPointeeType();
1725 break;
1726 case Type::PackExpansion:
1727 QT = cast<PackExpansionType>(T)->getPattern();
1728 break;
1729 case Type::Paren:
1730 case Type::ConstantArray:
1731 case Type::DependentSizedArray:
1732 case Type::IncompleteArray:
1733 case Type::VariableArray:
1734 case Type::FunctionProto:
1735 case Type::FunctionNoProto:
1736 return true;
1737 }
1738 }
1739}
1740
1741} // namespace
1742
1743SourceRange DeclaratorDecl::getSourceRange() const {
1744 SourceLocation RangeEnd = getLocation();
1745 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001746 // If the declaration has no name or the type extends past the name take the
1747 // end location of the type.
1748 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001749 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1750 }
1751 return SourceRange(getOuterLocStart(), RangeEnd);
1752}
1753
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001754void QualifierInfo::setTemplateParameterListsInfo(
1755 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001756 // Free previous template parameters (if any).
1757 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001758 Context.Deallocate(TemplParamLists);
Craig Topper36250ad2014-05-12 05:36:57 +00001759 TemplParamLists = nullptr;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001760 NumTemplParamLists = 0;
1761 }
1762 // Set info on matched template parameter lists (if any).
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001763 if (!TPLists.empty()) {
1764 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1765 NumTemplParamLists = TPLists.size();
1766 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001767 }
1768}
1769
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001770//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001771// VarDecl Implementation
1772//===----------------------------------------------------------------------===//
1773
Sebastian Redl833ef452010-01-26 22:01:41 +00001774const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1775 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001776 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001777 case SC_Auto: return "auto";
1778 case SC_Extern: return "extern";
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001779 case SC_PrivateExtern: return "__private_extern__";
1780 case SC_Register: return "register";
1781 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001782 }
1783
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001784 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001785}
1786
Richard Smith053f6c62014-05-16 23:01:30 +00001787VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1788 SourceLocation StartLoc, SourceLocation IdLoc,
1789 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1790 StorageClass SC)
1791 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1792 redeclarable_base(C), Init() {
Benjamin Kramera939c232014-03-15 18:54:13 +00001793 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1794 "VarDeclBitfields too large!");
1795 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1796 "ParmVarDeclBitfields too large!");
David Majnemerfa7bc782015-05-19 00:57:16 +00001797 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1798 "NonParmVarDeclBitfields too large!");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001799 AllBits = 0;
1800 VarDeclBits.SClass = SC;
1801 // Everything else is implicitly initialized to false.
1802}
1803
Abramo Bagnaradff19302011-03-08 08:55:46 +00001804VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1805 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001806 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001807 StorageClass S) {
Richard Smith053f6c62014-05-16 23:01:30 +00001808 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001809}
1810
Douglas Gregor72172e92012-01-05 21:55:30 +00001811VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00001812 return new (C, ID)
1813 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1814 QualType(), nullptr, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001815}
1816
Douglas Gregorbf62d642010-12-06 18:36:25 +00001817void VarDecl::setStorageClass(StorageClass SC) {
1818 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001819 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001820}
1821
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001822VarDecl::TLSKind VarDecl::getTLSKind() const {
1823 switch (VarDeclBits.TSCSpec) {
1824 case TSCS_unspecified:
Samuel Antaof8b50122015-07-13 22:54:53 +00001825 if (!hasAttr<ThreadAttr>() &&
1826 !(getASTContext().getLangOpts().OpenMPUseTLS &&
1827 getASTContext().getTargetInfo().isTLSSupported() &&
1828 hasAttr<OMPThreadPrivateDeclAttr>()))
David Majnemer1b5baff2015-05-14 05:19:23 +00001829 return TLS_None;
Samuel Antaof8b50122015-07-13 22:54:53 +00001830 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1831 LangOptions::MSVC2015)) ||
1832 hasAttr<OMPThreadPrivateDeclAttr>())
David Majnemer1b5baff2015-05-14 05:19:23 +00001833 ? TLS_Dynamic
1834 : TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001835 case TSCS___thread: // Fall through.
1836 case TSCS__Thread_local:
Samuel Antaof8b50122015-07-13 22:54:53 +00001837 return TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001838 case TSCS_thread_local:
1839 return TLS_Dynamic;
1840 }
1841 llvm_unreachable("Unknown thread storage class specifier!");
1842}
1843
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001844SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001845 if (const Expr *Init = getInit()) {
1846 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001847 // If Init is implicit, ignore its source range and fallback on
1848 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1849 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001850 return SourceRange(getOuterLocStart(), InitEnd);
1851 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001852 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001853}
1854
Rafael Espindola88510672013-01-04 21:18:45 +00001855template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001856static LanguageLinkage getDeclLanguageLinkage(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001857 // C++ [dcl.link]p1: All function types, function names with external linkage,
1858 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001859 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001860 return NoLanguageLinkage;
1861
1862 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001863 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001864 ASTContext &Context = D.getASTContext();
1865 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001866 return CLanguageLinkage;
1867
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001868 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1869 // language linkage of the names of class members and the function type of
1870 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001871 const DeclContext *DC = D.getDeclContext();
1872 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001873 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001874
1875 // If the first decl is in an extern "C" context, any other redeclaration
1876 // will have C language linkage. If the first one is not in an extern "C"
1877 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00001878 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00001879 return CLanguageLinkage;
1880 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001881}
1882
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001883template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001884static bool isDeclExternC(const T &D) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001885 // Since the context is ignored for class members, they can only have C++
1886 // language linkage or no language linkage.
1887 const DeclContext *DC = D.getDeclContext();
1888 if (DC->isRecord()) {
1889 assert(D.getASTContext().getLangOpts().CPlusPlus);
1890 return false;
1891 }
1892
1893 return D.getLanguageLinkage() == CLanguageLinkage;
1894}
1895
Rafael Espindolaf4187652013-02-14 01:18:37 +00001896LanguageLinkage VarDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00001897 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001898}
1899
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001900bool VarDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00001901 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001902}
1903
Rafael Espindola593537a2013-05-05 20:15:21 +00001904bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001905 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001906}
1907
1908bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001909 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001910}
1911
Rafael Espindola8db352d2013-10-17 15:37:26 +00001912VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00001913
Nico Weber7f5015a2015-04-15 21:53:00 +00001914VarDecl::DefinitionKind
1915VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001916 // C++ [basic.def]p2:
1917 // A declaration is a definition unless [...] it contains the 'extern'
1918 // specifier or a linkage-specification and neither an initializer [...],
Richard Smith62f19e72016-06-25 00:15:56 +00001919 // it declares a non-inline static data member in a class declaration [...],
1920 // it declares a static data member outside a class definition and the variable
1921 // was defined within the class with the constexpr specifier [...],
Richard Smith8809a0c2013-09-27 20:14:12 +00001922 // C++1y [temp.expl.spec]p15:
1923 // An explicit specialization of a static data member or an explicit
1924 // specialization of a static data member template is a definition if the
1925 // declaration includes an initializer; otherwise, it is a declaration.
1926 //
1927 // FIXME: How do you declare (but not define) a partial specialization of
1928 // a static data member template outside the containing class?
Sebastian Redl35351a92010-01-31 22:27:38 +00001929 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00001930 if (isOutOfLine() &&
Richard Smith62f19e72016-06-25 00:15:56 +00001931 !(getCanonicalDecl()->isInline() &&
1932 getCanonicalDecl()->isConstexpr()) &&
Richard Smith8809a0c2013-09-27 20:14:12 +00001933 (hasInit() ||
1934 // If the first declaration is out-of-line, this may be an
1935 // instantiation of an out-of-line partial specialization of a variable
1936 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00001937 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00001938 ? getTemplateSpecializationKind() == TSK_Undeclared
1939 : getTemplateSpecializationKind() !=
1940 TSK_ExplicitSpecialization) ||
1941 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00001942 return Definition;
Richard Smith62f19e72016-06-25 00:15:56 +00001943 else if (!isOutOfLine() && isInline())
1944 return Definition;
Sebastian Redl35351a92010-01-31 22:27:38 +00001945 else
1946 return DeclarationOnly;
1947 }
1948 // C99 6.7p5:
1949 // A definition of an identifier is a declaration for that identifier that
1950 // [...] causes storage to be reserved for that object.
1951 // Note: that applies for all non-file-scope objects.
1952 // C99 6.9.2p1:
1953 // If the declaration of an identifier for an object has file scope and an
1954 // initializer, the declaration is an external definition for the identifier
1955 if (hasInit())
1956 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00001957
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001958 if (hasDefiningAttr())
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001959 return Definition;
1960
David Majnemerdd0bed12015-05-14 05:19:20 +00001961 if (const auto *SAA = getAttr<SelectAnyAttr>())
1962 if (!SAA->isInherited())
1963 return Definition;
1964
Richard Smith8809a0c2013-09-27 20:14:12 +00001965 // A variable template specialization (other than a static data member
1966 // template or an explicit specialization) is a declaration until we
1967 // instantiate its initializer.
1968 if (isa<VarTemplateSpecializationDecl>(this) &&
1969 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1970 return DeclarationOnly;
1971
Nico Weber608e7682015-04-15 23:04:24 +00001972 if (hasExternalStorage())
Sebastian Redl35351a92010-01-31 22:27:38 +00001973 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00001974
Rafael Espindolabff59562013-04-25 12:11:36 +00001975 // [dcl.link] p7:
1976 // A declaration directly contained in a linkage-specification is treated
1977 // as if it contains the extern specifier for the purpose of determining
1978 // the linkage of the declared name and whether it is a definition.
Nico Weber608e7682015-04-15 23:04:24 +00001979 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00001980 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00001981
Sebastian Redl35351a92010-01-31 22:27:38 +00001982 // C99 6.9.2p2:
1983 // A declaration of an object that has file scope without an initializer,
1984 // and without a storage class specifier or the scs 'static', constitutes
1985 // a tentative definition.
1986 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001987 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00001988 return TentativeDefinition;
1989
1990 // What's left is (in C, block-scope) declarations without initializers or
1991 // external storage. These are definitions.
1992 return Definition;
1993}
1994
Sebastian Redl35351a92010-01-31 22:27:38 +00001995VarDecl *VarDecl::getActingDefinition() {
1996 DefinitionKind Kind = isThisDeclarationADefinition();
1997 if (Kind != TentativeDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00001998 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00001999
Craig Topper36250ad2014-05-12 05:36:57 +00002000 VarDecl *LastTentative = nullptr;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002001 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002002 for (auto I : First->redecls()) {
2003 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00002004 if (Kind == Definition)
Craig Topper36250ad2014-05-12 05:36:57 +00002005 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002006 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00002007 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00002008 }
2009 return LastTentative;
2010}
2011
Daniel Dunbar9d355812012-03-09 01:51:51 +00002012VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002013 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002014 for (auto I : First->redecls()) {
2015 if (I->isThisDeclarationADefinition(C) == Definition)
2016 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002017 }
Craig Topper36250ad2014-05-12 05:36:57 +00002018 return nullptr;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002019}
2020
Daniel Dunbar9d355812012-03-09 01:51:51 +00002021VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00002022 DefinitionKind Kind = DeclarationOnly;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002023
Rafael Espindola8db352d2013-10-17 15:37:26 +00002024 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002025 for (auto I : First->redecls()) {
2026 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00002027 if (Kind == Definition)
2028 break;
2029 }
John McCall37bb6c92010-10-29 22:22:43 +00002030
2031 return Kind;
2032}
2033
Sebastian Redl5ca79842010-02-01 20:16:42 +00002034const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002035 for (auto I : redecls()) {
2036 if (auto Expr = I->getInit()) {
2037 D = I;
2038 return Expr;
2039 }
Sebastian Redl833ef452010-01-26 22:01:41 +00002040 }
Craig Topper36250ad2014-05-12 05:36:57 +00002041 return nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002042}
2043
Chandler Carruth813faed2015-12-30 02:51:00 +00002044bool VarDecl::hasInit() const {
2045 if (auto *P = dyn_cast<ParmVarDecl>(this))
2046 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2047 return false;
2048
2049 return !Init.isNull();
2050}
2051
2052Expr *VarDecl::getInit() {
2053 if (!hasInit())
2054 return nullptr;
2055
2056 if (auto *S = Init.dyn_cast<Stmt *>())
2057 return cast<Expr>(S);
2058
2059 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2060}
2061
2062Stmt **VarDecl::getInitAddress() {
2063 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2064 return &ES->Value;
2065
2066 return Init.getAddrOfPtr1();
2067}
2068
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002069bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002070 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002071 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00002072
2073 if (!isStaticDataMember())
2074 return false;
2075
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002076 // If this static data member was instantiated from a static data member of
2077 // a class template, check whether that static data member was defined
2078 // out-of-line.
2079 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2080 return VD->isOutOfLine();
2081
2082 return false;
2083}
2084
Douglas Gregord5058122010-02-11 01:19:42 +00002085void VarDecl::setInit(Expr *I) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002086 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
Sebastian Redl833ef452010-01-26 22:01:41 +00002087 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00002088 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00002089 }
2090
2091 Init = I;
2092}
2093
Daniel Dunbar9d355812012-03-09 01:51:51 +00002094bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002095 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00002096
Richard Smith35ecb362012-03-02 04:14:40 +00002097 if (!Lang.CPlusPlus)
2098 return false;
2099
2100 // In C++11, any variable of reference type can be used in a constant
2101 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002102 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00002103 return true;
2104
2105 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00002106 // not require the variable to be non-volatile, but we consider this to be a
2107 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00002108 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00002109 return false;
2110
2111 // In C++, const, non-volatile variables of integral or enumeration types
2112 // can be used in constant expressions.
2113 if (getType()->isIntegralOrEnumerationType())
2114 return true;
2115
Richard Smith35ecb362012-03-02 04:14:40 +00002116 // Additionally, in C++11, non-volatile constexpr variables can be used in
2117 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002118 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00002119}
2120
Richard Smithd0b4dd62011-12-19 06:19:21 +00002121/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2122/// form, which contains extra information on the evaluated value of the
2123/// initializer.
2124EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002125 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002126 if (!Eval) {
Manuel Klimeka7328992013-06-03 13:51:33 +00002127 // Note: EvaluatedStmt contains an APValue, which usually holds
2128 // resources not allocated from the ASTContext. We need to do some
2129 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2130 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002131 Eval = new (getASTContext()) EvaluatedStmt;
Chandler Carruth813faed2015-12-30 02:51:00 +00002132 Eval->Value = Init.get<Stmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002133 Init = Eval;
2134 }
2135 return Eval;
2136}
2137
Richard Smithdafff942012-01-14 04:30:29 +00002138APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002139 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00002140 return evaluateValue(Notes);
2141}
2142
Manuel Klimeka7328992013-06-03 13:51:33 +00002143namespace {
2144// Destroy an APValue that was allocated in an ASTContext.
2145void DestroyAPValue(void* UntypedValue) {
2146 static_cast<APValue*>(UntypedValue)->~APValue();
2147}
2148} // namespace
2149
Richard Smithdafff942012-01-14 04:30:29 +00002150APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002151 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002152 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2153
2154 // We only produce notes indicating why an initializer is non-constant the
2155 // first time it is evaluated. FIXME: The notes won't always be emitted the
2156 // first time we try evaluation, so might not be produced at all.
2157 if (Eval->WasEvaluated)
Craig Topper36250ad2014-05-12 05:36:57 +00002158 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002159
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002160 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002161 assert(!Init->isValueDependent());
2162
2163 if (Eval->IsEvaluating) {
2164 // FIXME: Produce a diagnostic for self-initialization.
2165 Eval->CheckedICE = true;
2166 Eval->IsICE = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002167 return nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002168 }
2169
2170 Eval->IsEvaluating = true;
2171
2172 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2173 this, Notes);
2174
Manuel Klimeka7328992013-06-03 13:51:33 +00002175 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2176 // or that it's empty (so that there's nothing to clean up) if evaluation
2177 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002178 if (!Result)
2179 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00002180 else if (Eval->Evaluated.needsCleanup())
2181 getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002182
2183 Eval->IsEvaluating = false;
2184 Eval->WasEvaluated = true;
2185
2186 // In C++11, we have determined whether the initializer was a constant
2187 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002188 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002189 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00002190 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002191 }
2192
Craig Topper36250ad2014-05-12 05:36:57 +00002193 return Result ? &Eval->Evaluated : nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002194}
2195
Chandler Carruth813faed2015-12-30 02:51:00 +00002196APValue *VarDecl::getEvaluatedValue() const {
2197 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2198 if (Eval->WasEvaluated)
2199 return &Eval->Evaluated;
2200
2201 return nullptr;
2202}
2203
2204bool VarDecl::isInitKnownICE() const {
2205 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2206 return Eval->CheckedICE;
2207
2208 return false;
2209}
2210
2211bool VarDecl::isInitICE() const {
2212 assert(isInitKnownICE() &&
2213 "Check whether we already know that the initializer is an ICE");
2214 return Init.get<EvaluatedStmt *>()->IsICE;
2215}
2216
Richard Smithd0b4dd62011-12-19 06:19:21 +00002217bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00002218 // Initializers of weak variables are never ICEs.
2219 if (isWeak())
2220 return false;
2221
Richard Smithd0b4dd62011-12-19 06:19:21 +00002222 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2223 if (Eval->CheckedICE)
2224 // We have already checked whether this subexpression is an
2225 // integral constant expression.
2226 return Eval->IsICE;
2227
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002228 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002229 assert(!Init->isValueDependent());
2230
2231 // In C++11, evaluate the initializer to check whether it's a constant
2232 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002233 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002234 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002235 evaluateValue(Notes);
2236 return Eval->IsICE;
2237 }
2238
2239 // It's an ICE whether or not the definition we found is
2240 // out-of-line. See DR 721 and the discussion in Clang PR
2241 // 6206 for details.
2242
2243 if (Eval->CheckingICE)
2244 return false;
2245 Eval->CheckingICE = true;
2246
2247 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2248 Eval->CheckingICE = false;
2249 Eval->CheckedICE = true;
2250 return Eval->IsICE;
2251}
2252
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002253VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002254 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002255 return cast<VarDecl>(MSI->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002256
2257 return nullptr;
Douglas Gregor86d142a2009-10-08 07:24:58 +00002258}
2259
Douglas Gregor3c74d412009-10-14 20:14:33 +00002260TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002261 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002262 return Spec->getSpecializationKind();
2263
Sebastian Redl35351a92010-01-31 22:27:38 +00002264 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002265 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002266
Douglas Gregor86d142a2009-10-08 07:24:58 +00002267 return TSK_Undeclared;
2268}
2269
Richard Smith8809a0c2013-09-27 20:14:12 +00002270SourceLocation VarDecl::getPointOfInstantiation() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002271 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Richard Smith8809a0c2013-09-27 20:14:12 +00002272 return Spec->getPointOfInstantiation();
2273
2274 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2275 return MSI->getPointOfInstantiation();
2276
2277 return SourceLocation();
2278}
2279
Larisse Voufo39a1e502013-08-06 01:03:05 +00002280VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2281 return getASTContext().getTemplateOrSpecializationInfo(this)
2282 .dyn_cast<VarTemplateDecl *>();
2283}
2284
2285void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2286 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2287}
2288
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002289MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002290 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002291 // FIXME: Remove ?
2292 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2293 return getASTContext().getTemplateOrSpecializationInfo(this)
2294 .dyn_cast<MemberSpecializationInfo *>();
Craig Topper36250ad2014-05-12 05:36:57 +00002295 return nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002296}
2297
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002298void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2299 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002300 assert((isa<VarTemplateSpecializationDecl>(this) ||
2301 getMemberSpecializationInfo()) &&
2302 "not a variable or static data member template specialization");
2303
Larisse Voufo39a1e502013-08-06 01:03:05 +00002304 if (VarTemplateSpecializationDecl *Spec =
2305 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2306 Spec->setSpecializationKind(TSK);
2307 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2308 Spec->getPointOfInstantiation().isInvalid())
2309 Spec->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002310 }
2311
2312 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2313 MSI->setTemplateSpecializationKind(TSK);
2314 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2315 MSI->getPointOfInstantiation().isInvalid())
2316 MSI->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002317 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002318}
2319
2320void
2321VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2322 TemplateSpecializationKind TSK) {
2323 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2324 "Previous template or instantiation?");
2325 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002326}
2327
Sebastian Redl833ef452010-01-26 22:01:41 +00002328//===----------------------------------------------------------------------===//
2329// ParmVarDecl Implementation
2330//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002331
Sebastian Redl833ef452010-01-26 22:01:41 +00002332ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002333 SourceLocation StartLoc,
2334 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002335 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002336 StorageClass S, Expr *DefArg) {
Richard Smith053f6c62014-05-16 23:01:30 +00002337 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smithf7981722013-11-22 09:01:48 +00002338 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002339}
2340
Reid Kleckner8a365022013-06-24 17:51:48 +00002341QualType ParmVarDecl::getOriginalType() const {
2342 TypeSourceInfo *TSI = getTypeSourceInfo();
2343 QualType T = TSI ? TSI->getType() : getType();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002344 if (const auto *DT = dyn_cast<DecayedType>(T))
Reid Kleckner8a365022013-06-24 17:51:48 +00002345 return DT->getOriginalType();
2346 return T;
2347}
2348
Douglas Gregor72172e92012-01-05 21:55:30 +00002349ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00002350 return new (C, ID)
2351 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2352 nullptr, QualType(), nullptr, SC_None, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00002353}
2354
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002355SourceRange ParmVarDecl::getSourceRange() const {
2356 if (!hasInheritedDefaultArg()) {
2357 SourceRange ArgRange = getDefaultArgRange();
2358 if (ArgRange.isValid())
2359 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2360 }
2361
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002362 // DeclaratorDecl considers the range of postfix types as overlapping with the
2363 // declaration name, but this is not the case with parameters in ObjC methods.
2364 if (isa<ObjCMethodDecl>(getDeclContext()))
2365 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2366
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002367 return DeclaratorDecl::getSourceRange();
2368}
2369
Sebastian Redl833ef452010-01-26 22:01:41 +00002370Expr *ParmVarDecl::getDefaultArg() {
2371 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2372 assert(!hasUninstantiatedDefaultArg() &&
2373 "Default argument is not yet instantiated!");
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002374
Sebastian Redl833ef452010-01-26 22:01:41 +00002375 Expr *Arg = getInit();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002376 if (auto *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002377 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002378
Sebastian Redl833ef452010-01-26 22:01:41 +00002379 return Arg;
2380}
2381
Chandler Carruth813faed2015-12-30 02:51:00 +00002382void ParmVarDecl::setDefaultArg(Expr *defarg) {
2383 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2384 Init = defarg;
2385}
Sebastian Redl833ef452010-01-26 22:01:41 +00002386
Chandler Carruth813faed2015-12-30 02:51:00 +00002387SourceRange ParmVarDecl::getDefaultArgRange() const {
2388 switch (ParmVarDeclBits.DefaultArgKind) {
2389 case DAK_None:
2390 case DAK_Unparsed:
2391 // Nothing we can do here.
2392 return SourceRange();
2393
2394 case DAK_Uninstantiated:
Sebastian Redl833ef452010-01-26 22:01:41 +00002395 return getUninstantiatedDefaultArg()->getSourceRange();
2396
Chandler Carruth813faed2015-12-30 02:51:00 +00002397 case DAK_Normal:
2398 if (const Expr *E = getInit())
2399 return E->getSourceRange();
2400
2401 // Missing an actual expression, may be invalid.
2402 return SourceRange();
2403 }
2404 llvm_unreachable("Invalid default argument kind.");
2405}
2406
2407void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2408 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2409 Init = arg;
2410}
2411
2412Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2413 assert(hasUninstantiatedDefaultArg() &&
2414 "Wrong kind of initialization expression!");
2415 return cast_or_null<Expr>(Init.get<Stmt *>());
2416}
2417
2418bool ParmVarDecl::hasDefaultArg() const {
2419 // FIXME: We should just return false for DAK_None here once callers are
2420 // prepared for the case that we encountered an invalid default argument and
2421 // were unable to even build an invalid expression.
2422 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2423 !Init.isNull();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002424}
2425
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00002426bool ParmVarDecl::isParameterPack() const {
2427 return isa<PackExpansionType>(getType());
2428}
2429
Ted Kremenek540017e2011-10-06 05:00:56 +00002430void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2431 getASTContext().setParameterIndex(this, parameterIndex);
2432 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2433}
2434
2435unsigned ParmVarDecl::getParameterIndexLarge() const {
2436 return getASTContext().getParameterIndex(this);
2437}
2438
Nuno Lopes394ec982008-12-17 23:39:55 +00002439//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002440// FunctionDecl Implementation
2441//===----------------------------------------------------------------------===//
2442
Benjamin Kramer9170e912013-02-22 15:46:01 +00002443void FunctionDecl::getNameForDiagnostic(
2444 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2445 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002446 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2447 if (TemplateArgs)
Benjamin Kramer9170e912013-02-22 15:46:01 +00002448 TemplateSpecializationType::PrintTemplateArgumentList(
David Majnemer6fbeee32016-07-07 04:43:07 +00002449 OS, TemplateArgs->asArray(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002450}
2451
Ted Kremenek186a0742010-04-29 16:49:01 +00002452bool FunctionDecl::isVariadic() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002453 if (const auto *FT = getType()->getAs<FunctionProtoType>())
Ted Kremenek186a0742010-04-29 16:49:01 +00002454 return FT->isVariadic();
2455 return false;
2456}
2457
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002458bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002459 for (auto I : redecls()) {
Francois Pichet1c229c02011-04-22 22:18:13 +00002460 if (I->Body || I->IsLateTemplateParsed) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002461 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002462 return true;
2463 }
2464 }
2465
2466 return false;
2467}
2468
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002469bool FunctionDecl::hasTrivialBody() const
2470{
2471 Stmt *S = getBody();
2472 if (!S) {
2473 // Since we don't have a body for this function, we don't know if it's
2474 // trivial or not.
2475 return false;
2476 }
2477
2478 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2479 return true;
2480 return false;
2481}
2482
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002483bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002484 for (auto I : redecls()) {
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002485 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
Dmitry Polukhin85eda122016-04-11 07:48:59 +00002486 I->hasDefiningAttr()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002487 Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002488 return true;
2489 }
2490 }
2491
2492 return false;
2493}
2494
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002495Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002496 if (!hasBody(Definition))
Craig Topper36250ad2014-05-12 05:36:57 +00002497 return nullptr;
Rafael Espindola44503012013-10-19 01:37:17 +00002498
2499 if (Definition->Body)
2500 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002501
Craig Topper36250ad2014-05-12 05:36:57 +00002502 return nullptr;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002503}
2504
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002505void FunctionDecl::setBody(Stmt *B) {
2506 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002507 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002508 EndRangeLoc = B->getLocEnd();
2509}
2510
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002511void FunctionDecl::setPure(bool P) {
2512 IsPure = P;
2513 if (P)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002514 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002515 Parent->markedVirtualFunctionPure();
2516}
2517
Richard Smith8d0dc312013-07-21 23:12:18 +00002518template<std::size_t Len>
2519static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2520 IdentifierInfo *II = ND->getIdentifier();
2521 return II && II->isStr(Str);
2522}
2523
Douglas Gregor16618f22009-09-12 00:17:51 +00002524bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002525 const TranslationUnitDecl *tunit =
2526 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2527 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002528 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002529 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002530}
2531
David Majnemerc729b0b2013-09-16 22:44:20 +00002532bool FunctionDecl::isMSVCRTEntryPoint() const {
2533 const TranslationUnitDecl *TUnit =
2534 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2535 if (!TUnit)
2536 return false;
2537
2538 // Even though we aren't really targeting MSVCRT if we are freestanding,
2539 // semantic analysis for these functions remains the same.
2540
2541 // MSVCRT entry points only exist on MSVCRT targets.
2542 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2543 return false;
2544
2545 // Nameless functions like constructors cannot be entry points.
2546 if (!getIdentifier())
2547 return false;
2548
2549 return llvm::StringSwitch<bool>(getName())
2550 .Cases("main", // an ANSI console app
2551 "wmain", // a Unicode console App
2552 "WinMain", // an ANSI GUI app
2553 "wWinMain", // a Unicode GUI app
2554 "DllMain", // a DLL
2555 true)
2556 .Default(false);
2557}
2558
John McCall53ffd372011-05-15 17:49:20 +00002559bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2560 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2561 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2562 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2563 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2564 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2565
Richard Smithf6004412014-01-19 23:25:37 +00002566 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2567 return false;
John McCall53ffd372011-05-15 17:49:20 +00002568
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002569 const auto *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002570 if (proto->getNumParams() != 2 || proto->isVariadic())
2571 return false;
John McCall53ffd372011-05-15 17:49:20 +00002572
2573 ASTContext &Context =
2574 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2575 ->getASTContext();
2576
2577 // The result type and first argument type are constant across all
2578 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002579 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002580}
2581
Richard Smith8d0dc312013-07-21 23:12:18 +00002582bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2583 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2584 return false;
2585 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2586 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2587 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2588 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2589 return false;
2590
2591 if (isa<CXXRecordDecl>(getDeclContext()))
2592 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002593
2594 // This can only fail for an invalid 'operator new' declaration.
2595 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2596 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002597
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002598 const auto *FPT = getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00002599 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002600 return false;
2601
2602 // If this is a single-parameter function, it must be a replaceable global
2603 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002604 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002605 return true;
2606
Richard Smithb2f0f052016-10-10 18:54:32 +00002607 unsigned Params = 1;
2608 QualType Ty = FPT->getParamType(Params);
Richard Smith1cdec012013-09-29 04:40:38 +00002609 ASTContext &Ctx = getASTContext();
Richard Smithb2f0f052016-10-10 18:54:32 +00002610
2611 auto Consume = [&] {
2612 ++Params;
2613 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
2614 };
2615
2616 // In C++14, the next parameter can be a 'std::size_t' for sized delete.
2617 bool IsSizedDelete = false;
Richard Smithb47c36f2013-11-05 09:12:18 +00002618 if (Ctx.getLangOpts().SizedDeallocation &&
Richard Smithb2f0f052016-10-10 18:54:32 +00002619 (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2620 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
2621 Ctx.hasSameType(Ty, Ctx.getSizeType())) {
2622 IsSizedDelete = true;
2623 Consume();
2624 }
2625
2626 // In C++17, the next parameter can be a 'std::align_val_t' for aligned
2627 // new/delete.
2628 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT())
2629 Consume();
2630
2631 // Finally, if this is not a sized delete, the final parameter can
2632 // be a 'const std::nothrow_t&'.
2633 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
2634 Ty = Ty->getPointeeType();
2635 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2636 return false;
2637 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2638 if (RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace())
2639 Consume();
2640 }
2641
2642 return Params == FPT->getNumParams();
Richard Smith8d0dc312013-07-21 23:12:18 +00002643}
2644
Rafael Espindolaf4187652013-02-14 01:18:37 +00002645LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00002646 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002647}
2648
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002649bool FunctionDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00002650 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002651}
2652
Rafael Espindola593537a2013-05-05 20:15:21 +00002653bool FunctionDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002654 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002655}
2656
2657bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002658 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002659}
2660
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002661bool FunctionDecl::isGlobal() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002662 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002663 return Method->isStatic();
2664
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002665 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002666 return false;
2667
Mike Stump11289f42009-09-09 15:08:12 +00002668 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002669 DC->isNamespace();
2670 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002671 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002672 if (!Namespace->getDeclName())
2673 return false;
2674 break;
2675 }
2676 }
2677
2678 return true;
2679}
2680
Richard Smith10876ef2013-01-17 01:30:42 +00002681bool FunctionDecl::isNoReturn() const {
Adrian Prantl721c7cb2016-08-17 16:42:15 +00002682 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2683 hasAttr<C11NoReturnAttr>())
2684 return true;
2685
2686 if (auto *FnTy = getType()->getAs<FunctionType>())
2687 return FnTy->getNoReturnAttr();
2688
2689 return false;
Richard Smith10876ef2013-01-17 01:30:42 +00002690}
2691
Sebastian Redl833ef452010-01-26 22:01:41 +00002692void
2693FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002694 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002695
2696 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2697 FunctionTemplateDecl *PrevFunTmpl
Craig Topper36250ad2014-05-12 05:36:57 +00002698 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002699 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00002700 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002701 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002702
Axel Naumannfbc7b982011-11-08 18:21:06 +00002703 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002704 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002705}
2706
Rafael Espindola8db352d2013-10-17 15:37:26 +00002707FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002708
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002709/// \brief Returns a value indicating whether this function
2710/// corresponds to a builtin function.
2711///
2712/// The function corresponds to a built-in function if it is
2713/// declared at translation scope or within an extern "C" block and
2714/// its name matches with the name of a builtin. The returned value
2715/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002716/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002717/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002718unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002719 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002720 return 0;
2721
2722 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002723 if (!BuiltinID)
2724 return 0;
2725
2726 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00002727 if (Context.getLangOpts().CPlusPlus) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002728 const auto *LinkageDecl =
2729 dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
Warren Hunt445d83e2013-11-01 23:46:51 +00002730 // In C++, the first declaration of a builtin is always inside an implicit
2731 // extern "C".
2732 // FIXME: A recognised library function may not be directly in an extern "C"
2733 // declaration, for instance "extern "C" { namespace std { decl } }".
David Majnemerba3e5ec2015-03-13 18:26:17 +00002734 if (!LinkageDecl) {
2735 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
David Majnemer145abde2016-01-26 01:12:17 +00002736 Context.getTargetInfo().getCXXABI().isMicrosoft())
David Majnemerba3e5ec2015-03-13 18:26:17 +00002737 return Builtin::BI__GetExceptionInfo;
2738 return 0;
2739 }
2740 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
Warren Hunt445d83e2013-11-01 23:46:51 +00002741 return 0;
2742 }
2743
2744 // If the function is marked "overloadable", it has a different mangled name
2745 // and is not the C library function.
Aaron Ballman9ead1242013-12-19 02:39:40 +00002746 if (hasAttr<OverloadableAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00002747 return 0;
2748
Douglas Gregore711f702009-02-14 18:57:46 +00002749 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2750 return BuiltinID;
2751
2752 // This function has the name of a known C library
2753 // function. Determine whether it actually refers to the C library
2754 // function or whether it just has the same name.
2755
Douglas Gregora908e7f2009-02-17 03:23:10 +00002756 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002757 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002758 return 0;
2759
Anastasia Stulova1202de32016-02-12 12:07:04 +00002760 // OpenCL v1.2 s6.9.f - The library functions defined in
2761 // the C99 standard headers are not available.
2762 if (Context.getLangOpts().OpenCL &&
2763 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2764 return 0;
2765
Warren Hunt445d83e2013-11-01 23:46:51 +00002766 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002767}
2768
2769
Chris Lattner47c0d002009-04-25 06:03:53 +00002770/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002771/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002772/// after it has been created.
2773unsigned FunctionDecl::getNumParams() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002774 const auto *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002775 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002776}
2777
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002778void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002779 ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00002780 assert(!ParamInfo && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002781 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002782
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002783 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002784 if (!NewParamInfo.empty()) {
2785 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2786 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002787 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002788}
Chris Lattner41943152007-01-25 04:52:46 +00002789
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002790void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
James Molloy6f8780b2012-02-29 10:24:19 +00002791 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2792
2793 if (!NewDecls.empty()) {
2794 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2795 std::copy(NewDecls.begin(), NewDecls.end(), A);
Craig Topper5fc8fc22014-08-27 06:28:36 +00002796 DeclsInPrototypeScope = llvm::makeArrayRef(A, NewDecls.size());
Serge Pavlova8261472014-06-25 17:09:41 +00002797 // Move declarations introduced in prototype to the function context.
2798 for (auto I : NewDecls) {
2799 DeclContext *DC = I->getDeclContext();
2800 // Forward-declared reference to an enumeration is not added to
2801 // declaration scope, so skip declaration that is absent from its
2802 // declaration contexts.
2803 if (DC->containsDecl(I)) {
2804 DC->removeDecl(I);
2805 I->setDeclContext(this);
2806 addDecl(I);
2807 }
2808 }
James Molloy6f8780b2012-02-29 10:24:19 +00002809 }
2810}
2811
Chris Lattner58258242008-04-10 02:22:51 +00002812/// getMinRequiredArguments - Returns the minimum number of arguments
2813/// needed to call this function. This may be fewer than the number of
2814/// function parameters, if some of the parameters have default
Richard Smith91151782014-04-01 19:18:16 +00002815/// arguments (in C++) or are parameter packs (C++11).
Chris Lattner58258242008-04-10 02:22:51 +00002816unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002817 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002818 return getNumParams();
Chris Lattner58258242008-04-10 02:22:51 +00002819
Richard Smith91151782014-04-01 19:18:16 +00002820 unsigned NumRequiredArgs = 0;
David Majnemer59f77922016-06-24 04:05:48 +00002821 for (auto *Param : parameters())
Richard Smith91151782014-04-01 19:18:16 +00002822 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2823 ++NumRequiredArgs;
Chris Lattner58258242008-04-10 02:22:51 +00002824 return NumRequiredArgs;
2825}
2826
David Majnemer54e3ba52014-04-02 23:17:29 +00002827/// \brief The combination of the extern and inline keywords under MSVC forces
2828/// the function to be required.
2829///
2830/// Note: This function assumes that we will only get called when isInlined()
2831/// would return true for this FunctionDecl.
2832bool FunctionDecl::isMSExternInline() const {
2833 assert(isInlined() && "expected to get called on an inlined function!");
2834
2835 const ASTContext &Context = getASTContext();
David Majnemer3f021502015-10-08 04:53:31 +00002836 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2837 !hasAttr<DLLExportAttr>())
David Majnemer54e3ba52014-04-02 23:17:29 +00002838 return false;
2839
David Majnemer73768702015-03-20 00:02:27 +00002840 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
2841 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002842 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002843 return true;
2844
2845 return false;
2846}
2847
2848static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
2849 if (Redecl->getStorageClass() != SC_Extern)
2850 return false;
2851
2852 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
2853 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002854 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002855 return false;
2856
2857 return true;
2858}
2859
Eli Friedman1b125c32012-02-07 03:50:18 +00002860static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2861 // Only consider file-scope declarations in this test.
2862 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2863 return false;
2864
2865 // Only consider explicit declarations; the presence of a builtin for a
2866 // libcall shouldn't affect whether a definition is externally visible.
2867 if (Redecl->isImplicit())
2868 return false;
2869
2870 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2871 return true; // Not an inline definition
2872
2873 return false;
2874}
2875
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002876/// \brief For a function declaration in C or C++, determine whether this
2877/// declaration causes the definition to be externally visible.
2878///
David Majnemer54e3ba52014-04-02 23:17:29 +00002879/// For instance, this determines if adding the current declaration to the set
Eli Friedman1b125c32012-02-07 03:50:18 +00002880/// of redeclarations of the given functions causes
2881/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002882bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2883 assert(!doesThisDeclarationHaveABody() &&
2884 "Must have a declaration without a body.");
2885
2886 ASTContext &Context = getASTContext();
2887
David Majnemer54e3ba52014-04-02 23:17:29 +00002888 if (Context.getLangOpts().MSVCCompat) {
2889 const FunctionDecl *Definition;
2890 if (hasBody(Definition) && Definition->isInlined() &&
2891 redeclForcesDefMSVC(this))
2892 return true;
2893 }
2894
David Blaikiebbafb8a2012-03-11 07:00:24 +00002895 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002896 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2897 // an externally visible definition.
2898 //
2899 // FIXME: What happens if gnu_inline gets added on after the first
2900 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002901 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002902 return false;
2903
2904 const FunctionDecl *Prev = this;
2905 bool FoundBody = false;
2906 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002907 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002908
2909 if (Prev->Body) {
2910 // If it's not the case that both 'inline' and 'extern' are
2911 // specified on the definition, then it is always externally visible.
2912 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002913 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002914 return false;
2915 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002916 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002917 return false;
2918 }
2919 }
2920 return FoundBody;
2921 }
2922
David Blaikiebbafb8a2012-03-11 07:00:24 +00002923 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002924 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002925
2926 // C99 6.7.4p6:
2927 // [...] If all of the file scope declarations for a function in a
2928 // translation unit include the inline function specifier without extern,
2929 // then the definition in that translation unit is an inline definition.
2930 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002931 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002932 const FunctionDecl *Prev = this;
2933 bool FoundBody = false;
2934 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002935 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002936 if (RedeclForcesDefC99(Prev))
2937 return false;
2938 }
2939 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002940}
2941
Alp Tokerd0787eb2014-07-02 01:47:15 +00002942SourceRange FunctionDecl::getReturnTypeSourceRange() const {
2943 const TypeSourceInfo *TSI = getTypeSourceInfo();
2944 if (!TSI)
2945 return SourceRange();
Alp Tokerf5b10792014-07-02 12:55:58 +00002946 FunctionTypeLoc FTL =
2947 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
2948 if (!FTL)
Alp Tokerd0787eb2014-07-02 01:47:15 +00002949 return SourceRange();
2950
Alp Tokerf5b10792014-07-02 12:55:58 +00002951 // Skip self-referential return types.
2952 const SourceManager &SM = getASTContext().getSourceManager();
2953 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
2954 SourceLocation Boundary = getNameInfo().getLocStart();
2955 if (RTRange.isInvalid() || Boundary.isInvalid() ||
2956 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
2957 return SourceRange();
Alp Tokerd0787eb2014-07-02 01:47:15 +00002958
Alp Tokerf5b10792014-07-02 12:55:58 +00002959 return RTRange;
Alp Tokerd0787eb2014-07-02 01:47:15 +00002960}
2961
Aaron Ballmane7964782016-03-07 22:44:55 +00002962const Attr *FunctionDecl::getUnusedResultAttr() const {
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002963 QualType RetType = getReturnType();
2964 if (RetType->isRecordType()) {
2965 const CXXRecordDecl *Ret = RetType->getAsCXXRecordDecl();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002966 const auto *MD = dyn_cast<CXXMethodDecl>(this);
Aaron Ballmane7964782016-03-07 22:44:55 +00002967 if (Ret && !(MD && MD->getCorrespondingMethodInClass(Ret, true))) {
2968 if (const auto *R = Ret->getAttr<WarnUnusedResultAttr>())
2969 return R;
2970 }
2971 } else if (const auto *ET = RetType->getAs<EnumType>()) {
2972 if (const EnumDecl *ED = ET->getDecl()) {
2973 if (const auto *R = ED->getAttr<WarnUnusedResultAttr>())
2974 return R;
2975 }
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002976 }
Aaron Ballmane7964782016-03-07 22:44:55 +00002977 return getAttr<WarnUnusedResultAttr>();
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002978}
2979
Richard Smithf3814ad2013-01-25 00:08:28 +00002980/// \brief For an inline function definition in C, or for a gnu_inline function
2981/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002982///
2983/// Inline function definitions are always available for inlining optimizations.
2984/// However, depending on the language dialect, declaration specifiers, and
2985/// attributes, the definition of an inline function may or may not be
2986/// "externally" visible to other translation units in the program.
2987///
2988/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00002989/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00002990/// inline definition becomes externally visible (C99 6.7.4p6).
2991///
2992/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2993/// definition, we use the GNU semantics for inline, which are nearly the
2994/// opposite of C99 semantics. In particular, "inline" by itself will create
2995/// an externally visible symbol, but "extern inline" will not create an
2996/// externally visible symbol.
2997bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002998 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002999 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00003000 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00003001
David Blaikiebbafb8a2012-03-11 07:00:24 +00003002 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003003 // Note: If you change the logic here, please change
3004 // doesDeclarationForceExternallyVisibleDefinition as well.
3005 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00003006 // If it's not the case that both 'inline' and 'extern' are
3007 // specified on the definition, then this inline definition is
3008 // externally visible.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003009 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00003010 return true;
3011
3012 // If any declaration is 'inline' but not 'extern', then this definition
3013 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00003014 for (auto Redecl : redecls()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00003015 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003016 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00003017 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00003018 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00003019
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003020 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003021 }
Eli Friedman1b125c32012-02-07 03:50:18 +00003022
Richard Smithf3814ad2013-01-25 00:08:28 +00003023 // The rest of this function is C-only.
3024 assert(!Context.getLangOpts().CPlusPlus &&
3025 "should not use C inline rules in C++");
3026
Douglas Gregor299d76e2009-09-13 07:46:26 +00003027 // C99 6.7.4p6:
3028 // [...] If all of the file scope declarations for a function in a
3029 // translation unit include the inline function specifier without extern,
3030 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00003031 for (auto Redecl : redecls()) {
3032 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00003033 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003034 }
3035
3036 // C99 6.7.4p6:
3037 // An inline definition does not provide an external definition for the
3038 // function, and does not forbid an external definition in another
3039 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003040 return false;
3041}
3042
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003043/// getOverloadedOperator - Which C++ overloaded operator this
3044/// function represents, if any.
3045OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00003046 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3047 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003048 else
3049 return OO_None;
3050}
3051
Alexis Huntc88db062010-01-13 09:01:02 +00003052/// getLiteralIdentifier - The literal suffix identifier this function
3053/// represents, if any.
3054const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3055 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3056 return getDeclName().getCXXLiteralIdentifier();
3057 else
Craig Topper36250ad2014-05-12 05:36:57 +00003058 return nullptr;
Alexis Huntc88db062010-01-13 09:01:02 +00003059}
3060
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003061FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3062 if (TemplateOrSpecialization.isNull())
3063 return TK_NonTemplate;
3064 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3065 return TK_FunctionTemplate;
3066 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3067 return TK_MemberSpecialization;
3068 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3069 return TK_FunctionTemplateSpecialization;
3070 if (TemplateOrSpecialization.is
3071 <DependentFunctionTemplateSpecializationInfo*>())
3072 return TK_DependentFunctionTemplateSpecialization;
3073
David Blaikie83d382b2011-09-23 05:06:16 +00003074 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003075}
3076
Douglas Gregord801b062009-10-07 23:56:10 +00003077FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00003078 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00003079 return cast<FunctionDecl>(Info->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00003080
3081 return nullptr;
Douglas Gregord801b062009-10-07 23:56:10 +00003082}
3083
Chandler Carruth21c90602015-12-30 03:24:14 +00003084MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3085 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>();
3086}
3087
Douglas Gregord801b062009-10-07 23:56:10 +00003088void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003089FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3090 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00003091 TemplateSpecializationKind TSK) {
3092 assert(TemplateOrSpecialization.isNull() &&
3093 "Member function is already a specialization");
3094 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003095 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00003096 TemplateOrSpecialization = Info;
3097}
3098
Chandler Carruth21c90602015-12-30 03:24:14 +00003099FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3100 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3101}
3102
3103void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3104 TemplateOrSpecialization = Template;
3105}
3106
Douglas Gregorafca3b42009-10-27 20:53:28 +00003107bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00003108 // If the function is invalid, it can't be implicitly instantiated.
3109 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00003110 return false;
3111
3112 switch (getTemplateSpecializationKind()) {
3113 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00003114 case TSK_ExplicitInstantiationDefinition:
3115 return false;
3116
3117 case TSK_ImplicitInstantiation:
3118 return true;
3119
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003120 // It is possible to instantiate TSK_ExplicitSpecialization kind
3121 // if the FunctionDecl has a class scope specialization pattern.
3122 case TSK_ExplicitSpecialization:
Craig Topper36250ad2014-05-12 05:36:57 +00003123 return getClassScopeSpecializationPattern() != nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003124
Douglas Gregorafca3b42009-10-27 20:53:28 +00003125 case TSK_ExplicitInstantiationDeclaration:
3126 // Handled below.
3127 break;
3128 }
3129
3130 // Find the actual template from which we will instantiate.
3131 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003132 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003133 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003134 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00003135
3136 // C++0x [temp.explicit]p9:
3137 // Except for inline functions, other explicit instantiation declarations
3138 // have the effect of suppressing the implicit instantiation of the entity
3139 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003140 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00003141 return true;
3142
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003143 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00003144}
3145
3146bool FunctionDecl::isTemplateInstantiation() const {
3147 switch (getTemplateSpecializationKind()) {
3148 case TSK_Undeclared:
3149 case TSK_ExplicitSpecialization:
3150 return false;
3151 case TSK_ImplicitInstantiation:
3152 case TSK_ExplicitInstantiationDeclaration:
3153 case TSK_ExplicitInstantiationDefinition:
3154 return true;
3155 }
3156 llvm_unreachable("All TSK values handled.");
3157}
Douglas Gregorafca3b42009-10-27 20:53:28 +00003158
3159FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003160 // Handle class scope explicit specialization special case.
3161 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3162 return getClassScopeSpecializationPattern();
Faisal Valib90b2112014-04-03 16:32:21 +00003163
3164 // If this is a generic lambda call operator specialization, its
3165 // instantiation pattern is always its primary template's pattern
3166 // even if its primary template was instantiated from another
3167 // member template (which happens with nested generic lambdas).
3168 // Since a lambda's call operator's body is transformed eagerly,
3169 // we don't have to go hunting for a prototype definition template
3170 // (i.e. instantiated-from-member-template) to use as an instantiation
3171 // pattern.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003172
Faisal Valib90b2112014-04-03 16:32:21 +00003173 if (isGenericLambdaCallOperatorSpecialization(
3174 dyn_cast<CXXMethodDecl>(this))) {
3175 assert(getPrimaryTemplate() && "A generic lambda specialization must be "
3176 "generated from a primary call operator "
3177 "template");
3178 assert(getPrimaryTemplate()->getTemplatedDecl()->getBody() &&
3179 "A generic lambda call operator template must always have a body - "
3180 "even if instantiated from a prototype (i.e. as written) member "
3181 "template");
3182 return getPrimaryTemplate()->getTemplatedDecl();
3183 }
3184
Douglas Gregorafca3b42009-10-27 20:53:28 +00003185 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3186 while (Primary->getInstantiatedFromMemberTemplate()) {
3187 // If we have hit a point where the user provided a specialization of
3188 // this template, we're done looking.
3189 if (Primary->isMemberSpecialization())
3190 break;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003191 Primary = Primary->getInstantiatedFromMemberTemplate();
3192 }
3193
3194 return Primary->getTemplatedDecl();
3195 }
3196
3197 return getInstantiatedFromMemberFunction();
3198}
3199
Douglas Gregor70d83e22009-06-29 17:30:29 +00003200FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00003201 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003202 = TemplateOrSpecialization
3203 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00003204 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00003205 }
Craig Topper36250ad2014-05-12 05:36:57 +00003206 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003207}
3208
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003209FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3210 return getASTContext().getClassScopeSpecializationPattern(this);
3211}
3212
Chandler Carruth21c90602015-12-30 03:24:14 +00003213FunctionTemplateSpecializationInfo *
3214FunctionDecl::getTemplateSpecializationInfo() const {
3215 return TemplateOrSpecialization
3216 .dyn_cast<FunctionTemplateSpecializationInfo *>();
3217}
3218
Douglas Gregor70d83e22009-06-29 17:30:29 +00003219const TemplateArgumentList *
3220FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00003221 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00003222 = TemplateOrSpecialization
3223 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003224 return Info->TemplateArguments;
3225 }
Craig Topper36250ad2014-05-12 05:36:57 +00003226 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003227}
3228
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00003229const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003230FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3231 if (FunctionTemplateSpecializationInfo *Info
3232 = TemplateOrSpecialization
3233 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3234 return Info->TemplateArgumentsAsWritten;
3235 }
Craig Topper36250ad2014-05-12 05:36:57 +00003236 return nullptr;
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003237}
3238
Mike Stump11289f42009-09-09 15:08:12 +00003239void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003240FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3241 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003242 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003243 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003244 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00003245 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3246 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003247 assert(TSK != TSK_Undeclared &&
3248 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00003249 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003250 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003251 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00003252 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3253 TemplateArgs,
3254 TemplateArgsAsWritten,
3255 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003256 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00003257 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003258}
3259
John McCallb9c78482010-04-08 09:05:18 +00003260void
3261FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3262 const UnresolvedSetImpl &Templates,
3263 const TemplateArgumentListInfo &TemplateArgs) {
3264 assert(TemplateOrSpecialization.isNull());
John McCallb9c78482010-04-08 09:05:18 +00003265 DependentFunctionTemplateSpecializationInfo *Info =
James Y Knight7a22b242015-08-06 20:26:32 +00003266 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3267 TemplateArgs);
John McCallb9c78482010-04-08 09:05:18 +00003268 TemplateOrSpecialization = Info;
3269}
3270
James Y Knight7a22b242015-08-06 20:26:32 +00003271DependentFunctionTemplateSpecializationInfo *
Chandler Carruth21c90602015-12-30 03:24:14 +00003272FunctionDecl::getDependentSpecializationInfo() const {
3273 return TemplateOrSpecialization
3274 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3275}
3276
3277DependentFunctionTemplateSpecializationInfo *
James Y Knight7a22b242015-08-06 20:26:32 +00003278DependentFunctionTemplateSpecializationInfo::Create(
3279 ASTContext &Context, const UnresolvedSetImpl &Ts,
3280 const TemplateArgumentListInfo &TArgs) {
3281 void *Buffer = Context.Allocate(
3282 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3283 TArgs.size(), Ts.size()));
3284 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3285}
3286
John McCallb9c78482010-04-08 09:05:18 +00003287DependentFunctionTemplateSpecializationInfo::
3288DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3289 const TemplateArgumentListInfo &TArgs)
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003290 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
John McCallb9c78482010-04-08 09:05:18 +00003291
James Y Knight53c76162015-07-17 18:21:37 +00003292 NumTemplates = Ts.size();
3293 NumArgs = TArgs.size();
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003294
James Y Knight7a22b242015-08-06 20:26:32 +00003295 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
John McCallb9c78482010-04-08 09:05:18 +00003296 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3297 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3298
James Y Knight7a22b242015-08-06 20:26:32 +00003299 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
John McCallb9c78482010-04-08 09:05:18 +00003300 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3301 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3302}
3303
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003304TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00003305 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003306 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00003307 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00003308 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00003309 if (FTSInfo)
3310 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00003311
Douglas Gregord801b062009-10-07 23:56:10 +00003312 MemberSpecializationInfo *MSInfo
3313 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3314 if (MSInfo)
3315 return MSInfo->getTemplateSpecializationKind();
3316
3317 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003318}
3319
Mike Stump11289f42009-09-09 15:08:12 +00003320void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003321FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3322 SourceLocation PointOfInstantiation) {
3323 if (FunctionTemplateSpecializationInfo *FTSInfo
3324 = TemplateOrSpecialization.dyn_cast<
3325 FunctionTemplateSpecializationInfo*>()) {
3326 FTSInfo->setTemplateSpecializationKind(TSK);
3327 if (TSK != TSK_ExplicitSpecialization &&
3328 PointOfInstantiation.isValid() &&
3329 FTSInfo->getPointOfInstantiation().isInvalid())
3330 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3331 } else if (MemberSpecializationInfo *MSInfo
3332 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3333 MSInfo->setTemplateSpecializationKind(TSK);
3334 if (TSK != TSK_ExplicitSpecialization &&
3335 PointOfInstantiation.isValid() &&
3336 MSInfo->getPointOfInstantiation().isInvalid())
3337 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3338 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003339 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003340}
3341
3342SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00003343 if (FunctionTemplateSpecializationInfo *FTSInfo
3344 = TemplateOrSpecialization.dyn_cast<
3345 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003346 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00003347 else if (MemberSpecializationInfo *MSInfo
3348 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003349 return MSInfo->getPointOfInstantiation();
3350
3351 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00003352}
3353
Douglas Gregor6411b922009-09-11 20:15:17 +00003354bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00003355 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00003356 return true;
3357
3358 // If this function was instantiated from a member function of a
3359 // class template, check whether that member function was defined out-of-line.
3360 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3361 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003362 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003363 return Definition->isOutOfLine();
3364 }
3365
3366 // If this function was instantiated from a function template,
3367 // check whether that function template was defined out-of-line.
3368 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3369 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003370 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003371 return Definition->isOutOfLine();
3372 }
3373
3374 return false;
3375}
3376
Abramo Bagnaraea947882011-03-08 16:41:52 +00003377SourceRange FunctionDecl::getSourceRange() const {
3378 return SourceRange(getOuterLocStart(), EndRangeLoc);
3379}
3380
Anna Zaks28db7ce2012-01-18 02:45:01 +00003381unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00003382 IdentifierInfo *FnInfo = getIdentifier();
3383
3384 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00003385 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003386
3387 // Builtin handling.
3388 switch (getBuiltinID()) {
3389 case Builtin::BI__builtin_memset:
3390 case Builtin::BI__builtin___memset_chk:
3391 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003392 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003393
3394 case Builtin::BI__builtin_memcpy:
3395 case Builtin::BI__builtin___memcpy_chk:
3396 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003397 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003398
3399 case Builtin::BI__builtin_memmove:
3400 case Builtin::BI__builtin___memmove_chk:
3401 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003402 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003403
3404 case Builtin::BIstrlcpy:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003405 case Builtin::BI__builtin___strlcpy_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003406 return Builtin::BIstrlcpy;
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003407
Anna Zaks201d4892012-01-13 21:52:01 +00003408 case Builtin::BIstrlcat:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003409 case Builtin::BI__builtin___strlcat_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003410 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003411
3412 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003413 case Builtin::BImemcmp:
3414 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003415
3416 case Builtin::BI__builtin_strncpy:
3417 case Builtin::BI__builtin___strncpy_chk:
3418 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003419 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003420
3421 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003422 case Builtin::BIstrncmp:
3423 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003424
3425 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003426 case Builtin::BIstrncasecmp:
3427 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003428
3429 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003430 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003431 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003432 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003433
3434 case Builtin::BI__builtin_strndup:
3435 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003436 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003437
Anna Zaks314cd092012-02-01 19:08:57 +00003438 case Builtin::BI__builtin_strlen:
3439 case Builtin::BIstrlen:
3440 return Builtin::BIstrlen;
3441
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003442 case Builtin::BI__builtin_bzero:
3443 case Builtin::BIbzero:
3444 return Builtin::BIbzero;
3445
Anna Zaks201d4892012-01-13 21:52:01 +00003446 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003447 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003448 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003449 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003450 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003451 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003452 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003453 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003454 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003455 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003456 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003457 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003458 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003459 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003460 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003461 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003462 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003463 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003464 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003465 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003466 else if (FnInfo->isStr("strlen"))
3467 return Builtin::BIstrlen;
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003468 else if (FnInfo->isStr("bzero"))
3469 return Builtin::BIbzero;
Anna Zaks201d4892012-01-13 21:52:01 +00003470 }
3471 break;
3472 }
Anna Zaks22122702012-01-17 00:37:07 +00003473 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003474}
3475
Justin Lebar60dcc132016-08-15 20:38:56 +00003476void FunctionDecl::addDeferredDiag(PartialDiagnosticAt PD) {
3477 getASTContext().getDeferredDiags()[this].push_back(std::move(PD));
3478}
3479
3480std::vector<PartialDiagnosticAt> FunctionDecl::takeDeferredDiags() const {
3481 auto &DD = getASTContext().getDeferredDiags();
3482 auto It = DD.find(this);
3483 if (It == DD.end())
3484 return {};
3485 auto Ret = std::move(It->second);
3486 DD.erase(It);
3487 return Ret;
3488}
3489
Chris Lattner59a25942008-03-31 00:36:02 +00003490//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003491// FieldDecl Implementation
3492//===----------------------------------------------------------------------===//
3493
Jay Foad39c79802011-01-12 09:06:06 +00003494FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003495 SourceLocation StartLoc, SourceLocation IdLoc,
3496 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003497 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003498 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003499 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3500 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003501}
3502
Douglas Gregor72172e92012-01-05 21:55:30 +00003503FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003504 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3505 SourceLocation(), nullptr, QualType(), nullptr,
3506 nullptr, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00003507}
3508
Sebastian Redl833ef452010-01-26 22:01:41 +00003509bool FieldDecl::isAnonymousStructOrUnion() const {
3510 if (!isImplicit() || getDeclName())
3511 return false;
3512
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003513 if (const auto *Record = getType()->getAs<RecordType>())
Sebastian Redl833ef452010-01-26 22:01:41 +00003514 return Record->getDecl()->isAnonymousStructOrUnion();
3515
3516 return false;
3517}
3518
Richard Smithcaf33902011-10-10 18:28:20 +00003519unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3520 assert(isBitField() && "not a bitfield");
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003521 auto *BitWidth = static_cast<Expr *>(InitStorage.getPointer());
Richard Smithcaf33902011-10-10 18:28:20 +00003522 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3523}
3524
John McCall4e819612011-01-20 07:57:12 +00003525unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00003526 const FieldDecl *Canonical = getCanonicalDecl();
3527 if (Canonical != this)
3528 return Canonical->getFieldIndex();
3529
John McCall4e819612011-01-20 07:57:12 +00003530 if (CachedFieldIndex) return CachedFieldIndex - 1;
3531
Richard Smithd62306a2011-11-10 06:34:14 +00003532 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00003533 const RecordDecl *RD = getParent();
Richard Smithd62306a2011-11-10 06:34:14 +00003534
Hans Wennborga302cd92014-08-21 16:06:57 +00003535 for (auto *Field : RD->fields()) {
3536 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3537 ++Index;
3538 }
John McCall4e819612011-01-20 07:57:12 +00003539
Richard Smithd62306a2011-11-10 06:34:14 +00003540 assert(CachedFieldIndex && "failed to find field in parent");
3541 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00003542}
3543
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003544SourceRange FieldDecl::getSourceRange() const {
John McCallc90c1492014-10-10 18:44:34 +00003545 switch (InitStorage.getInt()) {
3546 // All three of these cases store an optional Expr*.
3547 case ISK_BitWidthOrNothing:
3548 case ISK_InClassCopyInit:
3549 case ISK_InClassListInit:
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003550 if (const auto *E = static_cast<const Expr *>(InitStorage.getPointer()))
John McCallc90c1492014-10-10 18:44:34 +00003551 return SourceRange(getInnerLocStart(), E->getLocEnd());
3552 // FALLTHROUGH
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003553
John McCallc90c1492014-10-10 18:44:34 +00003554 case ISK_CapturedVLAType:
3555 return DeclaratorDecl::getSourceRange();
3556 }
3557 llvm_unreachable("bad init storage kind");
Alexey Bataev39c81e22014-08-28 04:28:19 +00003558}
3559
3560void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
David Blaikie11ab0782014-10-31 17:18:09 +00003561 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
Alexey Bataev330de032014-10-29 12:21:55 +00003562 "capturing type in non-lambda or captured record.");
John McCallc90c1492014-10-10 18:44:34 +00003563 assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
3564 InitStorage.getPointer() == nullptr &&
Alexey Bataev39c81e22014-08-28 04:28:19 +00003565 "bit width, initializer or captured type already set");
John McCallc90c1492014-10-10 18:44:34 +00003566 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3567 ISK_CapturedVLAType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00003568}
3569
Sebastian Redl833ef452010-01-26 22:01:41 +00003570//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003571// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00003572//===----------------------------------------------------------------------===//
3573
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003574SourceLocation TagDecl::getOuterLocStart() const {
3575 return getTemplateOrInnerLocStart(this);
3576}
3577
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003578SourceRange TagDecl::getSourceRange() const {
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003579 SourceLocation RBraceLoc = BraceRange.getEnd();
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003580 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003581 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003582}
3583
Rafael Espindola8db352d2013-10-17 15:37:26 +00003584TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00003585
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00003586void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer00350522015-08-31 18:48:39 +00003587 TypedefNameDeclOrQualifier = TDD;
Reid Klecknercae82a22014-04-23 22:03:04 +00003588 if (const Type *T = getTypeForDecl()) {
3589 (void)T;
Richard Smith5b21db82014-04-23 18:20:42 +00003590 assert(T->isLinkageValid());
Reid Klecknercae82a22014-04-23 22:03:04 +00003591 }
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003592 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00003593}
3594
Douglas Gregordee1be82009-01-17 00:42:38 +00003595void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003596 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00003597
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003598 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
Richard Smith053f6c62014-05-16 23:01:30 +00003599 struct CXXRecordDecl::DefinitionData *Data =
John McCall67da35c2010-02-04 22:26:26 +00003600 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00003601 for (auto I : redecls())
Richard Smith64c06302014-05-22 23:19:02 +00003602 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00003603 }
Douglas Gregordee1be82009-01-17 00:42:38 +00003604}
3605
3606void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00003607 assert((!isa<CXXRecordDecl>(this) ||
3608 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3609 "definition completed but not started");
3610
John McCallf937c022011-10-07 06:10:15 +00003611 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003612 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00003613
3614 if (ASTMutationListener *L = getASTMutationListener())
3615 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00003616}
3617
John McCallf937c022011-10-07 06:10:15 +00003618TagDecl *TagDecl::getDefinition() const {
3619 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003620 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003621
3622 // If it's possible for us to have an out-of-date definition, check now.
3623 if (MayHaveOutOfDateDef) {
3624 if (IdentifierInfo *II = getIdentifier()) {
3625 if (II->isOutOfDate()) {
3626 updateOutOfDate(*II);
3627 }
3628 }
3629 }
3630
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003631 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
Andrew Trickba266ee2010-10-19 21:54:32 +00003632 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003633
Aaron Ballman86c93902014-03-06 23:45:36 +00003634 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00003635 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00003636 return R;
Mike Stump11289f42009-09-09 15:08:12 +00003637
Craig Topper36250ad2014-05-12 05:36:57 +00003638 return nullptr;
Ted Kremenek21475702008-09-05 17:16:31 +00003639}
3640
Douglas Gregor14454802011-02-25 02:25:35 +00003641void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3642 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00003643 // Make sure the extended qualifier info is allocated.
3644 if (!hasExtInfo())
David Majnemer00350522015-08-31 18:48:39 +00003645 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00003646 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00003647 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003648 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00003649 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00003650 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00003651 if (getExtInfo()->NumTemplParamLists == 0) {
3652 getASTContext().Deallocate(getExtInfo());
David Majnemer00350522015-08-31 18:48:39 +00003653 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003654 }
3655 else
3656 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00003657 }
3658 }
3659}
3660
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003661void TagDecl::setTemplateParameterListsInfo(
3662 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
3663 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00003664 // Make sure the extended decl info is allocated.
3665 if (!hasExtInfo())
3666 // Allocate external info struct.
David Majnemer00350522015-08-31 18:48:39 +00003667 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003668 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003669 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00003670}
3671
Ted Kremenek21475702008-09-05 17:16:31 +00003672//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003673// EnumDecl Implementation
3674//===----------------------------------------------------------------------===//
3675
David Blaikie68e081d2011-12-20 02:48:34 +00003676void EnumDecl::anchor() { }
3677
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003678EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3679 SourceLocation StartLoc, SourceLocation IdLoc,
3680 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00003681 EnumDecl *PrevDecl, bool IsScoped,
3682 bool IsScopedUsingClassTag, bool IsFixed) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003683 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
3684 IsScoped, IsScopedUsingClassTag, IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003685 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00003686 C.getTypeDeclType(Enum, PrevDecl);
3687 return Enum;
3688}
3689
Douglas Gregor72172e92012-01-05 21:55:30 +00003690EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003691 EnumDecl *Enum =
3692 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3693 nullptr, nullptr, false, false, false);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003694 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3695 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003696}
3697
Alp Tokerb9fa5122014-01-06 11:31:18 +00003698SourceRange EnumDecl::getIntegerTypeRange() const {
3699 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3700 return TI->getTypeLoc().getSourceRange();
3701 return SourceRange();
3702}
3703
Douglas Gregord5058122010-02-11 01:19:42 +00003704void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00003705 QualType NewPromotionType,
3706 unsigned NumPositiveBits,
3707 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00003708 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00003709 if (!IntegerType)
3710 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00003711 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00003712 setNumPositiveBits(NumPositiveBits);
3713 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00003714 TagDecl::completeDefinition();
3715}
3716
Richard Smith7d137e32012-03-23 03:33:32 +00003717TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3718 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3719 return MSI->getTemplateSpecializationKind();
3720
3721 return TSK_Undeclared;
3722}
3723
3724void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3725 SourceLocation PointOfInstantiation) {
3726 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3727 assert(MSI && "Not an instantiated member enumeration?");
3728 MSI->setTemplateSpecializationKind(TSK);
3729 if (TSK != TSK_ExplicitSpecialization &&
3730 PointOfInstantiation.isValid() &&
3731 MSI->getPointOfInstantiation().isInvalid())
3732 MSI->setPointOfInstantiation(PointOfInstantiation);
3733}
3734
Richard Smith6739a102016-05-05 00:56:12 +00003735EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
3736 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
3737 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
3738 EnumDecl *ED = getInstantiatedFromMemberEnum();
3739 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
3740 ED = NewED;
3741 return ED;
3742 }
3743 }
3744
3745 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
3746 "couldn't find pattern for enum instantiation");
3747 return nullptr;
3748}
3749
Richard Smith4b38ded2012-03-14 23:13:10 +00003750EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3751 if (SpecializationInfo)
3752 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3753
Craig Topper36250ad2014-05-12 05:36:57 +00003754 return nullptr;
Richard Smith4b38ded2012-03-14 23:13:10 +00003755}
3756
3757void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3758 TemplateSpecializationKind TSK) {
3759 assert(!SpecializationInfo && "Member enum is already a specialization");
3760 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3761}
3762
Sebastian Redl833ef452010-01-26 22:01:41 +00003763//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003764// RecordDecl Implementation
3765//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003766
Richard Smith053f6c62014-05-16 23:01:30 +00003767RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3768 DeclContext *DC, SourceLocation StartLoc,
3769 SourceLocation IdLoc, IdentifierInfo *Id,
3770 RecordDecl *PrevDecl)
3771 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003772 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003773 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003774 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00003775 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003776 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00003777 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003778}
3779
Jay Foad39c79802011-01-12 09:06:06 +00003780RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003781 SourceLocation StartLoc, SourceLocation IdLoc,
3782 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smith053f6c62014-05-16 23:01:30 +00003783 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
3784 StartLoc, IdLoc, Id, PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003785 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3786
Ted Kremenek21475702008-09-05 17:16:31 +00003787 C.getTypeDeclType(R, PrevDecl);
3788 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003789}
3790
Douglas Gregor72172e92012-01-05 21:55:30 +00003791RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003792 RecordDecl *R =
3793 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
3794 SourceLocation(), nullptr, nullptr);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003795 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3796 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003797}
3798
Douglas Gregordfcad112009-03-25 15:59:44 +00003799bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003800 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003801 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3802}
3803
Alexey Bataev39c81e22014-08-28 04:28:19 +00003804bool RecordDecl::isLambda() const {
3805 if (auto RD = dyn_cast<CXXRecordDecl>(this))
3806 return RD->isLambda();
3807 return false;
3808}
3809
Alexey Bataev330de032014-10-29 12:21:55 +00003810bool RecordDecl::isCapturedRecord() const {
3811 return hasAttr<CapturedRecordAttr>();
3812}
3813
3814void RecordDecl::setCapturedRecord() {
3815 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
3816}
3817
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003818RecordDecl::field_iterator RecordDecl::field_begin() const {
3819 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3820 LoadFieldsFromExternalStorage();
3821
3822 return field_iterator(decl_iterator(FirstDecl));
3823}
3824
Douglas Gregorb11aad82011-02-19 18:51:44 +00003825/// completeDefinition - Notes that the definition of this type is now
3826/// complete.
3827void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003828 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003829 TagDecl::completeDefinition();
3830}
3831
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003832/// isMsStruct - Get whether or not this record uses ms_struct layout.
3833/// This which can be turned on with an attribute, pragma, or the
3834/// -mms-bitfields command-line option.
3835bool RecordDecl::isMsStruct(const ASTContext &C) const {
David Majnemer8ab003a2015-02-02 19:30:52 +00003836 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003837}
3838
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003839void RecordDecl::LoadFieldsFromExternalStorage() const {
3840 ExternalASTSource *Source = getASTContext().getExternalSource();
3841 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3842
3843 // Notify that we have a RecordDecl doing some initialization.
3844 ExternalASTSource::Deserializing TheFields(Source);
3845
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003846 SmallVector<Decl*, 64> Decls;
Richard Smith3cb15722015-08-05 22:41:45 +00003847 LoadedFieldsFromExternalStorage = true;
3848 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
3849 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3850 }, Decls);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003851
3852#ifndef NDEBUG
3853 // Check that all decls we got were FieldDecls.
3854 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003855 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003856#endif
3857
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003858 if (Decls.empty())
3859 return;
3860
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003861 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003862 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003863}
3864
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003865bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
3866 ASTContext &Context = getASTContext();
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00003867 if (!Context.getLangOpts().Sanitize.hasOneOf(
3868 SanitizerKind::Address | SanitizerKind::KernelAddress) ||
Alexey Samsonova0416102014-11-11 01:26:14 +00003869 !Context.getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003870 return false;
Alexey Samsonov33e00e22014-10-16 23:50:26 +00003871 const auto &Blacklist = Context.getSanitizerBlacklist();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003872 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003873 // We may be able to relax some of these requirements.
3874 int ReasonToReject = -1;
3875 if (!CXXRD || CXXRD->isExternCContext())
3876 ReasonToReject = 0; // is not C++.
3877 else if (CXXRD->hasAttr<PackedAttr>())
3878 ReasonToReject = 1; // is packed.
3879 else if (CXXRD->isUnion())
3880 ReasonToReject = 2; // is a union.
3881 else if (CXXRD->isTriviallyCopyable())
3882 ReasonToReject = 3; // is trivially copyable.
3883 else if (CXXRD->hasTrivialDestructor())
3884 ReasonToReject = 4; // has trivial destructor.
3885 else if (CXXRD->isStandardLayout())
3886 ReasonToReject = 5; // is standard layout.
Alexey Samsonov33e00e22014-10-16 23:50:26 +00003887 else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003888 ReasonToReject = 6; // is in a blacklisted file.
3889 else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(),
3890 "field-padding"))
3891 ReasonToReject = 7; // is blacklisted.
3892
3893 if (EmitRemark) {
3894 if (ReasonToReject >= 0)
3895 Context.getDiagnostics().Report(
3896 getLocation(),
3897 diag::remark_sanitize_address_insert_extra_padding_rejected)
3898 << getQualifiedNameAsString() << ReasonToReject;
3899 else
3900 Context.getDiagnostics().Report(
3901 getLocation(),
3902 diag::remark_sanitize_address_insert_extra_padding_accepted)
3903 << getQualifiedNameAsString();
3904 }
3905 return ReasonToReject < 0;
3906}
3907
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003908const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
3909 for (const auto *I : fields()) {
3910 if (I->getIdentifier())
3911 return I;
3912
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003913 if (const auto *RT = I->getType()->getAs<RecordType>())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003914 if (const FieldDecl *NamedDataMember =
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003915 RT->getDecl()->findFirstNamedDataMember())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003916 return NamedDataMember;
3917 }
3918
3919 // We didn't find a named data member.
3920 return nullptr;
3921}
3922
3923
Steve Naroff415d3d52008-10-08 17:01:13 +00003924//===----------------------------------------------------------------------===//
3925// BlockDecl Implementation
3926//===----------------------------------------------------------------------===//
3927
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003928void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00003929 assert(!ParamInfo && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00003930
Steve Naroffc4b30e52009-03-13 16:56:44 +00003931 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003932 if (!NewParamInfo.empty()) {
3933 NumParams = NewParamInfo.size();
3934 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3935 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003936 }
3937}
3938
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00003939void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
3940 bool CapturesCXXThis) {
3941 this->CapturesCXXThis = CapturesCXXThis;
3942 this->NumCaptures = Captures.size();
John McCallc63de662011-02-02 13:00:07 +00003943
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00003944 if (Captures.empty()) {
3945 this->Captures = nullptr;
John McCallc63de662011-02-02 13:00:07 +00003946 return;
3947 }
3948
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00003949 this->Captures = Captures.copy(Context).data();
Steve Naroffc4b30e52009-03-13 16:56:44 +00003950}
Sebastian Redl833ef452010-01-26 22:01:41 +00003951
John McCallce45f882011-06-15 22:51:16 +00003952bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00003953 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00003954 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00003955 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00003956 return true;
3957
3958 return false;
3959}
3960
Douglas Gregor70226da2010-12-21 16:27:07 +00003961SourceRange BlockDecl::getSourceRange() const {
3962 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3963}
Sebastian Redl833ef452010-01-26 22:01:41 +00003964
3965//===----------------------------------------------------------------------===//
3966// Other Decl Allocation/Deallocation Method Implementations
3967//===----------------------------------------------------------------------===//
3968
David Blaikie68e081d2011-12-20 02:48:34 +00003969void TranslationUnitDecl::anchor() { }
3970
Sebastian Redl833ef452010-01-26 22:01:41 +00003971TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Craig Topper36250ad2014-05-12 05:36:57 +00003972 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00003973}
3974
Nico Weber66220292016-03-02 17:28:48 +00003975void PragmaCommentDecl::anchor() { }
3976
3977PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
3978 TranslationUnitDecl *DC,
3979 SourceLocation CommentLoc,
3980 PragmaMSCommentKind CommentKind,
3981 StringRef Arg) {
3982 PragmaCommentDecl *PCD =
3983 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
3984 PragmaCommentDecl(DC, CommentLoc, CommentKind);
3985 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
3986 PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
3987 return PCD;
3988}
3989
3990PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
3991 unsigned ID,
3992 unsigned ArgSize) {
3993 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
3994 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
3995}
3996
Nico Webercbbaeb12016-03-02 19:28:54 +00003997void PragmaDetectMismatchDecl::anchor() { }
3998
3999PragmaDetectMismatchDecl *
4000PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4001 SourceLocation Loc, StringRef Name,
4002 StringRef Value) {
4003 size_t ValueStart = Name.size() + 1;
4004 PragmaDetectMismatchDecl *PDMD =
4005 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4006 PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4007 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4008 PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4009 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4010 Value.size());
4011 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4012 return PDMD;
4013}
4014
4015PragmaDetectMismatchDecl *
4016PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4017 unsigned NameValueSize) {
4018 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4019 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4020}
Nico Weber66220292016-03-02 17:28:48 +00004021
Richard Smithf19e1272015-03-07 00:04:49 +00004022void ExternCContextDecl::anchor() { }
4023
4024ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4025 TranslationUnitDecl *DC) {
4026 return new (C, DC) ExternCContextDecl(DC);
4027}
4028
David Blaikie68e081d2011-12-20 02:48:34 +00004029void LabelDecl::anchor() { }
4030
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004031LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004032 SourceLocation IdentL, IdentifierInfo *II) {
Craig Topper36250ad2014-05-12 05:36:57 +00004033 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004034}
4035
4036LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4037 SourceLocation IdentL, IdentifierInfo *II,
4038 SourceLocation GnuLabelL) {
4039 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Craig Topper36250ad2014-05-12 05:36:57 +00004040 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004041}
4042
Douglas Gregor72172e92012-01-05 21:55:30 +00004043LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004044 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
4045 SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00004046}
4047
Ehsan Akhgari31097582014-09-22 02:21:54 +00004048void LabelDecl::setMSAsmLabel(StringRef Name) {
4049 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
4050 memcpy(Buffer, Name.data(), Name.size());
4051 Buffer[Name.size()] = '\0';
4052 MSAsmName = Buffer;
4053}
4054
David Blaikie68e081d2011-12-20 02:48:34 +00004055void ValueDecl::anchor() { }
4056
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004057bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00004058 for (const auto *I : attrs())
4059 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004060 return true;
4061
4062 return isWeakImported();
4063}
4064
David Blaikie68e081d2011-12-20 02:48:34 +00004065void ImplicitParamDecl::anchor() { }
4066
Sebastian Redl833ef452010-01-26 22:01:41 +00004067ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004068 SourceLocation IdLoc,
4069 IdentifierInfo *Id,
4070 QualType Type) {
Richard Smith053f6c62014-05-16 23:01:30 +00004071 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00004072}
4073
Richard Smithf7981722013-11-22 09:01:48 +00004074ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004075 unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004076 return new (C, ID) ImplicitParamDecl(C, nullptr, SourceLocation(), nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00004077 QualType());
Douglas Gregor72172e92012-01-05 21:55:30 +00004078}
4079
Sebastian Redl833ef452010-01-26 22:01:41 +00004080FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004081 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004082 const DeclarationNameInfo &NameInfo,
4083 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004084 StorageClass SC,
Richard Smithf7981722013-11-22 09:01:48 +00004085 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00004086 bool hasWrittenPrototype,
4087 bool isConstexprSpecified) {
Richard Smithf7981722013-11-22 09:01:48 +00004088 FunctionDecl *New =
Richard Smith053f6c62014-05-16 23:01:30 +00004089 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
4090 SC, isInlineSpecified, isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00004091 New->HasWrittenPrototype = hasWrittenPrototype;
4092 return New;
4093}
4094
Douglas Gregor72172e92012-01-05 21:55:30 +00004095FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004096 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004097 DeclarationNameInfo(), QualType(), nullptr,
Richard Smithf7981722013-11-22 09:01:48 +00004098 SC_None, false, false);
Douglas Gregor72172e92012-01-05 21:55:30 +00004099}
4100
Sebastian Redl833ef452010-01-26 22:01:41 +00004101BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004102 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00004103}
4104
Douglas Gregor72172e92012-01-05 21:55:30 +00004105BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004106 return new (C, ID) BlockDecl(nullptr, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00004107}
4108
Chandler Carruth21c90602015-12-30 03:24:14 +00004109CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
4110 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4111 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
4112
Ben Langmuir37943a72013-05-03 19:00:33 +00004113CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
4114 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004115 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Richard Smithf7981722013-11-22 09:01:48 +00004116 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004117}
4118
Ben Langmuirce914fc2013-05-03 19:20:19 +00004119CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00004120 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004121 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Craig Topper36250ad2014-05-12 05:36:57 +00004122 CapturedDecl(nullptr, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00004123}
4124
Chandler Carruth21c90602015-12-30 03:24:14 +00004125Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4126void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4127
4128bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4129void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4130
Sebastian Redl833ef452010-01-26 22:01:41 +00004131EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4132 SourceLocation L,
4133 IdentifierInfo *Id, QualType T,
4134 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00004135 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00004136}
4137
Douglas Gregor72172e92012-01-05 21:55:30 +00004138EnumConstantDecl *
4139EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004140 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4141 QualType(), nullptr, llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00004142}
4143
David Blaikie68e081d2011-12-20 02:48:34 +00004144void IndirectFieldDecl::anchor() { }
4145
Richard Smith9f951822016-01-06 22:49:11 +00004146IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4147 SourceLocation L, DeclarationName N,
David Majnemer59f77922016-06-24 04:05:48 +00004148 QualType T,
4149 MutableArrayRef<NamedDecl *> CH)
4150 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4151 ChainingSize(CH.size()) {
Richard Smith9f951822016-01-06 22:49:11 +00004152 // In C++, indirect field declarations conflict with tag declarations in the
4153 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4154 if (C.getLangOpts().CPlusPlus)
4155 IdentifierNamespace |= IDNS_Tag;
4156}
4157
Benjamin Kramer39593702010-11-21 14:11:41 +00004158IndirectFieldDecl *
4159IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
David Majnemer59f77922016-06-24 04:05:48 +00004160 IdentifierInfo *Id, QualType T,
4161 llvm::MutableArrayRef<NamedDecl *> CH) {
4162 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
Francois Pichet783dd6e2010-11-21 06:08:52 +00004163}
4164
Douglas Gregor72172e92012-01-05 21:55:30 +00004165IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4166 unsigned ID) {
Richard Smith9f951822016-01-06 22:49:11 +00004167 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
David Majnemer59f77922016-06-24 04:05:48 +00004168 DeclarationName(), QualType(), None);
Douglas Gregor72172e92012-01-05 21:55:30 +00004169}
4170
Douglas Gregorbe996932010-09-01 20:41:53 +00004171SourceRange EnumConstantDecl::getSourceRange() const {
4172 SourceLocation End = getLocation();
4173 if (Init)
4174 End = Init->getLocEnd();
4175 return SourceRange(getLocation(), End);
4176}
4177
David Blaikie68e081d2011-12-20 02:48:34 +00004178void TypeDecl::anchor() { }
4179
Sebastian Redl833ef452010-01-26 22:01:41 +00004180TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00004181 SourceLocation StartLoc, SourceLocation IdLoc,
4182 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004183 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00004184}
4185
David Blaikie68e081d2011-12-20 02:48:34 +00004186void TypedefNameDecl::anchor() { }
4187
Richard Smith42413142015-05-15 20:05:43 +00004188TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4189 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4190 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4191 auto *ThisTypedef = this;
4192 if (AnyRedecl && OwningTypedef) {
4193 OwningTypedef = OwningTypedef->getCanonicalDecl();
4194 ThisTypedef = ThisTypedef->getCanonicalDecl();
4195 }
4196 if (OwningTypedef == ThisTypedef)
Richard Smitha5230222015-03-27 01:37:43 +00004197 return TT->getDecl();
Richard Smith42413142015-05-15 20:05:43 +00004198 }
Richard Smitha5230222015-03-27 01:37:43 +00004199
4200 return nullptr;
4201}
4202
Douglas Gregor72172e92012-01-05 21:55:30 +00004203TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004204 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004205 nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004206}
4207
Richard Smithdda56e42011-04-15 14:24:37 +00004208TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4209 SourceLocation StartLoc,
4210 SourceLocation IdLoc, IdentifierInfo *Id,
4211 TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004212 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00004213}
4214
Douglas Gregor72172e92012-01-05 21:55:30 +00004215TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004216 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
4217 SourceLocation(), nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004218}
4219
Abramo Bagnaraea947882011-03-08 16:41:52 +00004220SourceRange TypedefDecl::getSourceRange() const {
4221 SourceLocation RangeEnd = getLocation();
4222 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4223 if (typeIsPostfix(TInfo->getType()))
4224 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4225 }
4226 return SourceRange(getLocStart(), RangeEnd);
4227}
4228
Richard Smithdda56e42011-04-15 14:24:37 +00004229SourceRange TypeAliasDecl::getSourceRange() const {
4230 SourceLocation RangeEnd = getLocStart();
4231 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4232 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4233 return SourceRange(getLocStart(), RangeEnd);
4234}
4235
David Blaikie68e081d2011-12-20 02:48:34 +00004236void FileScopeAsmDecl::anchor() { }
4237
Sebastian Redl833ef452010-01-26 22:01:41 +00004238FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00004239 StringLiteral *Str,
4240 SourceLocation AsmLoc,
4241 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00004242 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00004243}
Douglas Gregorba345522011-12-02 23:23:56 +00004244
Richard Smithf7981722013-11-22 09:01:48 +00004245FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004246 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004247 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4248 SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00004249}
4250
Michael Han84324352013-02-22 17:15:32 +00004251void EmptyDecl::anchor() {}
4252
4253EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004254 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00004255}
4256
4257EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004258 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00004259}
4260
Douglas Gregorba345522011-12-02 23:23:56 +00004261//===----------------------------------------------------------------------===//
4262// ImportDecl Implementation
4263//===----------------------------------------------------------------------===//
4264
4265/// \brief Retrieve the number of module identifiers needed to name the given
4266/// module.
4267static unsigned getNumModuleIdentifiers(Module *Mod) {
4268 unsigned Result = 1;
4269 while (Mod->Parent) {
4270 Mod = Mod->Parent;
4271 ++Result;
4272 }
4273 return Result;
4274}
4275
Douglas Gregor22d09742012-01-03 18:04:46 +00004276ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004277 Module *Imported,
4278 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00004279 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00004280 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00004281{
4282 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004283 auto *StoredLocs = getTrailingObjects<SourceLocation>();
James Y Knight7a22b242015-08-06 20:26:32 +00004284 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4285 StoredLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004286}
4287
Douglas Gregor22d09742012-01-03 18:04:46 +00004288ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004289 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00004290 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00004291 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00004292{
James Y Knight7a22b242015-08-06 20:26:32 +00004293 *getTrailingObjects<SourceLocation>() = EndLoc;
Douglas Gregorba345522011-12-02 23:23:56 +00004294}
4295
Richard Smithf7981722013-11-22 09:01:48 +00004296ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004297 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004298 ArrayRef<SourceLocation> IdentifierLocs) {
James Y Knight7a22b242015-08-06 20:26:32 +00004299 return new (C, DC,
4300 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
Richard Smithf7981722013-11-22 09:01:48 +00004301 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004302}
4303
Richard Smithf7981722013-11-22 09:01:48 +00004304ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004305 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00004306 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004307 SourceLocation EndLoc) {
James Y Knight7a22b242015-08-06 20:26:32 +00004308 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
4309 ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00004310 Import->setImplicit();
4311 return Import;
4312}
4313
Douglas Gregor72172e92012-01-05 21:55:30 +00004314ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4315 unsigned NumLocations) {
James Y Knight7a22b242015-08-06 20:26:32 +00004316 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
Richard Smithf7981722013-11-22 09:01:48 +00004317 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00004318}
4319
4320ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4321 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004322 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00004323
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004324 const auto *StoredLocs = getTrailingObjects<SourceLocation>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00004325 return llvm::makeArrayRef(StoredLocs,
4326 getNumModuleIdentifiers(getImportedModule()));
Douglas Gregorba345522011-12-02 23:23:56 +00004327}
4328
4329SourceRange ImportDecl::getSourceRange() const {
4330 if (!ImportedAndComplete.getInt())
James Y Knight7a22b242015-08-06 20:26:32 +00004331 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
4332
Douglas Gregorba345522011-12-02 23:23:56 +00004333 return SourceRange(getLocation(), getIdentifierLocs().back());
4334}
Richard Smith8df390f2016-09-08 23:14:54 +00004335
4336//===----------------------------------------------------------------------===//
4337// ExportDecl Implementation
4338//===----------------------------------------------------------------------===//
4339
4340void ExportDecl::anchor() {}
4341
4342ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
4343 SourceLocation ExportLoc) {
4344 return new (C, DC) ExportDecl(DC, ExportLoc);
4345}
4346
4347ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4348 return new (C, ID) ExportDecl(nullptr, SourceLocation());
4349}