blob: 3f6941ab72d988b4dd7338ce600a33967d67701b [file] [log] [blame]
Chris Lattnera11999d2006-10-15 22:34:45 +00001//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera11999d2006-10-15 22:34:45 +00007//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidis63018842008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Chris Lattnera11999d2006-10-15 22:34:45 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
Chris Lattnera7b32872008-03-15 06:12:44 +000015#include "clang/AST/ASTContext.h"
Faisal Valib90b2112014-04-03 16:32:21 +000016#include "clang/AST/ASTLambda.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/Attr.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000022#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000024#include "clang/AST/PrettyPrinter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000025#include "clang/AST/Stmt.h"
26#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000027#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000028#include "clang/Basic/IdentifierTable.h"
Douglas Gregorba345522011-12-02 23:23:56 +000029#include "clang/Basic/Module.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000030#include "clang/Basic/Specifiers.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000031#include "clang/Basic/TargetInfo.h"
Kostya Serebryany293dc9b2014-10-16 20:54:52 +000032#include "clang/Frontend/FrontendDiagnostic.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000033#include "llvm/Support/ErrorHandling.h"
David Blaikie9c70e042011-09-21 18:16:56 +000034#include <algorithm>
35
Chris Lattner6d9a6852006-10-25 05:11:20 +000036using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000037
Richard Smith0b87e072013-10-07 08:02:11 +000038Decl *clang::getPrimaryMergedDecl(Decl *D) {
39 return D->getASTContext().getPrimaryMergedDecl(D);
40}
41
Richard Smith73b21d82014-09-03 02:33:22 +000042// Defined here so that it can be inlined into its direct callers.
43bool Decl::isOutOfLine() const {
44 return !getLexicalDeclContext()->Equals(getDeclContext());
45}
46
Richard Smith42413142015-05-15 20:05:43 +000047TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
48 : Decl(TranslationUnit, nullptr, SourceLocation()),
49 DeclContext(TranslationUnit), Ctx(ctx), AnonymousNamespace(nullptr) {
50 Hidden = Ctx.getLangOpts().ModulesLocalVisibility;
51}
52
Chris Lattner88f70d62008-03-15 05:43:15 +000053//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000054// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000055//===----------------------------------------------------------------------===//
56
John McCalldf25c432013-02-16 00:17:33 +000057// Visibility rules aren't rigorously externally specified, but here
58// are the basic principles behind what we implement:
59//
60// 1. An explicit visibility attribute is generally a direct expression
61// of the user's intent and should be honored. Only the innermost
62// visibility attribute applies. If no visibility attribute applies,
63// global visibility settings are considered.
64//
65// 2. There is one caveat to the above: on or in a template pattern,
66// an explicit visibility attribute is just a default rule, and
67// visibility can be decreased by the visibility of template
68// arguments. But this, too, has an exception: an attribute on an
69// explicit specialization or instantiation causes all the visibility
70// restrictions of the template arguments to be ignored.
71//
72// 3. A variable that does not otherwise have explicit visibility can
73// be restricted by the visibility of its type.
74//
75// 4. A visibility restriction is explicit if it comes from an
76// attribute (or something like it), not a global visibility setting.
77// When emitting a reference to an external symbol, visibility
78// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +000079//
80// 5. When computing the visibility of a non-type, including a
81// non-type member of a class, only non-type visibility restrictions
82// are considered: the 'visibility' attribute, global value-visibility
83// settings, and a few special cases like __private_extern.
84//
85// 6. When computing the visibility of a type, including a type member
86// of a class, only type visibility restrictions are considered:
87// the 'type_visibility' attribute and global type-visibility settings.
88// However, a 'visibility' attribute counts as a 'type_visibility'
89// attribute on any declaration that only has the former.
90//
91// The visibility of a "secondary" entity, like a template argument,
92// is computed using the kind of that entity, not the kind of the
93// primary entity for which we are computing visibility. For example,
94// the visibility of a specialization of either of these templates:
95// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
96// template <class T, bool (&compare)(T, X)> class matcher;
97// is restricted according to the type visibility of the argument 'T',
98// the type visibility of 'bool(&)(T,X)', and the value visibility of
99// the argument function 'compare'. That 'has_match' is a value
100// and 'matcher' is a type only matters when looking for attributes
101// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +0000102
John McCall5f46c482013-02-21 23:42:58 +0000103const unsigned IgnoreExplicitVisibilityBit = 2;
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000104const unsigned IgnoreAllVisibilityBit = 4;
John McCall5f46c482013-02-21 23:42:58 +0000105
John McCalldf25c432013-02-16 00:17:33 +0000106/// Kinds of LV computation. The linkage side of the computation is
107/// always the same, but different things can change how visibility is
108/// computed.
109enum LVComputationKind {
John McCall5f46c482013-02-21 23:42:58 +0000110 /// Do an LV computation for, ultimately, a type.
111 /// Visibility may be restricted by type visibility settings and
112 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000113 LVForType = NamedDecl::VisibilityForType,
John McCalldf25c432013-02-16 00:17:33 +0000114
John McCall5f46c482013-02-21 23:42:58 +0000115 /// Do an LV computation for, ultimately, a non-type declaration.
116 /// Visibility may be restricted by value visibility settings and
117 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000118 LVForValue = NamedDecl::VisibilityForValue,
119
John McCall5f46c482013-02-21 23:42:58 +0000120 /// Do an LV computation for, ultimately, a type that already has
121 /// some sort of explicit visibility. Visibility may only be
122 /// restricted by the visibility of template arguments.
123 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
John McCalld041a9b2013-02-20 01:54:26 +0000124
John McCall5f46c482013-02-21 23:42:58 +0000125 /// Do an LV computation for, ultimately, a non-type declaration
126 /// that already has some sort of explicit visibility. Visibility
127 /// may only be restricted by the visibility of template arguments.
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000128 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
129
130 /// Do an LV computation when we only care about the linkage.
131 LVForLinkageOnly =
132 LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
John McCalldf25c432013-02-16 00:17:33 +0000133};
134
John McCalld041a9b2013-02-20 01:54:26 +0000135/// Does this computation kind permit us to consider additional
136/// visibility settings from attributes and the like?
137static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000138 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
John McCalld041a9b2013-02-20 01:54:26 +0000139}
140
141/// Given an LVComputationKind, return one of the same type/value sort
142/// that records that it already has explicit visibility.
143static LVComputationKind
144withExplicitVisibilityAlready(LVComputationKind oldKind) {
145 LVComputationKind newKind =
John McCall5f46c482013-02-21 23:42:58 +0000146 static_cast<LVComputationKind>(unsigned(oldKind) |
147 IgnoreExplicitVisibilityBit);
John McCalld041a9b2013-02-20 01:54:26 +0000148 assert(oldKind != LVForType || newKind == LVForExplicitType);
149 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
150 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
151 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
152 return newKind;
153}
154
David Blaikie05785d12013-02-20 22:23:23 +0000155static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
156 LVComputationKind kind) {
John McCalld041a9b2013-02-20 01:54:26 +0000157 assert(!hasExplicitVisibilityAlready(kind) &&
158 "asking for explicit visibility when we shouldn't be");
159 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
160}
161
John McCalldf25c432013-02-16 00:17:33 +0000162/// Is the given declaration a "type" or a "value" for the purposes of
163/// visibility computation?
164static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000165 return isa<TypeDecl>(D) ||
166 isa<ClassTemplateDecl>(D) ||
167 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000168}
169
John McCall5f46c482013-02-21 23:42:58 +0000170/// Does the given declaration have member specialization information,
171/// and if so, is it an explicit specialization?
172template <class T> static typename
Benjamin Kramered2f4762014-03-07 14:30:23 +0000173std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-02-21 23:42:58 +0000174isExplicitMemberSpecialization(const T *D) {
175 if (const MemberSpecializationInfo *member =
176 D->getMemberSpecializationInfo()) {
177 return member->isExplicitSpecialization();
178 }
179 return false;
180}
181
182/// For templates, this question is easier: a member template can't be
183/// explicitly instantiated, so there's a single bit indicating whether
184/// or not this is an explicit member specialization.
185static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
186 return D->isMemberSpecialization();
187}
188
John McCalld041a9b2013-02-20 01:54:26 +0000189/// Given a visibility attribute, return the explicit visibility
190/// associated with it.
191template <class T>
192static Visibility getVisibilityFromAttr(const T *attr) {
193 switch (attr->getVisibility()) {
194 case T::Default:
195 return DefaultVisibility;
196 case T::Hidden:
197 return HiddenVisibility;
198 case T::Protected:
199 return ProtectedVisibility;
200 }
201 llvm_unreachable("bad visibility kind");
202}
203
John McCalldf25c432013-02-16 00:17:33 +0000204/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000205static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000206 NamedDecl::ExplicitVisibilityKind kind) {
207 // If we're ultimately computing the visibility of a type, look for
208 // a 'type_visibility' attribute before looking for 'visibility'.
209 if (kind == NamedDecl::VisibilityForType) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000210 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000211 return getVisibilityFromAttr(A);
212 }
213 }
214
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000215 // If this declaration has an explicit visibility attribute, use it.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000216 if (const auto *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000217 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000218 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000219
220 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
221 // implies visibility(default).
Douglas Gregore8bbc122011-09-02 00:18:52 +0000222 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000223 for (const auto *A : D->specific_attrs<AvailabilityAttr>())
224 if (A->getPlatform()->getName().equals("macosx"))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000225 return DefaultVisibility;
226 }
227
David Blaikie7a30dc52013-02-21 01:47:18 +0000228 return None;
John McCall457a04e2010-10-22 21:05:15 +0000229}
230
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000231static LinkageInfo
232getLVForType(const Type &T, LVComputationKind computation) {
233 if (computation == LVForLinkageOnly)
234 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
235 return T.getLinkageAndVisibility();
236}
237
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000238/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000239/// template parameter list. For visibility purposes, template
240/// parameters are part of the signature of a template.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000241static LinkageInfo
David Majnemerc7b85c42014-04-23 05:16:48 +0000242getLVForTemplateParameterList(const TemplateParameterList *Params,
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000243 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000244 LinkageInfo LV;
David Majnemerc7b85c42014-04-23 05:16:48 +0000245 for (const NamedDecl *P : *Params) {
John McCalldf25c432013-02-16 00:17:33 +0000246 // Template type parameters are the most common and never
247 // contribute to visibility, pack or not.
David Majnemerc7b85c42014-04-23 05:16:48 +0000248 if (isa<TemplateTypeParmDecl>(P))
John McCalldf25c432013-02-16 00:17:33 +0000249 continue;
250
251 // Non-type template parameters can be restricted by the value type, e.g.
252 // template <enum X> class A { ... };
253 // We have to be careful here, though, because we can be dealing with
254 // dependent types.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000255 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
John McCalldf25c432013-02-16 00:17:33 +0000256 // Handle the non-pack case first.
257 if (!NTTP->isExpandedParameterPack()) {
258 if (!NTTP->getType()->isDependentType()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000259 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000260 }
261 continue;
262 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000263
John McCalldf25c432013-02-16 00:17:33 +0000264 // Look at all the types in an expanded pack.
265 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
266 QualType type = NTTP->getExpansionType(i);
267 if (!type->isDependentType())
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000268 LV.merge(type->getLinkageAndVisibility());
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000269 }
John McCalldf25c432013-02-16 00:17:33 +0000270 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000271 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000272
John McCalldf25c432013-02-16 00:17:33 +0000273 // Template template parameters can be restricted by their
274 // template parameters, recursively.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000275 const auto *TTP = cast<TemplateTemplateParmDecl>(P);
John McCalldf25c432013-02-16 00:17:33 +0000276
277 // Handle the non-pack case first.
278 if (!TTP->isExpandedParameterPack()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000279 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
280 computation));
John McCalldf25c432013-02-16 00:17:33 +0000281 continue;
282 }
283
284 // Look at all expansions in an expanded pack.
285 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
286 i != n; ++i) {
287 LV.merge(getLVForTemplateParameterList(
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000288 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000289 }
290 }
291
John McCall457a04e2010-10-22 21:05:15 +0000292 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000293}
294
Rafael Espindola19de5612013-01-12 06:42:30 +0000295/// getLVForDecl - Get the linkage and visibility for the given declaration.
John McCalldf25c432013-02-16 00:17:33 +0000296static LinkageInfo getLVForDecl(const NamedDecl *D,
297 LVComputationKind computation);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000298
Eli Friedman7e346a82013-07-01 20:22:57 +0000299static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
Craig Topper36250ad2014-05-12 05:36:57 +0000300 const Decl *Ret = nullptr;
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000301 const DeclContext *DC = D->getDeclContext();
302 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman7e346a82013-07-01 20:22:57 +0000303 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
304 Ret = cast<Decl>(DC);
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000305 DC = DC->getParent();
306 }
307 return Ret;
308}
309
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000310/// \brief Get the most restrictive linkage for the types and
311/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000312///
313/// Note that we don't take an LVComputationKind because we always
314/// want to honor the visibility of template arguments in the same way.
David Majnemerc7b85c42014-04-23 05:16:48 +0000315static LinkageInfo getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
316 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000317 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000318
David Majnemerc7b85c42014-04-23 05:16:48 +0000319 for (const TemplateArgument &Arg : Args) {
320 switch (Arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000321 case TemplateArgument::Null:
322 case TemplateArgument::Integral:
323 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000324 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000325
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000326 case TemplateArgument::Type:
David Majnemerc7b85c42014-04-23 05:16:48 +0000327 LV.merge(getLVForType(*Arg.getAsType(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000328 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000329
330 case TemplateArgument::Declaration:
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000331 if (const auto *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
John McCalldf25c432013-02-16 00:17:33 +0000332 assert(!usesTypeVisibility(ND));
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000333 LV.merge(getLVForDecl(ND, computation));
John McCalldf25c432013-02-16 00:17:33 +0000334 }
335 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +0000336
337 case TemplateArgument::NullPtr:
David Majnemerc7b85c42014-04-23 05:16:48 +0000338 LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility());
John McCalldf25c432013-02-16 00:17:33 +0000339 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000340
341 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000342 case TemplateArgument::TemplateExpansion:
David Majnemerc7b85c42014-04-23 05:16:48 +0000343 if (TemplateDecl *Template =
344 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000345 LV.merge(getLVForDecl(Template, computation));
John McCalldf25c432013-02-16 00:17:33 +0000346 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000347
348 case TemplateArgument::Pack:
David Majnemerc7b85c42014-04-23 05:16:48 +0000349 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000350 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000351 }
John McCalldf25c432013-02-16 00:17:33 +0000352 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000353 }
354
John McCall457a04e2010-10-22 21:05:15 +0000355 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000356}
357
Rafael Espindola2f869a32012-01-14 00:30:36 +0000358static LinkageInfo
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000359getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
360 LVComputationKind computation) {
361 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall8823c652010-08-13 08:35:10 +0000362}
363
John McCall5f46c482013-02-21 23:42:58 +0000364static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
365 const FunctionTemplateSpecializationInfo *specInfo) {
366 // Include visibility from the template parameters and arguments
367 // only if this is not an explicit instantiation or specialization
368 // with direct explicit visibility. (Implicit instantiations won't
369 // have a direct attribute.)
370 if (!specInfo->isExplicitInstantiationOrSpecialization())
371 return true;
372
373 return !fn->hasAttr<VisibilityAttr>();
374}
375
John McCalldf25c432013-02-16 00:17:33 +0000376/// Merge in template-related linkage and visibility for the given
377/// function template specialization.
378///
379/// We don't need a computation kind here because we can assume
380/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000381///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000382/// \param[out] LV the computation to use for the parent
John McCall5f46c482013-02-21 23:42:58 +0000383static void
384mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000385 const FunctionTemplateSpecializationInfo *specInfo,
386 LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000387 bool considerVisibility =
388 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000389
390 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000391 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000392 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000393 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000394 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
395
396 // Merge information from the template arguments.
397 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000398 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCalldf25c432013-02-16 00:17:33 +0000399 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000400}
401
John McCall5f46c482013-02-21 23:42:58 +0000402/// Does the given declaration have a direct visibility attribute
403/// that would match the given rules?
404static bool hasDirectVisibilityAttribute(const NamedDecl *D,
405 LVComputationKind computation) {
406 switch (computation) {
407 case LVForType:
408 case LVForExplicitType:
409 if (D->hasAttr<TypeVisibilityAttr>())
410 return true;
411 // fallthrough
412 case LVForValue:
413 case LVForExplicitValue:
414 if (D->hasAttr<VisibilityAttr>())
415 return true;
416 return false;
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000417 case LVForLinkageOnly:
418 return false;
John McCall5f46c482013-02-21 23:42:58 +0000419 }
420 llvm_unreachable("bad visibility computation kind");
421}
422
John McCalld041a9b2013-02-20 01:54:26 +0000423/// Should we consider visibility associated with the template
424/// arguments and parameters of the given class template specialization?
425static bool shouldConsiderTemplateVisibility(
426 const ClassTemplateSpecializationDecl *spec,
427 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000428 // Include visibility from the template parameters and arguments
429 // only if this is not an explicit instantiation or specialization
430 // with direct explicit visibility (and note that implicit
431 // instantiations won't have a direct attribute).
432 //
433 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000434 // for an explicit specialization when computing the visibility of a
435 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000436 //
437 // This is a bit complex; let's unpack it.
438 //
439 // An explicit class specialization is an independent, top-level
440 // declaration. As such, if it or any of its members has an
441 // explicit visibility attribute, that must directly express the
442 // user's intent, and we should honor it. The same logic applies to
443 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000444
445 // Fast path: if this is not an explicit instantiation or
446 // specialization, we always want to consider template-related
447 // visibility restrictions.
448 if (!spec->isExplicitInstantiationOrSpecialization())
449 return true;
450
451 // This is the 'member thereof' check.
452 if (spec->isExplicitSpecialization() &&
453 hasExplicitVisibilityAlready(computation))
454 return false;
455
John McCall5f46c482013-02-21 23:42:58 +0000456 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000457}
458
459/// Merge in template-related linkage and visibility for the given
460/// class template specialization.
461static void mergeTemplateLV(LinkageInfo &LV,
462 const ClassTemplateSpecializationDecl *spec,
463 LVComputationKind computation) {
464 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000465
466 // Merge information from the template parameters, but ignore
467 // visibility if we're only considering template arguments.
468
John McCalld041a9b2013-02-20 01:54:26 +0000469 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000470 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000471 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000472 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000473 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000474
475 // Merge information from the template arguments. We ignore
476 // template-argument visibility if we've got an explicit
477 // instantiation with a visibility attribute.
478 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000479 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000480 if (considerVisibility)
481 LV.mergeVisibility(argsLV);
482 LV.mergeExternalVisibility(argsLV);
John McCallb8c604a2011-06-27 23:06:04 +0000483}
484
Larisse Voufo5899e192014-07-02 23:08:34 +0000485/// Should we consider visibility associated with the template
486/// arguments and parameters of the given variable template
487/// specialization? As usual, follow class template specialization
488/// logic up to initialization.
489static bool shouldConsiderTemplateVisibility(
490 const VarTemplateSpecializationDecl *spec,
491 LVComputationKind computation) {
492 // Include visibility from the template parameters and arguments
493 // only if this is not an explicit instantiation or specialization
494 // with direct explicit visibility (and note that implicit
495 // instantiations won't have a direct attribute).
496 if (!spec->isExplicitInstantiationOrSpecialization())
497 return true;
498
499 // An explicit variable specialization is an independent, top-level
500 // declaration. As such, if it has an explicit visibility attribute,
501 // that must directly express the user's intent, and we should honor
502 // it.
503 if (spec->isExplicitSpecialization() &&
504 hasExplicitVisibilityAlready(computation))
505 return false;
506
507 return !hasDirectVisibilityAttribute(spec, computation);
508}
509
510/// Merge in template-related linkage and visibility for the given
511/// variable template specialization. As usual, follow class template
512/// specialization logic up to initialization.
513static void mergeTemplateLV(LinkageInfo &LV,
514 const VarTemplateSpecializationDecl *spec,
515 LVComputationKind computation) {
516 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
517
518 // Merge information from the template parameters, but ignore
519 // visibility if we're only considering template arguments.
520
521 VarTemplateDecl *temp = spec->getSpecializedTemplate();
522 LinkageInfo tempLV =
523 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
524 LV.mergeMaybeWithVisibility(tempLV,
525 considerVisibility && !hasExplicitVisibilityAlready(computation));
526
527 // Merge information from the template arguments. We ignore
528 // template-argument visibility if we've got an explicit
529 // instantiation with a visibility attribute.
530 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
531 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
532 if (considerVisibility)
533 LV.mergeVisibility(argsLV);
534 LV.mergeExternalVisibility(argsLV);
535}
536
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000537static bool useInlineVisibilityHidden(const NamedDecl *D) {
538 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000539 const LangOptions &Opts = D->getASTContext().getLangOpts();
540 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000541 return false;
542
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000543 const auto *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000544 if (!FD)
545 return false;
546
547 TemplateSpecializationKind TSK = TSK_Undeclared;
548 if (FunctionTemplateSpecializationInfo *spec
549 = FD->getTemplateSpecializationInfo()) {
550 TSK = spec->getTemplateSpecializationKind();
551 } else if (MemberSpecializationInfo *MSI =
552 FD->getMemberSpecializationInfo()) {
553 TSK = MSI->getTemplateSpecializationKind();
554 }
555
Craig Topper36250ad2014-05-12 05:36:57 +0000556 const FunctionDecl *Def = nullptr;
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000557 // InlineVisibilityHidden only applies to definitions, and
558 // isInlined() only gives meaningful answers on definitions
559 // anyway.
560 return TSK != TSK_ExplicitInstantiationDeclaration &&
561 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000562 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000563}
564
Rafael Espindola593537a2013-05-05 20:15:21 +0000565template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000566 const T *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +0000567 return First->isInExternCContext();
Rafael Espindolaf4187652013-02-14 01:18:37 +0000568}
569
Richard Smith03c05032014-02-17 23:34:47 +0000570static bool isSingleLineLanguageLinkage(const Decl &D) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000571 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Richard Smith03c05032014-02-17 23:34:47 +0000572 if (!SD->hasBraces())
Rafael Espindola327be3c2013-04-26 01:30:23 +0000573 return true;
574 return false;
575}
576
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000577static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
John McCalldf25c432013-02-16 00:17:33 +0000578 LVComputationKind computation) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000579 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000580 "Not a name having namespace scope");
581 ASTContext &Context = D->getASTContext();
582
583 // C++ [basic.link]p3:
584 // A name having namespace scope (3.3.6) has internal linkage if it
585 // is the name of
586 // - an object, reference, function or function template that is
587 // explicitly declared static; or,
588 // (This bullet corresponds to C99 6.2.2p3.)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000589 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000590 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000591 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000592 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000593
Richard Smithdc0ef452012-10-19 06:37:48 +0000594 // - a non-volatile object or reference that is explicitly declared const
595 // or constexpr and neither explicitly declared extern nor previously
596 // declared to have external linkage; or (there is no equivalent in C99)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000597 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000598 Var->getType().isConstQualified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000599 !Var->getType().isVolatileQualified()) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000600 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000601 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000602 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000603
604 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000605 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000606 !isSingleLineLanguageLinkage(*Var))
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000607 return LinkageInfo::internal();
608 }
609
610 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
611 PrevVar = PrevVar->getPreviousDecl()) {
612 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
613 Var->getStorageClass() == SC_None)
614 return PrevVar->getLinkageAndVisibility();
615 // Explicitly declared static.
616 if (PrevVar->getStorageClass() == SC_Static)
617 return LinkageInfo::internal();
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000618 }
Alp Tokera2794f92014-01-22 07:29:52 +0000619 } else if (const FunctionDecl *Function = D->getAsFunction()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000620 // C++ [temp]p4:
621 // A non-member function template can have internal linkage; any
622 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000623
624 // Explicitly declared static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000625 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000626 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
David Majnemer18fac3b2014-12-10 22:58:14 +0000627 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
628 // - a data member of an anonymous union.
629 const VarDecl *VD = IFD->getVarDecl();
630 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
631 return getLVForNamespaceScopeDecl(VD, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000632 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000633 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000634
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000635 if (D->isInAnonymousNamespace()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000636 const auto *Var = dyn_cast<VarDecl>(D);
637 const auto *Func = dyn_cast<FunctionDecl>(D);
Richard Smith97135cc2015-11-12 22:19:45 +0000638 // FIXME: In C++11 onwards, anonymous namespaces should give decls
639 // within them internal linkage, not unique external linkage.
Rafael Espindola593537a2013-05-05 20:15:21 +0000640 if ((!Var || !isFirstInExternCContext(Var)) &&
641 (!Func || !isFirstInExternCContext(Func)))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000642 return LinkageInfo::uniqueExternal();
643 }
John McCallb7139c42010-10-28 04:18:25 +0000644
John McCall457a04e2010-10-22 21:05:15 +0000645 // Set up the defaults.
646
647 // C99 6.2.2p5:
648 // If the declaration of an identifier for an object has file
649 // scope and no storage-class specifier, its linkage is
650 // external.
John McCallc273f242010-10-30 11:50:40 +0000651 LinkageInfo LV;
652
John McCalld041a9b2013-02-20 01:54:26 +0000653 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000654 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000655 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000656 } else {
657 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000658 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000659 for (const DeclContext *DC = D->getDeclContext();
660 !isa<TranslationUnitDecl>(DC);
661 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000662 const auto *ND = dyn_cast<NamespaceDecl>(DC);
Rafael Espindola78158af2012-04-16 18:46:26 +0000663 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000664 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000665 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000666 break;
667 }
668 }
669 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000670
John McCalldf25c432013-02-16 00:17:33 +0000671 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000672 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000673 // Use global type/value visibility as appropriate.
674 Visibility globalVisibility;
675 if (computation == LVForValue) {
Larisse Voufo404e1422015-02-04 02:34:32 +0000676 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
John McCallb4a99d32013-02-19 01:57:35 +0000677 } else {
678 assert(computation == LVForType);
679 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
680 }
681 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000682
683 // If we're paying attention to global visibility, apply
684 // -finline-visibility-hidden if this is an inline method.
685 if (useInlineVisibilityHidden(D))
686 LV.mergeVisibility(HiddenVisibility, true);
687 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000688 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000689
Douglas Gregorf73b2822009-11-25 22:24:25 +0000690 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000691
Douglas Gregorf73b2822009-11-25 22:24:25 +0000692 // A name having namespace scope has external linkage if it is the
693 // name of
694 //
695 // - an object or reference, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000696 if (const auto *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000697 // GCC applies the following optimization to variables and static
698 // data members, but not to functions:
699 //
John McCall457a04e2010-10-22 21:05:15 +0000700 // Modify the variable's LV by the LV of its type unless this is
701 // C or extern "C". This follows from [basic.link]p9:
702 // A type without linkage shall not be used as the type of a
703 // variable or function with external linkage unless
704 // - the entity has C language linkage, or
705 // - the entity is declared within an unnamed namespace, or
706 // - the entity is not used or is defined in the same
707 // translation unit.
708 // and [basic.link]p10:
709 // ...the types specified by all declarations referring to a
710 // given variable or function shall be identical...
711 // C does not have an equivalent rule.
712 //
John McCall5fe84122010-10-26 04:59:26 +0000713 // Ignore this if we've got an explicit attribute; the user
714 // probably knows what they're doing.
715 //
John McCall457a04e2010-10-22 21:05:15 +0000716 // Note that we don't want to make the variable non-external
717 // because of this, but unique-external linkage suits us.
Rafael Espindola593537a2013-05-05 20:15:21 +0000718 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000719 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Rafael Espindola4a5da442013-02-27 02:56:45 +0000720 if (TypeLV.getLinkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000721 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000722 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000723 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000724 }
725
John McCall23032652010-11-02 18:38:13 +0000726 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000727 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000728
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000729 // Note that Sema::MergeVarDecl already takes care of implementing
730 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
731 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000732
Larisse Voufo5899e192014-07-02 23:08:34 +0000733 // As per function and class template specializations (below),
734 // consider LV for the template and template arguments. We're at file
735 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000736 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000737 mergeTemplateLV(LV, spec, computation);
738 }
739
Douglas Gregorf73b2822009-11-25 22:24:25 +0000740 // - a function, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000741 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000742 // In theory, we can modify the function's LV by the LV of its
743 // type unless it has C linkage (see comment above about variables
744 // for justification). In practice, GCC doesn't do this, so it's
745 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000746
John McCall23032652010-11-02 18:38:13 +0000747 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000748 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000749
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000750 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
751 // merging storage classes and visibility attributes, so we don't have to
752 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000753
John McCallf768aa72011-02-10 06:50:24 +0000754 // In C++, then if the type of the function uses a type with
755 // unique-external linkage, it's not legally usable from outside
756 // this translation unit. However, we should use the C linkage
757 // rules instead for extern "C" declarations.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000758 if (Context.getLangOpts().CPlusPlus &&
Richard Smith50f4afc2013-05-12 23:17:59 +0000759 !Function->isInExternCContext()) {
760 // Only look at the type-as-written. If this function has an auto-deduced
761 // return type, we can't compute the linkage of that type because it could
762 // require looking at the linkage of this function, and we don't need this
763 // for correctness because the type is not part of the function's
764 // signature.
Faisal Valid2598e92013-10-08 04:15:04 +0000765 // FIXME: This is a hack. We should be able to solve this circularity and
766 // the one in getLVForClassMember for Functions some other way.
Richard Smith50f4afc2013-05-12 23:17:59 +0000767 QualType TypeAsWritten = Function->getType();
768 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
769 TypeAsWritten = TSI->getType();
770 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
771 return LinkageInfo::uniqueExternal();
772 }
John McCallf768aa72011-02-10 06:50:24 +0000773
John McCall5f46c482013-02-21 23:42:58 +0000774 // Consider LV from the template and the template arguments.
775 // We're at file scope, so we do not need to worry about nested
776 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000777 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000778 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000779 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000780 }
781
Douglas Gregorf73b2822009-11-25 22:24:25 +0000782 // - a named class (Clause 9), or an unnamed class defined in a
783 // typedef declaration in which the class has the typedef name
784 // for linkage purposes (7.1.3); or
785 // - a named enumeration (7.2), or an unnamed enumeration
786 // defined in a typedef declaration in which the enumeration
787 // has the typedef name for linkage purposes (7.1.3); or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000788 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000789 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000790 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000791 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000792
John McCall457a04e2010-10-22 21:05:15 +0000793 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000794 // linkage of the template and template arguments. We're at file
795 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000796 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000797 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000798 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000799
800 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000801 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000802 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000803 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000804 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000805 return LinkageInfo::none();
806 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000807
808 // - a template, unless it is a function template that has
809 // internal linkage (Clause 14);
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000810 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000811 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000812 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000813 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000814 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
815
Douglas Gregorf73b2822009-11-25 22:24:25 +0000816 // - a namespace (7.3), unless it is declared within an unnamed
817 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000818 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
819 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000820
John McCall457a04e2010-10-22 21:05:15 +0000821 // By extension, we assign external linkage to Objective-C
822 // interfaces.
823 } else if (isa<ObjCInterfaceDecl>(D)) {
824 // fallout
825
Richard Smith97135cc2015-11-12 22:19:45 +0000826 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
827 // A typedef declaration has linkage if it gives a type a name for
828 // linkage purposes.
829 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
830 return LinkageInfo::none();
831
John McCall457a04e2010-10-22 21:05:15 +0000832 // Everything not covered here has no linkage.
833 } else {
John McCallc273f242010-10-30 11:50:40 +0000834 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000835 }
836
837 // If we ended up with non-external linkage, visibility should
838 // always be default.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000839 if (LV.getLinkage() != ExternalLinkage)
840 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000841
John McCall457a04e2010-10-22 21:05:15 +0000842 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000843}
844
John McCalldf25c432013-02-16 00:17:33 +0000845static LinkageInfo getLVForClassMember(const NamedDecl *D,
846 LVComputationKind computation) {
John McCall457a04e2010-10-22 21:05:15 +0000847 // Only certain class members have linkage. Note that fields don't
848 // really have linkage, but it's convenient to say they do for the
849 // purposes of calculating linkage of pointer-to-data-member
850 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000851 //
852 // Templates also don't officially have linkage, but since we ignore
853 // the C++ standard and look at template arguments when determining
854 // linkage and visibility of a template specialization, we might hit
855 // a template template argument that way. If we do, we need to
856 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000857 if (!(isa<CXXMethodDecl>(D) ||
858 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000859 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000860 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000861 isa<TagDecl>(D) ||
862 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000863 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000864
John McCall07072662010-11-02 01:45:15 +0000865 LinkageInfo LV;
866
John McCall07072662010-11-02 01:45:15 +0000867 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000868 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000869 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000870 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000871 // If we're paying attention to global visibility, apply
872 // -finline-visibility-hidden if this is an inline method.
873 //
874 // Note that we do this before merging information about
875 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000876 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000877 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000878 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000879
880 // If this class member has an explicit visibility attribute, the only
881 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000882 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000883 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000884 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000885 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000886
John McCall5f46c482013-02-21 23:42:58 +0000887 LinkageInfo classLV =
888 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
John McCall8823c652010-08-13 08:35:10 +0000889 // If the class already has unique-external linkage, we can't improve.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000890 if (classLV.getLinkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000891 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000892
Rafael Espindolae6190db2013-05-28 02:22:10 +0000893 if (!isExternallyVisible(classLV.getLinkage()))
894 return LinkageInfo::none();
895
896
John McCall5f46c482013-02-21 23:42:58 +0000897 // Otherwise, don't merge in classLV yet, because in certain cases
898 // we need to completely ignore the visibility from it.
899
900 // Specifically, if this decl exists and has an explicit attribute.
Craig Topper36250ad2014-05-12 05:36:57 +0000901 const NamedDecl *explicitSpecSuppressor = nullptr;
John McCall5f46c482013-02-21 23:42:58 +0000902
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000903 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000904 // If the type of the function uses a type with unique-external
905 // linkage, it's not legally usable from outside this translation unit.
Nico Weber38267342015-04-22 03:44:51 +0000906 // But only look at the type-as-written. If this function has an
907 // auto-deduced return type, we can't compute the linkage of that type
908 // because it could require looking at the linkage of this function, and we
909 // don't need this for correctness because the type is not part of the
910 // function's signature.
911 // FIXME: This is a hack. We should be able to solve this circularity and
912 // the one in getLVForNamespaceScopeDecl for Functions some other way.
Faisal Valid2598e92013-10-08 04:15:04 +0000913 {
914 QualType TypeAsWritten = MD->getType();
915 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
916 TypeAsWritten = TSI->getType();
917 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
918 return LinkageInfo::uniqueExternal();
919 }
John McCall457a04e2010-10-22 21:05:15 +0000920 // If this is a method template specialization, use the linkage for
921 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000922 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000923 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000924 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000925 if (spec->isExplicitSpecialization()) {
926 explicitSpecSuppressor = MD;
927 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
928 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
929 }
930 } else if (isExplicitMemberSpecialization(MD)) {
931 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000932 }
John McCall457a04e2010-10-22 21:05:15 +0000933
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000934 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
935 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000936 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000937 if (spec->isExplicitSpecialization()) {
938 explicitSpecSuppressor = spec;
939 } else {
940 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
941 if (isExplicitMemberSpecialization(temp)) {
942 explicitSpecSuppressor = temp->getTemplatedDecl();
943 }
944 }
945 } else if (isExplicitMemberSpecialization(RD)) {
946 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000947 }
948
John McCall37bb6c92010-10-29 22:22:43 +0000949 // Static data members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000950 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
951 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
Larisse Voufo5899e192014-07-02 23:08:34 +0000952 mergeTemplateLV(LV, spec, computation);
953
John McCall36cd5cc2010-10-30 09:18:49 +0000954 // Modify the variable's linkage by its type, but ignore the
955 // type's visibility unless it's a definition.
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000956 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000957 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
958 LV.mergeVisibility(typeLV);
959 LV.mergeExternalVisibility(typeLV);
John McCall5f46c482013-02-21 23:42:58 +0000960
961 if (isExplicitMemberSpecialization(VD)) {
962 explicitSpecSuppressor = VD;
963 }
John McCalldf25c432013-02-16 00:17:33 +0000964
965 // Template members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000966 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +0000967 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +0000968 (!LV.isVisibilityExplicit() &&
969 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000970 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000971 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000972 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000973 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +0000974
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000975 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
John McCall5f46c482013-02-21 23:42:58 +0000976 if (isExplicitMemberSpecialization(redeclTemp)) {
977 explicitSpecSuppressor = temp->getTemplatedDecl();
978 }
979 }
John McCall37bb6c92010-10-29 22:22:43 +0000980 }
981
John McCall5f46c482013-02-21 23:42:58 +0000982 // We should never be looking for an attribute directly on a template.
983 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
984
985 // If this member is an explicit member specialization, and it has
986 // an explicit attribute, ignore visibility from the parent.
987 bool considerClassVisibility = true;
988 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +0000989 // optimization: hasDVA() is true only with explicit visibility.
990 LV.isVisibilityExplicit() &&
991 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +0000992 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
993 considerClassVisibility = false;
994 }
995
996 // Finally, merge in information from the class.
997 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +0000998 return LV;
John McCall8823c652010-08-13 08:35:10 +0000999}
1000
David Blaikie68e081d2011-12-20 02:48:34 +00001001void NamedDecl::anchor() { }
1002
Rafael Espindolaecf63c62013-05-29 04:55:30 +00001003static LinkageInfo computeLVForDecl(const NamedDecl *D,
1004 LVComputationKind computation);
1005
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001006bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001007 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001008 return true;
John McCalld396b972011-02-08 19:01:05 +00001009
Rafael Espindolaecf63c62013-05-29 04:55:30 +00001010 return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
Rafael Espindola50df3a02013-05-25 17:16:20 +00001011 getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +00001012}
1013
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001014ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1015 StringRef name = getName();
1016 if (name.empty()) return SFF_None;
1017
1018 if (name.front() == 'C')
1019 if (name == "CFStringCreateWithFormat" ||
1020 name == "CFStringCreateWithFormatAndArguments" ||
1021 name == "CFStringAppendFormat" ||
1022 name == "CFStringAppendFormatAndArguments")
1023 return SFF_CFString;
1024 return SFF_None;
1025}
1026
Rafael Espindola3ae00052013-05-13 00:12:11 +00001027Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +00001028 // We don't care about visibility here, so ask for the cheapest
1029 // possible visibility analysis.
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001030 return getLVForDecl(this, LVForLinkageOnly).getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001031}
1032
John McCallc273f242010-10-30 11:50:40 +00001033LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCalldf25c432013-02-16 00:17:33 +00001034 LVComputationKind computation =
1035 (usesTypeVisibility(this) ? LVForType : LVForValue);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001036 return getLVForDecl(this, computation);
John McCall033caa52010-10-29 00:29:13 +00001037}
Ted Kremenek926d8602010-04-20 23:15:35 +00001038
Rafael Espindola9ad61122013-11-26 16:09:08 +00001039static Optional<Visibility>
1040getExplicitVisibilityAux(const NamedDecl *ND,
1041 NamedDecl::ExplicitVisibilityKind kind,
1042 bool IsMostRecent) {
1043 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1044
Rafael Espindola3a52c442013-02-26 19:33:14 +00001045 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001046 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001047 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001048
Rafael Espindola3a52c442013-02-26 19:33:14 +00001049 // If this is a member class of a specialization of a class template
1050 // and the corresponding decl has explicit visibility, use that.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001051 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +00001052 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1053 if (InstantiatedFrom)
1054 return getVisibilityOf(InstantiatedFrom, kind);
1055 }
1056
1057 // If there wasn't explicit visibility there, and this is a
1058 // specialization of a class template, check for visibility
1059 // on the pattern.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001060 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001061 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1062 kind);
1063
1064 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +00001065 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +00001066 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1067 if (MostRecent != ND)
1068 return getExplicitVisibilityAux(MostRecent, kind, true);
1069 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001070
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001071 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +00001072 if (Var->isStaticDataMember()) {
1073 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1074 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001075 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +00001076 }
1077
David Majnemer35b02bc2014-04-29 07:32:26 +00001078 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1079 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1080 kind);
1081
David Blaikie7a30dc52013-02-21 01:47:18 +00001082 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +00001083 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001084 // Also handle function template specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001085 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001086 // If the function is a specialization of a template with an
1087 // explicit visibility attribute, use that.
1088 if (FunctionTemplateSpecializationInfo *templateInfo
1089 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +00001090 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1091 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001092
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001093 // If the function is a member of a specialization of a class template
1094 // and the corresponding decl has explicit visibility, use that.
1095 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1096 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001097 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001098
David Blaikie7a30dc52013-02-21 01:47:18 +00001099 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001100 }
1101
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001102 // The visibility of a template is stored in the templated decl.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001103 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001104 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001105
David Blaikie7a30dc52013-02-21 01:47:18 +00001106 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001107}
1108
Rafael Espindola9ad61122013-11-26 16:09:08 +00001109Optional<Visibility>
1110NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1111 return getExplicitVisibilityAux(this, kind, false);
1112}
1113
Eli Friedman7e346a82013-07-01 20:22:57 +00001114static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
1115 LVComputationKind computation) {
1116 // This lambda has its linkage/visibility determined by its owner.
1117 if (ContextDecl) {
1118 if (isa<ParmVarDecl>(ContextDecl))
1119 DC = ContextDecl->getDeclContext()->getRedeclContext();
1120 else
1121 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1122 }
Faisal Vali98b8e182013-09-29 20:27:06 +00001123
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001124 if (const auto *ND = dyn_cast<NamedDecl>(DC))
Eli Friedman7e346a82013-07-01 20:22:57 +00001125 return getLVForDecl(ND, computation);
Faisal Vali98b8e182013-09-29 20:27:06 +00001126
Eli Friedman7e346a82013-07-01 20:22:57 +00001127 return LinkageInfo::external();
1128}
1129
John McCalldf25c432013-02-16 00:17:33 +00001130static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1131 LVComputationKind computation) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001132 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001133 if (Function->isInAnonymousNamespace() &&
Rafael Espindola593537a2013-05-05 20:15:21 +00001134 !Function->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001135 return LinkageInfo::uniqueExternal();
1136
1137 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001138 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCalldf25c432013-02-16 00:17:33 +00001139 return LinkageInfo::internal();
1140
1141 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001142 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001143 if (Optional<Visibility> Vis =
1144 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001145 LV.mergeVisibility(*Vis, true);
1146 }
1147
1148 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1149 // merging storage classes and visibility attributes, so we don't have to
1150 // look at previous decls in here.
1151
1152 return LV;
1153 }
1154
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001155 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001156 if (Var->hasExternalStorage()) {
Rafael Espindola593537a2013-05-05 20:15:21 +00001157 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001158 return LinkageInfo::uniqueExternal();
1159
John McCalldf25c432013-02-16 00:17:33 +00001160 LinkageInfo LV;
1161 if (Var->getStorageClass() == SC_PrivateExtern)
1162 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001163 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001164 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001165 LV.mergeVisibility(*Vis, true);
1166 }
1167
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001168 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1169 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1170 if (PrevLV.getLinkage())
1171 LV.setLinkage(PrevLV.getLinkage());
1172 LV.mergeVisibility(PrevLV);
1173 }
1174
John McCalldf25c432013-02-16 00:17:33 +00001175 return LV;
1176 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001177
1178 if (!Var->isStaticLocal())
1179 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001180 }
1181
Rafael Espindolaa4184182013-06-17 20:04:51 +00001182 ASTContext &Context = D->getASTContext();
1183 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001184 return LinkageInfo::none();
1185
Eli Friedman7e346a82013-07-01 20:22:57 +00001186 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1187 if (!OuterD)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001188 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001189
Eli Friedman7e346a82013-07-01 20:22:57 +00001190 LinkageInfo LV;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001191 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001192 if (!BD->getBlockManglingNumber())
1193 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001194
Eli Friedman7e346a82013-07-01 20:22:57 +00001195 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1196 BD->getBlockManglingContextDecl(), computation);
1197 } else {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001198 const auto *FD = cast<FunctionDecl>(OuterD);
Eli Friedman7e346a82013-07-01 20:22:57 +00001199 if (!FD->isInlined() &&
David Majnemer9963ade2014-12-16 04:52:14 +00001200 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
Eli Friedman7e346a82013-07-01 20:22:57 +00001201 return LinkageInfo::none();
1202
1203 LV = getLVForDecl(FD, computation);
1204 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001205 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001206 return LinkageInfo::none();
1207 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1208 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001209}
1210
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001211static inline const CXXRecordDecl*
1212getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1213 const CXXRecordDecl *Ret = Record;
1214 while (Record && Record->isLambda()) {
1215 Ret = Record;
1216 if (!Record->getParent()) break;
1217 // Get the Containing Class of this Lambda Class
1218 Record = dyn_cast_or_null<CXXRecordDecl>(
1219 Record->getParent()->getParent());
1220 }
1221 return Ret;
1222}
1223
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001224static LinkageInfo computeLVForDecl(const NamedDecl *D,
1225 LVComputationKind computation) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001226 // Internal_linkage attribute overrides other considerations.
1227 if (D->hasAttr<InternalLinkageAttr>())
1228 return LinkageInfo::internal();
1229
Ted Kremenek926d8602010-04-20 23:15:35 +00001230 // Objective-C: treat all Objective-C declarations as having external
1231 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001232 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001233 default:
1234 break;
Richard Smith97135cc2015-11-12 22:19:45 +00001235
1236 // Per C++ [basic.link]p2, only the names of objects, references,
1237 // functions, types, templates, namespaces, and values ever have linkage.
1238 //
1239 // Note that the name of a typedef, namespace alias, using declaration,
1240 // and so on are not the name of the corresponding type, namespace, or
1241 // declaration, so they do *not* have linkage.
Richard Smith97135cc2015-11-12 22:19:45 +00001242 case Decl::ImplicitParam:
1243 case Decl::Label:
1244 case Decl::NamespaceAlias:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001245 case Decl::ParmVar:
Richard Smith97135cc2015-11-12 22:19:45 +00001246 case Decl::Using:
1247 case Decl::UsingShadow:
1248 case Decl::UsingDirective:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001249 return LinkageInfo::none();
Richard Smith97135cc2015-11-12 22:19:45 +00001250
Richard Smith26210db2015-11-13 03:52:13 +00001251 case Decl::EnumConstant:
1252 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
1253 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1254
Richard Smith97135cc2015-11-12 22:19:45 +00001255 case Decl::Typedef:
1256 case Decl::TypeAlias:
1257 // A typedef declaration has linkage if it gives a type a name for
1258 // linkage purposes.
1259 if (!cast<TypedefNameDecl>(D)
1260 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1261 return LinkageInfo::none();
1262 break;
1263
John McCall457a04e2010-10-22 21:05:15 +00001264 case Decl::TemplateTemplateParm: // count these as external
1265 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001266 case Decl::ObjCAtDefsField:
1267 case Decl::ObjCCategory:
1268 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001269 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001270 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001271 case Decl::ObjCMethod:
1272 case Decl::ObjCProperty:
1273 case Decl::ObjCPropertyImpl:
1274 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +00001275 return LinkageInfo::external();
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001276
1277 case Decl::CXXRecord: {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001278 const auto *Record = cast<CXXRecordDecl>(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001279 if (Record->isLambda()) {
1280 if (!Record->getLambdaManglingNumber()) {
1281 // This lambda has no mangling number, so it's internal.
1282 return LinkageInfo::internal();
1283 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001284
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001285 // This lambda has its linkage/visibility determined:
1286 // - either by the outermost lambda if that lambda has no mangling
1287 // number.
1288 // - or by the parent of the outer most lambda
1289 // This prevents infinite recursion in settings such as nested lambdas
1290 // used in NSDMI's, for e.g.
1291 // struct L {
1292 // int t{};
1293 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1294 // };
1295 const CXXRecordDecl *OuterMostLambda =
1296 getOutermostEnclosingLambda(Record);
1297 if (!OuterMostLambda->getLambdaManglingNumber())
1298 return LinkageInfo::internal();
1299
1300 return getLVForClosure(
1301 OuterMostLambda->getDeclContext()->getRedeclContext(),
1302 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001303 }
1304
1305 break;
1306 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001307 }
1308
Douglas Gregorf73b2822009-11-25 22:24:25 +00001309 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001310 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCalldf25c432013-02-16 00:17:33 +00001311 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001312
1313 // C++ [basic.link]p5:
1314 // In addition, a member function, static data member, a named
1315 // class or enumeration of class scope, or an unnamed class or
1316 // enumeration defined in a class-scope typedef declaration such
1317 // that the class or enumeration has the typedef name for linkage
1318 // purposes (7.1.3), has external linkage if the name of the class
1319 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001320 if (D->getDeclContext()->isRecord())
John McCalldf25c432013-02-16 00:17:33 +00001321 return getLVForClassMember(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001322
1323 // C++ [basic.link]p6:
1324 // The name of a function declared in block scope and the name of
1325 // an object declared by a block scope extern declaration have
1326 // linkage. If there is a visible declaration of an entity with
1327 // linkage having the same name and type, ignoring entities
1328 // declared outside the innermost enclosing namespace scope, the
1329 // block scope declaration declares that same entity and receives
1330 // the linkage of the previous declaration. If there is more than
1331 // one such matching entity, the program is ill-formed. Otherwise,
1332 // if no matching entity is found, the block scope entity receives
1333 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001334 if (D->getDeclContext()->isFunctionOrMethod())
1335 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001336
1337 // C++ [basic.link]p6:
1338 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001339 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001340}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001341
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001342namespace clang {
1343class LinkageComputer {
1344public:
1345 static LinkageInfo getLVForDecl(const NamedDecl *D,
1346 LVComputationKind computation) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001347 // Internal_linkage attribute overrides other considerations.
1348 if (D->hasAttr<InternalLinkageAttr>())
1349 return LinkageInfo::internal();
1350
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001351 if (computation == LVForLinkageOnly && D->hasCachedLinkage())
1352 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1353
1354 LinkageInfo LV = computeLVForDecl(D, computation);
1355 if (D->hasCachedLinkage())
1356 assert(D->getCachedLinkage() == LV.getLinkage());
1357
1358 D->setCachedLinkage(LV.getLinkage());
1359
1360#ifndef NDEBUG
1361 // In C (because of gnu inline) and in c++ with microsoft extensions an
1362 // static can follow an extern, so we can have two decls with different
1363 // linkages.
1364 const LangOptions &Opts = D->getASTContext().getLangOpts();
1365 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1366 return LV;
1367
1368 // We have just computed the linkage for this decl. By induction we know
1369 // that all other computed linkages match, check that the one we just
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001370 // computed also does.
Craig Topper36250ad2014-05-12 05:36:57 +00001371 NamedDecl *Old = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +00001372 for (auto I : D->redecls()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001373 auto *T = cast<NamedDecl>(I);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001374 if (T == D)
1375 continue;
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001376 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001377 Old = T;
1378 break;
1379 }
1380 }
1381 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1382#endif
1383
1384 return LV;
1385 }
1386};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001387}
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001388
1389static LinkageInfo getLVForDecl(const NamedDecl *D,
1390 LVComputationKind computation) {
1391 return clang::LinkageComputer::getLVForDecl(D, computation);
1392}
1393
Douglas Gregor2ada0482009-02-04 17:27:36 +00001394std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001395 std::string QualName;
1396 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001397 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001398 return OS.str();
1399}
1400
1401void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1402 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1403}
1404
1405void NamedDecl::printQualifiedName(raw_ostream &OS,
1406 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001407 const DeclContext *Ctx = getDeclContext();
1408
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001409 if (Ctx->isFunctionOrMethod()) {
1410 printName(OS);
1411 return;
1412 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001413
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001414 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001415 ContextsTy Contexts;
1416
1417 // Collect contexts.
1418 while (Ctx && isa<NamedDecl>(Ctx)) {
1419 Contexts.push_back(Ctx);
1420 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001421 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001422
1423 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1424 I != E; ++I) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001425 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001426 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001427 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00001428 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1429 TemplateArgs.data(),
1430 TemplateArgs.size(),
1431 P);
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001432 } else if (const auto *ND = dyn_cast<NamespaceDecl>(*I)) {
Richard Smith46dd5bb2014-05-30 22:16:51 +00001433 if (P.SuppressUnwrittenScope &&
1434 (ND->isAnonymousNamespace() || ND->isInline()))
1435 continue;
Sam Weinig07d211e2009-12-24 23:15:03 +00001436 if (ND->isAnonymousNamespace())
David Blaikieabe1a392014-04-02 05:58:29 +00001437 OS << "(anonymous namespace)";
Sam Weinig07d211e2009-12-24 23:15:03 +00001438 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001439 OS << *ND;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001440 } else if (const auto *RD = dyn_cast<RecordDecl>(*I)) {
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001441 if (!RD->getIdentifier())
David Blaikieabe1a392014-04-02 05:58:29 +00001442 OS << "(anonymous " << RD->getKindName() << ')';
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001443 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001444 OS << *RD;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001445 } else if (const auto *FD = dyn_cast<FunctionDecl>(*I)) {
Craig Topper36250ad2014-05-12 05:36:57 +00001446 const FunctionProtoType *FT = nullptr;
Sam Weinigb999f682009-12-28 03:19:38 +00001447 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001448 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001449
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001450 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001451 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001452 unsigned NumParams = FD->getNumParams();
1453 for (unsigned i = 0; i < NumParams; ++i) {
1454 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001455 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001456 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001457 }
1458
1459 if (FT->isVariadic()) {
1460 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001461 OS << ", ";
1462 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001463 }
1464 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001465 OS << ')';
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001466 } else if (const auto *ED = dyn_cast<EnumDecl>(*I)) {
Alexander Kornienko4f355322015-11-09 16:45:17 +00001467 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1468 // enumerator is declared in the scope that immediately contains
1469 // the enum-specifier. Each scoped enumerator is declared in the
1470 // scope of the enumeration.
1471 if (ED->isScoped() || ED->getIdentifier())
1472 OS << *ED;
1473 else
1474 continue;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001475 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001476 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001477 }
1478 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001479 }
1480
John McCalla2a3f7d2010-03-16 21:48:18 +00001481 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001482 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001483 else
David Blaikieabe1a392014-04-02 05:58:29 +00001484 OS << "(anonymous)";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001485}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001486
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001487void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1488 const PrintingPolicy &Policy,
1489 bool Qualified) const {
1490 if (Qualified)
1491 printQualifiedName(OS, Policy);
1492 else
1493 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001494}
1495
Richard Smithe8292b12015-02-10 03:28:10 +00001496template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1497 return true;
1498}
1499static bool isRedeclarableImpl(...) { return false; }
1500static bool isRedeclarable(Decl::Kind K) {
1501 switch (K) {
1502#define DECL(Type, Base) \
1503 case Decl::Type: \
1504 return isRedeclarableImpl((Type##Decl *)nullptr);
1505#define ABSTRACT_DECL(DECL)
1506#include "clang/AST/DeclNodes.inc"
1507 }
1508 llvm_unreachable("unknown decl kind");
1509}
1510
1511bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001512 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1513
Richard Smithfe620d22015-03-05 23:24:12 +00001514 // Never replace one imported declaration with another; we need both results
1515 // when re-exporting.
1516 if (OldD->isFromASTFile() && isFromASTFile())
1517 return false;
1518
Richard Smith5cd86f82015-11-03 03:13:11 +00001519 // A kind mismatch implies that the declaration is not replaced.
1520 if (OldD->getKind() != getKind())
Richard Smithe8292b12015-02-10 03:28:10 +00001521 return false;
1522
Richard Smith5cd86f82015-11-03 03:13:11 +00001523 // For method declarations, we never replace. (Why?)
1524 if (isa<ObjCMethodDecl>(this))
1525 return false;
1526
1527 // For parameters, pick the newer one. This is either an error or (in
1528 // Objective-C) permitted as an extension.
1529 if (isa<ParmVarDecl>(this))
1530 return true;
1531
Richard Smithe8292b12015-02-10 03:28:10 +00001532 // Inline namespaces can give us two declarations with the same
1533 // name and kind in the same scope but different contexts; we should
1534 // keep both declarations in this case.
1535 if (!this->getDeclContext()->getRedeclContext()->Equals(
1536 OldD->getDeclContext()->getRedeclContext()))
1537 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001538
Richard Smith5cd86f82015-11-03 03:13:11 +00001539 // Using declarations can be replaced if they import the same name from the
1540 // same context.
Richard Smithe8292b12015-02-10 03:28:10 +00001541 if (auto *UD = dyn_cast<UsingDecl>(this)) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001542 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001543 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001544 Context.getCanonicalNestedNameSpecifier(
Richard Smithe8292b12015-02-10 03:28:10 +00001545 cast<UsingDecl>(OldD)->getQualifier());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001546 }
Richard Smithe8292b12015-02-10 03:28:10 +00001547 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001548 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001549 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001550 Context.getCanonicalNestedNameSpecifier(
1551 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1552 }
1553
Richard Smithe8292b12015-02-10 03:28:10 +00001554 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
Richard Smith5cd86f82015-11-03 03:13:11 +00001555 // They can be replaced if they nominate the same namespace.
1556 // FIXME: Is this true even if they have different module visibility?
Richard Smithe8292b12015-02-10 03:28:10 +00001557 if (auto *UD = dyn_cast<UsingDirectiveDecl>(this))
1558 return UD->getNominatedNamespace()->getOriginalNamespace() ==
1559 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1560 ->getOriginalNamespace();
Richard Smithbaf3ca52014-03-17 21:46:03 +00001561
Richard Smith5cd86f82015-11-03 03:13:11 +00001562 if (isRedeclarable(getKind())) {
1563 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1564 return false;
1565
1566 if (IsKnownNewer)
1567 return true;
1568
Richard Smithe8292b12015-02-10 03:28:10 +00001569 // Check whether this is actually newer than OldD. We want to keep the
1570 // newer declaration. This loop will usually only iterate once, because
1571 // OldD is usually the previous declaration.
1572 for (auto D : redecls()) {
1573 if (D == OldD)
1574 break;
1575
1576 // If we reach the canonical declaration, then OldD is not actually older
1577 // than this one.
1578 //
1579 // FIXME: In this case, we should not add this decl to the lookup table.
1580 if (D->isCanonicalDecl())
1581 return false;
1582 }
Richard Smith5cd86f82015-11-03 03:13:11 +00001583
1584 // It's a newer declaration of the same kind of declaration in the same
1585 // scope: we want this decl instead of the existing one.
1586 return true;
Richard Smithe8292b12015-02-10 03:28:10 +00001587 }
1588
Richard Smith5cd86f82015-11-03 03:13:11 +00001589 // In all other cases, we need to keep both declarations in case they have
1590 // different visibility. Any attempt to use the name will result in an
1591 // ambiguity if more than one is visible.
1592 return false;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001593}
1594
Douglas Gregoreddf4332009-02-24 20:03:32 +00001595bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001596 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001597}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001598
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001599NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001600 NamedDecl *ND = this;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001601 while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001602 ND = UD->getTargetDecl();
1603
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001604 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001605 return AD->getClassInterface();
1606
1607 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001608}
1609
John McCalla8ae2222010-04-06 21:38:20 +00001610bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001611 if (!isCXXClassMember())
1612 return false;
1613
John McCalla8ae2222010-04-06 21:38:20 +00001614 const NamedDecl *D = this;
1615 if (isa<UsingShadowDecl>(D))
1616 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1617
John McCall5e77d762013-04-16 07:28:30 +00001618 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001619 return true;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001620 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
Alp Tokera2794f92014-01-22 07:29:52 +00001621 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001622 return false;
1623}
1624
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001625//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001626// DeclaratorDecl Implementation
1627//===----------------------------------------------------------------------===//
1628
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001629template <typename DeclT>
1630static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1631 if (decl->getNumTemplateParameterLists() > 0)
1632 return decl->getTemplateParameterList(0)->getTemplateLoc();
1633 else
1634 return decl->getInnerLocStart();
1635}
1636
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001637SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001638 TypeSourceInfo *TSI = getTypeSourceInfo();
1639 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001640 return SourceLocation();
1641}
1642
Douglas Gregor14454802011-02-25 02:25:35 +00001643void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1644 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001645 // Make sure the extended decl info is allocated.
1646 if (!hasExtInfo()) {
1647 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001648 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
John McCall3e11ebe2010-03-15 10:12:16 +00001649 // Allocate external info struct.
1650 DeclInfo = new (getASTContext()) ExtInfo;
1651 // Restore savedTInfo into (extended) decl info.
1652 getExtInfo()->TInfo = savedTInfo;
1653 }
1654 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001655 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001656 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001657 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001658 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001659 if (getExtInfo()->NumTemplParamLists == 0) {
1660 // Save type source info pointer.
1661 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1662 // Deallocate the extended decl info.
1663 getASTContext().Deallocate(getExtInfo());
1664 // Restore savedTInfo into (non-extended) decl info.
1665 DeclInfo = savedTInfo;
1666 }
1667 else
1668 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001669 }
1670 }
1671}
1672
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001673void DeclaratorDecl::setTemplateParameterListsInfo(
1674 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1675 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00001676 // Make sure the extended decl info is allocated.
1677 if (!hasExtInfo()) {
1678 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001679 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
Abramo Bagnara60804e12011-03-18 15:16:37 +00001680 // Allocate external info struct.
1681 DeclInfo = new (getASTContext()) ExtInfo;
1682 // Restore savedTInfo into (extended) decl info.
1683 getExtInfo()->TInfo = savedTInfo;
1684 }
1685 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001686 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00001687}
1688
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001689SourceLocation DeclaratorDecl::getOuterLocStart() const {
1690 return getTemplateOrInnerLocStart(this);
1691}
1692
Abramo Bagnaraea947882011-03-08 16:41:52 +00001693namespace {
1694
1695// Helper function: returns true if QT is or contains a type
1696// having a postfix component.
1697bool typeIsPostfix(clang::QualType QT) {
1698 while (true) {
1699 const Type* T = QT.getTypePtr();
1700 switch (T->getTypeClass()) {
1701 default:
1702 return false;
1703 case Type::Pointer:
1704 QT = cast<PointerType>(T)->getPointeeType();
1705 break;
1706 case Type::BlockPointer:
1707 QT = cast<BlockPointerType>(T)->getPointeeType();
1708 break;
1709 case Type::MemberPointer:
1710 QT = cast<MemberPointerType>(T)->getPointeeType();
1711 break;
1712 case Type::LValueReference:
1713 case Type::RValueReference:
1714 QT = cast<ReferenceType>(T)->getPointeeType();
1715 break;
1716 case Type::PackExpansion:
1717 QT = cast<PackExpansionType>(T)->getPattern();
1718 break;
1719 case Type::Paren:
1720 case Type::ConstantArray:
1721 case Type::DependentSizedArray:
1722 case Type::IncompleteArray:
1723 case Type::VariableArray:
1724 case Type::FunctionProto:
1725 case Type::FunctionNoProto:
1726 return true;
1727 }
1728 }
1729}
1730
1731} // namespace
1732
1733SourceRange DeclaratorDecl::getSourceRange() const {
1734 SourceLocation RangeEnd = getLocation();
1735 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001736 // If the declaration has no name or the type extends past the name take the
1737 // end location of the type.
1738 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001739 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1740 }
1741 return SourceRange(getOuterLocStart(), RangeEnd);
1742}
1743
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001744void QualifierInfo::setTemplateParameterListsInfo(
1745 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001746 // Free previous template parameters (if any).
1747 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001748 Context.Deallocate(TemplParamLists);
Craig Topper36250ad2014-05-12 05:36:57 +00001749 TemplParamLists = nullptr;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001750 NumTemplParamLists = 0;
1751 }
1752 // Set info on matched template parameter lists (if any).
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001753 if (!TPLists.empty()) {
1754 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1755 NumTemplParamLists = TPLists.size();
1756 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001757 }
1758}
1759
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001760//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001761// VarDecl Implementation
1762//===----------------------------------------------------------------------===//
1763
Sebastian Redl833ef452010-01-26 22:01:41 +00001764const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1765 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001766 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001767 case SC_Auto: return "auto";
1768 case SC_Extern: return "extern";
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001769 case SC_PrivateExtern: return "__private_extern__";
1770 case SC_Register: return "register";
1771 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001772 }
1773
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001774 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001775}
1776
Richard Smith053f6c62014-05-16 23:01:30 +00001777VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1778 SourceLocation StartLoc, SourceLocation IdLoc,
1779 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1780 StorageClass SC)
1781 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1782 redeclarable_base(C), Init() {
Benjamin Kramera939c232014-03-15 18:54:13 +00001783 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1784 "VarDeclBitfields too large!");
1785 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1786 "ParmVarDeclBitfields too large!");
David Majnemerfa7bc782015-05-19 00:57:16 +00001787 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1788 "NonParmVarDeclBitfields too large!");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001789 AllBits = 0;
1790 VarDeclBits.SClass = SC;
1791 // Everything else is implicitly initialized to false.
1792}
1793
Abramo Bagnaradff19302011-03-08 08:55:46 +00001794VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1795 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001796 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001797 StorageClass S) {
Richard Smith053f6c62014-05-16 23:01:30 +00001798 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001799}
1800
Douglas Gregor72172e92012-01-05 21:55:30 +00001801VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00001802 return new (C, ID)
1803 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1804 QualType(), nullptr, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001805}
1806
Douglas Gregorbf62d642010-12-06 18:36:25 +00001807void VarDecl::setStorageClass(StorageClass SC) {
1808 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001809 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001810}
1811
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001812VarDecl::TLSKind VarDecl::getTLSKind() const {
1813 switch (VarDeclBits.TSCSpec) {
1814 case TSCS_unspecified:
Samuel Antaof8b50122015-07-13 22:54:53 +00001815 if (!hasAttr<ThreadAttr>() &&
1816 !(getASTContext().getLangOpts().OpenMPUseTLS &&
1817 getASTContext().getTargetInfo().isTLSSupported() &&
1818 hasAttr<OMPThreadPrivateDeclAttr>()))
David Majnemer1b5baff2015-05-14 05:19:23 +00001819 return TLS_None;
Samuel Antaof8b50122015-07-13 22:54:53 +00001820 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1821 LangOptions::MSVC2015)) ||
1822 hasAttr<OMPThreadPrivateDeclAttr>())
David Majnemer1b5baff2015-05-14 05:19:23 +00001823 ? TLS_Dynamic
1824 : TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001825 case TSCS___thread: // Fall through.
1826 case TSCS__Thread_local:
Samuel Antaof8b50122015-07-13 22:54:53 +00001827 return TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001828 case TSCS_thread_local:
1829 return TLS_Dynamic;
1830 }
1831 llvm_unreachable("Unknown thread storage class specifier!");
1832}
1833
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001834SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001835 if (const Expr *Init = getInit()) {
1836 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001837 // If Init is implicit, ignore its source range and fallback on
1838 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1839 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001840 return SourceRange(getOuterLocStart(), InitEnd);
1841 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001842 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001843}
1844
Rafael Espindola88510672013-01-04 21:18:45 +00001845template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001846static LanguageLinkage getDeclLanguageLinkage(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001847 // C++ [dcl.link]p1: All function types, function names with external linkage,
1848 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001849 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001850 return NoLanguageLinkage;
1851
1852 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001853 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001854 ASTContext &Context = D.getASTContext();
1855 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001856 return CLanguageLinkage;
1857
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001858 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1859 // language linkage of the names of class members and the function type of
1860 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001861 const DeclContext *DC = D.getDeclContext();
1862 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001863 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001864
1865 // If the first decl is in an extern "C" context, any other redeclaration
1866 // will have C language linkage. If the first one is not in an extern "C"
1867 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00001868 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00001869 return CLanguageLinkage;
1870 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001871}
1872
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001873template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001874static bool isDeclExternC(const T &D) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001875 // Since the context is ignored for class members, they can only have C++
1876 // language linkage or no language linkage.
1877 const DeclContext *DC = D.getDeclContext();
1878 if (DC->isRecord()) {
1879 assert(D.getASTContext().getLangOpts().CPlusPlus);
1880 return false;
1881 }
1882
1883 return D.getLanguageLinkage() == CLanguageLinkage;
1884}
1885
Rafael Espindolaf4187652013-02-14 01:18:37 +00001886LanguageLinkage VarDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00001887 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001888}
1889
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001890bool VarDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00001891 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001892}
1893
Rafael Espindola593537a2013-05-05 20:15:21 +00001894bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001895 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001896}
1897
1898bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001899 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001900}
1901
Rafael Espindola8db352d2013-10-17 15:37:26 +00001902VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00001903
Nico Weber7f5015a2015-04-15 21:53:00 +00001904VarDecl::DefinitionKind
1905VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001906 // C++ [basic.def]p2:
1907 // A declaration is a definition unless [...] it contains the 'extern'
1908 // specifier or a linkage-specification and neither an initializer [...],
1909 // it declares a static data member in a class declaration [...].
Richard Smith8809a0c2013-09-27 20:14:12 +00001910 // C++1y [temp.expl.spec]p15:
1911 // An explicit specialization of a static data member or an explicit
1912 // specialization of a static data member template is a definition if the
1913 // declaration includes an initializer; otherwise, it is a declaration.
1914 //
1915 // FIXME: How do you declare (but not define) a partial specialization of
1916 // a static data member template outside the containing class?
Sebastian Redl35351a92010-01-31 22:27:38 +00001917 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00001918 if (isOutOfLine() &&
1919 (hasInit() ||
1920 // If the first declaration is out-of-line, this may be an
1921 // instantiation of an out-of-line partial specialization of a variable
1922 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00001923 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00001924 ? getTemplateSpecializationKind() == TSK_Undeclared
1925 : getTemplateSpecializationKind() !=
1926 TSK_ExplicitSpecialization) ||
1927 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00001928 return Definition;
1929 else
1930 return DeclarationOnly;
1931 }
1932 // C99 6.7p5:
1933 // A definition of an identifier is a declaration for that identifier that
1934 // [...] causes storage to be reserved for that object.
1935 // Note: that applies for all non-file-scope objects.
1936 // C99 6.9.2p1:
1937 // If the declaration of an identifier for an object has file scope and an
1938 // initializer, the declaration is an external definition for the identifier
1939 if (hasInit())
1940 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00001941
David Majnemerdd0bed12015-05-14 05:19:20 +00001942 if (hasAttr<AliasAttr>())
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001943 return Definition;
1944
David Majnemerdd0bed12015-05-14 05:19:20 +00001945 if (const auto *SAA = getAttr<SelectAnyAttr>())
1946 if (!SAA->isInherited())
1947 return Definition;
1948
Richard Smith8809a0c2013-09-27 20:14:12 +00001949 // A variable template specialization (other than a static data member
1950 // template or an explicit specialization) is a declaration until we
1951 // instantiate its initializer.
1952 if (isa<VarTemplateSpecializationDecl>(this) &&
1953 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1954 return DeclarationOnly;
1955
Nico Weber608e7682015-04-15 23:04:24 +00001956 if (hasExternalStorage())
Sebastian Redl35351a92010-01-31 22:27:38 +00001957 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00001958
Rafael Espindolabff59562013-04-25 12:11:36 +00001959 // [dcl.link] p7:
1960 // A declaration directly contained in a linkage-specification is treated
1961 // as if it contains the extern specifier for the purpose of determining
1962 // the linkage of the declared name and whether it is a definition.
Nico Weber608e7682015-04-15 23:04:24 +00001963 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00001964 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00001965
Sebastian Redl35351a92010-01-31 22:27:38 +00001966 // C99 6.9.2p2:
1967 // A declaration of an object that has file scope without an initializer,
1968 // and without a storage class specifier or the scs 'static', constitutes
1969 // a tentative definition.
1970 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001971 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00001972 return TentativeDefinition;
1973
1974 // What's left is (in C, block-scope) declarations without initializers or
1975 // external storage. These are definitions.
1976 return Definition;
1977}
1978
Sebastian Redl35351a92010-01-31 22:27:38 +00001979VarDecl *VarDecl::getActingDefinition() {
1980 DefinitionKind Kind = isThisDeclarationADefinition();
1981 if (Kind != TentativeDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00001982 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00001983
Craig Topper36250ad2014-05-12 05:36:57 +00001984 VarDecl *LastTentative = nullptr;
Rafael Espindola8db352d2013-10-17 15:37:26 +00001985 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001986 for (auto I : First->redecls()) {
1987 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00001988 if (Kind == Definition)
Craig Topper36250ad2014-05-12 05:36:57 +00001989 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00001990 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00001991 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00001992 }
1993 return LastTentative;
1994}
1995
Daniel Dunbar9d355812012-03-09 01:51:51 +00001996VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001997 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001998 for (auto I : First->redecls()) {
1999 if (I->isThisDeclarationADefinition(C) == Definition)
2000 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002001 }
Craig Topper36250ad2014-05-12 05:36:57 +00002002 return nullptr;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002003}
2004
Daniel Dunbar9d355812012-03-09 01:51:51 +00002005VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00002006 DefinitionKind Kind = DeclarationOnly;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002007
Rafael Espindola8db352d2013-10-17 15:37:26 +00002008 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002009 for (auto I : First->redecls()) {
2010 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00002011 if (Kind == Definition)
2012 break;
2013 }
John McCall37bb6c92010-10-29 22:22:43 +00002014
2015 return Kind;
2016}
2017
Sebastian Redl5ca79842010-02-01 20:16:42 +00002018const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002019 for (auto I : redecls()) {
2020 if (auto Expr = I->getInit()) {
2021 D = I;
2022 return Expr;
2023 }
Sebastian Redl833ef452010-01-26 22:01:41 +00002024 }
Craig Topper36250ad2014-05-12 05:36:57 +00002025 return nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002026}
2027
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002028bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002029 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002030 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00002031
2032 if (!isStaticDataMember())
2033 return false;
2034
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002035 // If this static data member was instantiated from a static data member of
2036 // a class template, check whether that static data member was defined
2037 // out-of-line.
2038 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2039 return VD->isOutOfLine();
2040
2041 return false;
2042}
2043
Douglas Gregor1d957a32009-10-27 18:42:08 +00002044VarDecl *VarDecl::getOutOfLineDefinition() {
2045 if (!isStaticDataMember())
Craig Topper36250ad2014-05-12 05:36:57 +00002046 return nullptr;
2047
Aaron Ballman86c93902014-03-06 23:45:36 +00002048 for (auto RD : redecls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002049 if (RD->getLexicalDeclContext()->isFileContext())
Aaron Ballman86c93902014-03-06 23:45:36 +00002050 return RD;
Douglas Gregor1d957a32009-10-27 18:42:08 +00002051 }
Craig Topper36250ad2014-05-12 05:36:57 +00002052
2053 return nullptr;
Douglas Gregor1d957a32009-10-27 18:42:08 +00002054}
2055
Douglas Gregord5058122010-02-11 01:19:42 +00002056void VarDecl::setInit(Expr *I) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002057 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
Sebastian Redl833ef452010-01-26 22:01:41 +00002058 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00002059 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00002060 }
2061
2062 Init = I;
2063}
2064
Daniel Dunbar9d355812012-03-09 01:51:51 +00002065bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002066 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00002067
Richard Smith35ecb362012-03-02 04:14:40 +00002068 if (!Lang.CPlusPlus)
2069 return false;
2070
2071 // In C++11, any variable of reference type can be used in a constant
2072 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002073 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00002074 return true;
2075
2076 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00002077 // not require the variable to be non-volatile, but we consider this to be a
2078 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00002079 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00002080 return false;
2081
2082 // In C++, const, non-volatile variables of integral or enumeration types
2083 // can be used in constant expressions.
2084 if (getType()->isIntegralOrEnumerationType())
2085 return true;
2086
Richard Smith35ecb362012-03-02 04:14:40 +00002087 // Additionally, in C++11, non-volatile constexpr variables can be used in
2088 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002089 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00002090}
2091
Richard Smithd0b4dd62011-12-19 06:19:21 +00002092/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2093/// form, which contains extra information on the evaluated value of the
2094/// initializer.
2095EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002096 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002097 if (!Eval) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002098 auto *S = Init.get<Stmt *>();
Manuel Klimeka7328992013-06-03 13:51:33 +00002099 // Note: EvaluatedStmt contains an APValue, which usually holds
2100 // resources not allocated from the ASTContext. We need to do some
2101 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2102 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002103 Eval = new (getASTContext()) EvaluatedStmt;
2104 Eval->Value = S;
2105 Init = Eval;
2106 }
2107 return Eval;
2108}
2109
Richard Smithdafff942012-01-14 04:30:29 +00002110APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002111 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00002112 return evaluateValue(Notes);
2113}
2114
Manuel Klimeka7328992013-06-03 13:51:33 +00002115namespace {
2116// Destroy an APValue that was allocated in an ASTContext.
2117void DestroyAPValue(void* UntypedValue) {
2118 static_cast<APValue*>(UntypedValue)->~APValue();
2119}
2120} // namespace
2121
Richard Smithdafff942012-01-14 04:30:29 +00002122APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002123 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002124 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2125
2126 // We only produce notes indicating why an initializer is non-constant the
2127 // first time it is evaluated. FIXME: The notes won't always be emitted the
2128 // first time we try evaluation, so might not be produced at all.
2129 if (Eval->WasEvaluated)
Craig Topper36250ad2014-05-12 05:36:57 +00002130 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002131
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002132 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002133 assert(!Init->isValueDependent());
2134
2135 if (Eval->IsEvaluating) {
2136 // FIXME: Produce a diagnostic for self-initialization.
2137 Eval->CheckedICE = true;
2138 Eval->IsICE = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002139 return nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002140 }
2141
2142 Eval->IsEvaluating = true;
2143
2144 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2145 this, Notes);
2146
Manuel Klimeka7328992013-06-03 13:51:33 +00002147 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2148 // or that it's empty (so that there's nothing to clean up) if evaluation
2149 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002150 if (!Result)
2151 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00002152 else if (Eval->Evaluated.needsCleanup())
2153 getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002154
2155 Eval->IsEvaluating = false;
2156 Eval->WasEvaluated = true;
2157
2158 // In C++11, we have determined whether the initializer was a constant
2159 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002160 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002161 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00002162 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002163 }
2164
Craig Topper36250ad2014-05-12 05:36:57 +00002165 return Result ? &Eval->Evaluated : nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002166}
2167
2168bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00002169 // Initializers of weak variables are never ICEs.
2170 if (isWeak())
2171 return false;
2172
Richard Smithd0b4dd62011-12-19 06:19:21 +00002173 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2174 if (Eval->CheckedICE)
2175 // We have already checked whether this subexpression is an
2176 // integral constant expression.
2177 return Eval->IsICE;
2178
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002179 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002180 assert(!Init->isValueDependent());
2181
2182 // In C++11, evaluate the initializer to check whether it's a constant
2183 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002184 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002185 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002186 evaluateValue(Notes);
2187 return Eval->IsICE;
2188 }
2189
2190 // It's an ICE whether or not the definition we found is
2191 // out-of-line. See DR 721 and the discussion in Clang PR
2192 // 6206 for details.
2193
2194 if (Eval->CheckingICE)
2195 return false;
2196 Eval->CheckingICE = true;
2197
2198 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2199 Eval->CheckingICE = false;
2200 Eval->CheckedICE = true;
2201 return Eval->IsICE;
2202}
2203
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002204VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002205 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002206 return cast<VarDecl>(MSI->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002207
2208 return nullptr;
Douglas Gregor86d142a2009-10-08 07:24:58 +00002209}
2210
Douglas Gregor3c74d412009-10-14 20:14:33 +00002211TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002212 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002213 return Spec->getSpecializationKind();
2214
Sebastian Redl35351a92010-01-31 22:27:38 +00002215 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002216 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002217
Douglas Gregor86d142a2009-10-08 07:24:58 +00002218 return TSK_Undeclared;
2219}
2220
Richard Smith8809a0c2013-09-27 20:14:12 +00002221SourceLocation VarDecl::getPointOfInstantiation() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002222 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Richard Smith8809a0c2013-09-27 20:14:12 +00002223 return Spec->getPointOfInstantiation();
2224
2225 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2226 return MSI->getPointOfInstantiation();
2227
2228 return SourceLocation();
2229}
2230
Larisse Voufo39a1e502013-08-06 01:03:05 +00002231VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2232 return getASTContext().getTemplateOrSpecializationInfo(this)
2233 .dyn_cast<VarTemplateDecl *>();
2234}
2235
2236void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2237 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2238}
2239
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002240MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002241 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002242 // FIXME: Remove ?
2243 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2244 return getASTContext().getTemplateOrSpecializationInfo(this)
2245 .dyn_cast<MemberSpecializationInfo *>();
Craig Topper36250ad2014-05-12 05:36:57 +00002246 return nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002247}
2248
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002249void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2250 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002251 assert((isa<VarTemplateSpecializationDecl>(this) ||
2252 getMemberSpecializationInfo()) &&
2253 "not a variable or static data member template specialization");
2254
Larisse Voufo39a1e502013-08-06 01:03:05 +00002255 if (VarTemplateSpecializationDecl *Spec =
2256 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2257 Spec->setSpecializationKind(TSK);
2258 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2259 Spec->getPointOfInstantiation().isInvalid())
2260 Spec->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002261 }
2262
2263 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2264 MSI->setTemplateSpecializationKind(TSK);
2265 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2266 MSI->getPointOfInstantiation().isInvalid())
2267 MSI->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002268 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002269}
2270
2271void
2272VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2273 TemplateSpecializationKind TSK) {
2274 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2275 "Previous template or instantiation?");
2276 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002277}
2278
Sebastian Redl833ef452010-01-26 22:01:41 +00002279//===----------------------------------------------------------------------===//
2280// ParmVarDecl Implementation
2281//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002282
Sebastian Redl833ef452010-01-26 22:01:41 +00002283ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002284 SourceLocation StartLoc,
2285 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002286 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002287 StorageClass S, Expr *DefArg) {
Richard Smith053f6c62014-05-16 23:01:30 +00002288 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smithf7981722013-11-22 09:01:48 +00002289 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002290}
2291
Reid Kleckner8a365022013-06-24 17:51:48 +00002292QualType ParmVarDecl::getOriginalType() const {
2293 TypeSourceInfo *TSI = getTypeSourceInfo();
2294 QualType T = TSI ? TSI->getType() : getType();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002295 if (const auto *DT = dyn_cast<DecayedType>(T))
Reid Kleckner8a365022013-06-24 17:51:48 +00002296 return DT->getOriginalType();
2297 return T;
2298}
2299
Douglas Gregor72172e92012-01-05 21:55:30 +00002300ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00002301 return new (C, ID)
2302 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2303 nullptr, QualType(), nullptr, SC_None, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00002304}
2305
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002306SourceRange ParmVarDecl::getSourceRange() const {
2307 if (!hasInheritedDefaultArg()) {
2308 SourceRange ArgRange = getDefaultArgRange();
2309 if (ArgRange.isValid())
2310 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2311 }
2312
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002313 // DeclaratorDecl considers the range of postfix types as overlapping with the
2314 // declaration name, but this is not the case with parameters in ObjC methods.
2315 if (isa<ObjCMethodDecl>(getDeclContext()))
2316 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2317
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002318 return DeclaratorDecl::getSourceRange();
2319}
2320
Sebastian Redl833ef452010-01-26 22:01:41 +00002321Expr *ParmVarDecl::getDefaultArg() {
2322 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2323 assert(!hasUninstantiatedDefaultArg() &&
2324 "Default argument is not yet instantiated!");
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002325
Sebastian Redl833ef452010-01-26 22:01:41 +00002326 Expr *Arg = getInit();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002327 if (auto *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002328 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002329
Sebastian Redl833ef452010-01-26 22:01:41 +00002330 return Arg;
2331}
2332
Sebastian Redl833ef452010-01-26 22:01:41 +00002333SourceRange ParmVarDecl::getDefaultArgRange() const {
2334 if (const Expr *E = getInit())
2335 return E->getSourceRange();
2336
2337 if (hasUninstantiatedDefaultArg())
2338 return getUninstantiatedDefaultArg()->getSourceRange();
2339
2340 return SourceRange();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002341}
2342
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00002343bool ParmVarDecl::isParameterPack() const {
2344 return isa<PackExpansionType>(getType());
2345}
2346
Ted Kremenek540017e2011-10-06 05:00:56 +00002347void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2348 getASTContext().setParameterIndex(this, parameterIndex);
2349 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2350}
2351
2352unsigned ParmVarDecl::getParameterIndexLarge() const {
2353 return getASTContext().getParameterIndex(this);
2354}
2355
Nuno Lopes394ec982008-12-17 23:39:55 +00002356//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002357// FunctionDecl Implementation
2358//===----------------------------------------------------------------------===//
2359
Benjamin Kramer9170e912013-02-22 15:46:01 +00002360void FunctionDecl::getNameForDiagnostic(
2361 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2362 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002363 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2364 if (TemplateArgs)
Benjamin Kramer9170e912013-02-22 15:46:01 +00002365 TemplateSpecializationType::PrintTemplateArgumentList(
2366 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002367}
2368
Ted Kremenek186a0742010-04-29 16:49:01 +00002369bool FunctionDecl::isVariadic() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002370 if (const auto *FT = getType()->getAs<FunctionProtoType>())
Ted Kremenek186a0742010-04-29 16:49:01 +00002371 return FT->isVariadic();
2372 return false;
2373}
2374
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002375bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002376 for (auto I : redecls()) {
Francois Pichet1c229c02011-04-22 22:18:13 +00002377 if (I->Body || I->IsLateTemplateParsed) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002378 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002379 return true;
2380 }
2381 }
2382
2383 return false;
2384}
2385
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002386bool FunctionDecl::hasTrivialBody() const
2387{
2388 Stmt *S = getBody();
2389 if (!S) {
2390 // Since we don't have a body for this function, we don't know if it's
2391 // trivial or not.
2392 return false;
2393 }
2394
2395 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2396 return true;
2397 return false;
2398}
2399
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002400bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002401 for (auto I : redecls()) {
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002402 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
2403 I->hasAttr<AliasAttr>()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002404 Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002405 return true;
2406 }
2407 }
2408
2409 return false;
2410}
2411
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002412Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002413 if (!hasBody(Definition))
Craig Topper36250ad2014-05-12 05:36:57 +00002414 return nullptr;
Rafael Espindola44503012013-10-19 01:37:17 +00002415
2416 if (Definition->Body)
2417 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002418
Craig Topper36250ad2014-05-12 05:36:57 +00002419 return nullptr;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002420}
2421
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002422void FunctionDecl::setBody(Stmt *B) {
2423 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002424 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002425 EndRangeLoc = B->getLocEnd();
2426}
2427
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002428void FunctionDecl::setPure(bool P) {
2429 IsPure = P;
2430 if (P)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002431 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002432 Parent->markedVirtualFunctionPure();
2433}
2434
Richard Smith8d0dc312013-07-21 23:12:18 +00002435template<std::size_t Len>
2436static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2437 IdentifierInfo *II = ND->getIdentifier();
2438 return II && II->isStr(Str);
2439}
2440
Douglas Gregor16618f22009-09-12 00:17:51 +00002441bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002442 const TranslationUnitDecl *tunit =
2443 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2444 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002445 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002446 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002447}
2448
David Majnemerc729b0b2013-09-16 22:44:20 +00002449bool FunctionDecl::isMSVCRTEntryPoint() const {
2450 const TranslationUnitDecl *TUnit =
2451 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2452 if (!TUnit)
2453 return false;
2454
2455 // Even though we aren't really targeting MSVCRT if we are freestanding,
2456 // semantic analysis for these functions remains the same.
2457
2458 // MSVCRT entry points only exist on MSVCRT targets.
2459 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2460 return false;
2461
2462 // Nameless functions like constructors cannot be entry points.
2463 if (!getIdentifier())
2464 return false;
2465
2466 return llvm::StringSwitch<bool>(getName())
2467 .Cases("main", // an ANSI console app
2468 "wmain", // a Unicode console App
2469 "WinMain", // an ANSI GUI app
2470 "wWinMain", // a Unicode GUI app
2471 "DllMain", // a DLL
2472 true)
2473 .Default(false);
2474}
2475
John McCall53ffd372011-05-15 17:49:20 +00002476bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2477 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2478 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2479 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2480 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2481 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2482
Richard Smithf6004412014-01-19 23:25:37 +00002483 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2484 return false;
John McCall53ffd372011-05-15 17:49:20 +00002485
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002486 const auto *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002487 if (proto->getNumParams() != 2 || proto->isVariadic())
2488 return false;
John McCall53ffd372011-05-15 17:49:20 +00002489
2490 ASTContext &Context =
2491 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2492 ->getASTContext();
2493
2494 // The result type and first argument type are constant across all
2495 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002496 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002497}
2498
Richard Smith8d0dc312013-07-21 23:12:18 +00002499bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2500 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2501 return false;
2502 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2503 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2504 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2505 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2506 return false;
2507
2508 if (isa<CXXRecordDecl>(getDeclContext()))
2509 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002510
2511 // This can only fail for an invalid 'operator new' declaration.
2512 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2513 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002514
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002515 const auto *FPT = getType()->castAs<FunctionProtoType>();
Nick Lewycky6fb99b92014-06-07 00:43:57 +00002516 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 2 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002517 return false;
2518
2519 // If this is a single-parameter function, it must be a replaceable global
2520 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002521 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002522 return true;
2523
2524 // Otherwise, we're looking for a second parameter whose type is
Richard Smith1cdec012013-09-29 04:40:38 +00002525 // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
Alp Toker9cacbab2014-01-20 20:26:09 +00002526 QualType Ty = FPT->getParamType(1);
Richard Smith1cdec012013-09-29 04:40:38 +00002527 ASTContext &Ctx = getASTContext();
Richard Smithb47c36f2013-11-05 09:12:18 +00002528 if (Ctx.getLangOpts().SizedDeallocation &&
2529 Ctx.hasSameType(Ty, Ctx.getSizeType()))
Richard Smith1cdec012013-09-29 04:40:38 +00002530 return true;
Richard Smith8d0dc312013-07-21 23:12:18 +00002531 if (!Ty->isReferenceType())
2532 return false;
2533 Ty = Ty->getPointeeType();
2534 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2535 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002536 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Richard Trieuc771d5d2014-05-28 02:16:01 +00002537 return RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace();
Richard Smith8d0dc312013-07-21 23:12:18 +00002538}
2539
Rafael Espindolaf4187652013-02-14 01:18:37 +00002540LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00002541 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002542}
2543
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002544bool FunctionDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00002545 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002546}
2547
Rafael Espindola593537a2013-05-05 20:15:21 +00002548bool FunctionDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002549 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002550}
2551
2552bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002553 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002554}
2555
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002556bool FunctionDecl::isGlobal() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002557 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002558 return Method->isStatic();
2559
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002560 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002561 return false;
2562
Mike Stump11289f42009-09-09 15:08:12 +00002563 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002564 DC->isNamespace();
2565 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002566 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002567 if (!Namespace->getDeclName())
2568 return false;
2569 break;
2570 }
2571 }
2572
2573 return true;
2574}
2575
Richard Smith10876ef2013-01-17 01:30:42 +00002576bool FunctionDecl::isNoReturn() const {
2577 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
Richard Smithdebc59d2013-01-30 05:45:05 +00002578 hasAttr<C11NoReturnAttr>() ||
Richard Smith10876ef2013-01-17 01:30:42 +00002579 getType()->getAs<FunctionType>()->getNoReturnAttr();
2580}
2581
Sebastian Redl833ef452010-01-26 22:01:41 +00002582void
2583FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002584 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002585
2586 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2587 FunctionTemplateDecl *PrevFunTmpl
Craig Topper36250ad2014-05-12 05:36:57 +00002588 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002589 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00002590 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002591 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002592
Axel Naumannfbc7b982011-11-08 18:21:06 +00002593 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002594 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002595}
2596
Rafael Espindola8db352d2013-10-17 15:37:26 +00002597FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002598
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002599/// \brief Returns a value indicating whether this function
2600/// corresponds to a builtin function.
2601///
2602/// The function corresponds to a built-in function if it is
2603/// declared at translation scope or within an extern "C" block and
2604/// its name matches with the name of a builtin. The returned value
2605/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002606/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002607/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002608unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002609 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002610 return 0;
2611
2612 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002613 if (!BuiltinID)
2614 return 0;
2615
2616 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00002617 if (Context.getLangOpts().CPlusPlus) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002618 const auto *LinkageDecl =
2619 dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
Warren Hunt445d83e2013-11-01 23:46:51 +00002620 // In C++, the first declaration of a builtin is always inside an implicit
2621 // extern "C".
2622 // FIXME: A recognised library function may not be directly in an extern "C"
2623 // declaration, for instance "extern "C" { namespace std { decl } }".
David Majnemerba3e5ec2015-03-13 18:26:17 +00002624 if (!LinkageDecl) {
2625 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
2626 Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2627 isInStdNamespace())
2628 return Builtin::BI__GetExceptionInfo;
2629 return 0;
2630 }
2631 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
Warren Hunt445d83e2013-11-01 23:46:51 +00002632 return 0;
2633 }
2634
2635 // If the function is marked "overloadable", it has a different mangled name
2636 // and is not the C library function.
Aaron Ballman9ead1242013-12-19 02:39:40 +00002637 if (hasAttr<OverloadableAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00002638 return 0;
2639
Douglas Gregore711f702009-02-14 18:57:46 +00002640 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2641 return BuiltinID;
2642
2643 // This function has the name of a known C library
2644 // function. Determine whether it actually refers to the C library
2645 // function or whether it just has the same name.
2646
Douglas Gregora908e7f2009-02-17 03:23:10 +00002647 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002648 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002649 return 0;
2650
Warren Hunt445d83e2013-11-01 23:46:51 +00002651 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002652}
2653
2654
Chris Lattner47c0d002009-04-25 06:03:53 +00002655/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002656/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002657/// after it has been created.
2658unsigned FunctionDecl::getNumParams() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002659 const auto *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002660 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002661}
2662
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002663void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002664 ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00002665 assert(!ParamInfo && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002666 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002667
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002668 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002669 if (!NewParamInfo.empty()) {
2670 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2671 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002672 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002673}
Chris Lattner41943152007-01-25 04:52:46 +00002674
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002675void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
James Molloy6f8780b2012-02-29 10:24:19 +00002676 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2677
2678 if (!NewDecls.empty()) {
2679 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2680 std::copy(NewDecls.begin(), NewDecls.end(), A);
Craig Topper5fc8fc22014-08-27 06:28:36 +00002681 DeclsInPrototypeScope = llvm::makeArrayRef(A, NewDecls.size());
Serge Pavlova8261472014-06-25 17:09:41 +00002682 // Move declarations introduced in prototype to the function context.
2683 for (auto I : NewDecls) {
2684 DeclContext *DC = I->getDeclContext();
2685 // Forward-declared reference to an enumeration is not added to
2686 // declaration scope, so skip declaration that is absent from its
2687 // declaration contexts.
2688 if (DC->containsDecl(I)) {
2689 DC->removeDecl(I);
2690 I->setDeclContext(this);
2691 addDecl(I);
2692 }
2693 }
James Molloy6f8780b2012-02-29 10:24:19 +00002694 }
2695}
2696
Chris Lattner58258242008-04-10 02:22:51 +00002697/// getMinRequiredArguments - Returns the minimum number of arguments
2698/// needed to call this function. This may be fewer than the number of
2699/// function parameters, if some of the parameters have default
Richard Smith91151782014-04-01 19:18:16 +00002700/// arguments (in C++) or are parameter packs (C++11).
Chris Lattner58258242008-04-10 02:22:51 +00002701unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002702 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002703 return getNumParams();
Chris Lattner58258242008-04-10 02:22:51 +00002704
Richard Smith91151782014-04-01 19:18:16 +00002705 unsigned NumRequiredArgs = 0;
2706 for (auto *Param : params())
2707 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2708 ++NumRequiredArgs;
Chris Lattner58258242008-04-10 02:22:51 +00002709 return NumRequiredArgs;
2710}
2711
David Majnemer54e3ba52014-04-02 23:17:29 +00002712/// \brief The combination of the extern and inline keywords under MSVC forces
2713/// the function to be required.
2714///
2715/// Note: This function assumes that we will only get called when isInlined()
2716/// would return true for this FunctionDecl.
2717bool FunctionDecl::isMSExternInline() const {
2718 assert(isInlined() && "expected to get called on an inlined function!");
2719
2720 const ASTContext &Context = getASTContext();
David Majnemer3f021502015-10-08 04:53:31 +00002721 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2722 !hasAttr<DLLExportAttr>())
David Majnemer54e3ba52014-04-02 23:17:29 +00002723 return false;
2724
David Majnemer73768702015-03-20 00:02:27 +00002725 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
2726 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002727 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002728 return true;
2729
2730 return false;
2731}
2732
2733static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
2734 if (Redecl->getStorageClass() != SC_Extern)
2735 return false;
2736
2737 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
2738 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002739 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002740 return false;
2741
2742 return true;
2743}
2744
Eli Friedman1b125c32012-02-07 03:50:18 +00002745static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2746 // Only consider file-scope declarations in this test.
2747 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2748 return false;
2749
2750 // Only consider explicit declarations; the presence of a builtin for a
2751 // libcall shouldn't affect whether a definition is externally visible.
2752 if (Redecl->isImplicit())
2753 return false;
2754
2755 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2756 return true; // Not an inline definition
2757
2758 return false;
2759}
2760
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002761/// \brief For a function declaration in C or C++, determine whether this
2762/// declaration causes the definition to be externally visible.
2763///
David Majnemer54e3ba52014-04-02 23:17:29 +00002764/// For instance, this determines if adding the current declaration to the set
Eli Friedman1b125c32012-02-07 03:50:18 +00002765/// of redeclarations of the given functions causes
2766/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002767bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2768 assert(!doesThisDeclarationHaveABody() &&
2769 "Must have a declaration without a body.");
2770
2771 ASTContext &Context = getASTContext();
2772
David Majnemer54e3ba52014-04-02 23:17:29 +00002773 if (Context.getLangOpts().MSVCCompat) {
2774 const FunctionDecl *Definition;
2775 if (hasBody(Definition) && Definition->isInlined() &&
2776 redeclForcesDefMSVC(this))
2777 return true;
2778 }
2779
David Blaikiebbafb8a2012-03-11 07:00:24 +00002780 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002781 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2782 // an externally visible definition.
2783 //
2784 // FIXME: What happens if gnu_inline gets added on after the first
2785 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002786 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002787 return false;
2788
2789 const FunctionDecl *Prev = this;
2790 bool FoundBody = false;
2791 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002792 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002793
2794 if (Prev->Body) {
2795 // If it's not the case that both 'inline' and 'extern' are
2796 // specified on the definition, then it is always externally visible.
2797 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002798 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002799 return false;
2800 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002801 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002802 return false;
2803 }
2804 }
2805 return FoundBody;
2806 }
2807
David Blaikiebbafb8a2012-03-11 07:00:24 +00002808 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002809 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002810
2811 // C99 6.7.4p6:
2812 // [...] If all of the file scope declarations for a function in a
2813 // translation unit include the inline function specifier without extern,
2814 // then the definition in that translation unit is an inline definition.
2815 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002816 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002817 const FunctionDecl *Prev = this;
2818 bool FoundBody = false;
2819 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002820 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002821 if (RedeclForcesDefC99(Prev))
2822 return false;
2823 }
2824 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002825}
2826
Alp Tokerd0787eb2014-07-02 01:47:15 +00002827SourceRange FunctionDecl::getReturnTypeSourceRange() const {
2828 const TypeSourceInfo *TSI = getTypeSourceInfo();
2829 if (!TSI)
2830 return SourceRange();
Alp Tokerf5b10792014-07-02 12:55:58 +00002831 FunctionTypeLoc FTL =
2832 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
2833 if (!FTL)
Alp Tokerd0787eb2014-07-02 01:47:15 +00002834 return SourceRange();
2835
Alp Tokerf5b10792014-07-02 12:55:58 +00002836 // Skip self-referential return types.
2837 const SourceManager &SM = getASTContext().getSourceManager();
2838 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
2839 SourceLocation Boundary = getNameInfo().getLocStart();
2840 if (RTRange.isInvalid() || Boundary.isInvalid() ||
2841 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
2842 return SourceRange();
Alp Tokerd0787eb2014-07-02 01:47:15 +00002843
Alp Tokerf5b10792014-07-02 12:55:58 +00002844 return RTRange;
Alp Tokerd0787eb2014-07-02 01:47:15 +00002845}
2846
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002847bool FunctionDecl::hasUnusedResultAttr() const {
2848 QualType RetType = getReturnType();
2849 if (RetType->isRecordType()) {
2850 const CXXRecordDecl *Ret = RetType->getAsCXXRecordDecl();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002851 const auto *MD = dyn_cast<CXXMethodDecl>(this);
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002852 if (Ret && Ret->hasAttr<WarnUnusedResultAttr>() &&
2853 !(MD && MD->getCorrespondingMethodInClass(Ret, true)))
2854 return true;
2855 }
2856 return hasAttr<WarnUnusedResultAttr>();
2857}
2858
Richard Smithf3814ad2013-01-25 00:08:28 +00002859/// \brief For an inline function definition in C, or for a gnu_inline function
2860/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002861///
2862/// Inline function definitions are always available for inlining optimizations.
2863/// However, depending on the language dialect, declaration specifiers, and
2864/// attributes, the definition of an inline function may or may not be
2865/// "externally" visible to other translation units in the program.
2866///
2867/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00002868/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00002869/// inline definition becomes externally visible (C99 6.7.4p6).
2870///
2871/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2872/// definition, we use the GNU semantics for inline, which are nearly the
2873/// opposite of C99 semantics. In particular, "inline" by itself will create
2874/// an externally visible symbol, but "extern inline" will not create an
2875/// externally visible symbol.
2876bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002877 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002878 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00002879 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00002880
David Blaikiebbafb8a2012-03-11 07:00:24 +00002881 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002882 // Note: If you change the logic here, please change
2883 // doesDeclarationForceExternallyVisibleDefinition as well.
2884 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00002885 // If it's not the case that both 'inline' and 'extern' are
2886 // specified on the definition, then this inline definition is
2887 // externally visible.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002888 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00002889 return true;
2890
2891 // If any declaration is 'inline' but not 'extern', then this definition
2892 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00002893 for (auto Redecl : redecls()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00002894 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002895 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00002896 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00002897 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00002898
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002899 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002900 }
Eli Friedman1b125c32012-02-07 03:50:18 +00002901
Richard Smithf3814ad2013-01-25 00:08:28 +00002902 // The rest of this function is C-only.
2903 assert(!Context.getLangOpts().CPlusPlus &&
2904 "should not use C inline rules in C++");
2905
Douglas Gregor299d76e2009-09-13 07:46:26 +00002906 // C99 6.7.4p6:
2907 // [...] If all of the file scope declarations for a function in a
2908 // translation unit include the inline function specifier without extern,
2909 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00002910 for (auto Redecl : redecls()) {
2911 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00002912 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002913 }
2914
2915 // C99 6.7.4p6:
2916 // An inline definition does not provide an external definition for the
2917 // function, and does not forbid an external definition in another
2918 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002919 return false;
2920}
2921
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002922/// getOverloadedOperator - Which C++ overloaded operator this
2923/// function represents, if any.
2924OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00002925 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2926 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002927 else
2928 return OO_None;
2929}
2930
Alexis Huntc88db062010-01-13 09:01:02 +00002931/// getLiteralIdentifier - The literal suffix identifier this function
2932/// represents, if any.
2933const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2934 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2935 return getDeclName().getCXXLiteralIdentifier();
2936 else
Craig Topper36250ad2014-05-12 05:36:57 +00002937 return nullptr;
Alexis Huntc88db062010-01-13 09:01:02 +00002938}
2939
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002940FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2941 if (TemplateOrSpecialization.isNull())
2942 return TK_NonTemplate;
2943 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2944 return TK_FunctionTemplate;
2945 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2946 return TK_MemberSpecialization;
2947 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2948 return TK_FunctionTemplateSpecialization;
2949 if (TemplateOrSpecialization.is
2950 <DependentFunctionTemplateSpecializationInfo*>())
2951 return TK_DependentFunctionTemplateSpecialization;
2952
David Blaikie83d382b2011-09-23 05:06:16 +00002953 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002954}
2955
Douglas Gregord801b062009-10-07 23:56:10 +00002956FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002957 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00002958 return cast<FunctionDecl>(Info->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002959
2960 return nullptr;
Douglas Gregord801b062009-10-07 23:56:10 +00002961}
2962
2963void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002964FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2965 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00002966 TemplateSpecializationKind TSK) {
2967 assert(TemplateOrSpecialization.isNull() &&
2968 "Member function is already a specialization");
2969 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002970 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00002971 TemplateOrSpecialization = Info;
2972}
2973
Douglas Gregorafca3b42009-10-27 20:53:28 +00002974bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00002975 // If the function is invalid, it can't be implicitly instantiated.
2976 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00002977 return false;
2978
2979 switch (getTemplateSpecializationKind()) {
2980 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00002981 case TSK_ExplicitInstantiationDefinition:
2982 return false;
2983
2984 case TSK_ImplicitInstantiation:
2985 return true;
2986
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002987 // It is possible to instantiate TSK_ExplicitSpecialization kind
2988 // if the FunctionDecl has a class scope specialization pattern.
2989 case TSK_ExplicitSpecialization:
Craig Topper36250ad2014-05-12 05:36:57 +00002990 return getClassScopeSpecializationPattern() != nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002991
Douglas Gregorafca3b42009-10-27 20:53:28 +00002992 case TSK_ExplicitInstantiationDeclaration:
2993 // Handled below.
2994 break;
2995 }
2996
2997 // Find the actual template from which we will instantiate.
2998 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002999 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003000 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003001 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00003002
3003 // C++0x [temp.explicit]p9:
3004 // Except for inline functions, other explicit instantiation declarations
3005 // have the effect of suppressing the implicit instantiation of the entity
3006 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003007 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00003008 return true;
3009
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003010 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00003011}
3012
3013bool FunctionDecl::isTemplateInstantiation() const {
3014 switch (getTemplateSpecializationKind()) {
3015 case TSK_Undeclared:
3016 case TSK_ExplicitSpecialization:
3017 return false;
3018 case TSK_ImplicitInstantiation:
3019 case TSK_ExplicitInstantiationDeclaration:
3020 case TSK_ExplicitInstantiationDefinition:
3021 return true;
3022 }
3023 llvm_unreachable("All TSK values handled.");
3024}
Douglas Gregorafca3b42009-10-27 20:53:28 +00003025
3026FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003027 // Handle class scope explicit specialization special case.
3028 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3029 return getClassScopeSpecializationPattern();
Faisal Valib90b2112014-04-03 16:32:21 +00003030
3031 // If this is a generic lambda call operator specialization, its
3032 // instantiation pattern is always its primary template's pattern
3033 // even if its primary template was instantiated from another
3034 // member template (which happens with nested generic lambdas).
3035 // Since a lambda's call operator's body is transformed eagerly,
3036 // we don't have to go hunting for a prototype definition template
3037 // (i.e. instantiated-from-member-template) to use as an instantiation
3038 // pattern.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003039
Faisal Valib90b2112014-04-03 16:32:21 +00003040 if (isGenericLambdaCallOperatorSpecialization(
3041 dyn_cast<CXXMethodDecl>(this))) {
3042 assert(getPrimaryTemplate() && "A generic lambda specialization must be "
3043 "generated from a primary call operator "
3044 "template");
3045 assert(getPrimaryTemplate()->getTemplatedDecl()->getBody() &&
3046 "A generic lambda call operator template must always have a body - "
3047 "even if instantiated from a prototype (i.e. as written) member "
3048 "template");
3049 return getPrimaryTemplate()->getTemplatedDecl();
3050 }
3051
Douglas Gregorafca3b42009-10-27 20:53:28 +00003052 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3053 while (Primary->getInstantiatedFromMemberTemplate()) {
3054 // If we have hit a point where the user provided a specialization of
3055 // this template, we're done looking.
3056 if (Primary->isMemberSpecialization())
3057 break;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003058 Primary = Primary->getInstantiatedFromMemberTemplate();
3059 }
3060
3061 return Primary->getTemplatedDecl();
3062 }
3063
3064 return getInstantiatedFromMemberFunction();
3065}
3066
Douglas Gregor70d83e22009-06-29 17:30:29 +00003067FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00003068 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003069 = TemplateOrSpecialization
3070 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00003071 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00003072 }
Craig Topper36250ad2014-05-12 05:36:57 +00003073 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003074}
3075
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003076FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3077 return getASTContext().getClassScopeSpecializationPattern(this);
3078}
3079
Douglas Gregor70d83e22009-06-29 17:30:29 +00003080const TemplateArgumentList *
3081FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00003082 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00003083 = TemplateOrSpecialization
3084 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003085 return Info->TemplateArguments;
3086 }
Craig Topper36250ad2014-05-12 05:36:57 +00003087 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003088}
3089
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00003090const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003091FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3092 if (FunctionTemplateSpecializationInfo *Info
3093 = TemplateOrSpecialization
3094 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3095 return Info->TemplateArgumentsAsWritten;
3096 }
Craig Topper36250ad2014-05-12 05:36:57 +00003097 return nullptr;
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003098}
3099
Mike Stump11289f42009-09-09 15:08:12 +00003100void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003101FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3102 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003103 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003104 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003105 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00003106 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3107 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003108 assert(TSK != TSK_Undeclared &&
3109 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00003110 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003111 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003112 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00003113 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3114 TemplateArgs,
3115 TemplateArgsAsWritten,
3116 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003117 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00003118 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003119}
3120
John McCallb9c78482010-04-08 09:05:18 +00003121void
3122FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3123 const UnresolvedSetImpl &Templates,
3124 const TemplateArgumentListInfo &TemplateArgs) {
3125 assert(TemplateOrSpecialization.isNull());
John McCallb9c78482010-04-08 09:05:18 +00003126 DependentFunctionTemplateSpecializationInfo *Info =
James Y Knight7a22b242015-08-06 20:26:32 +00003127 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3128 TemplateArgs);
John McCallb9c78482010-04-08 09:05:18 +00003129 TemplateOrSpecialization = Info;
3130}
3131
James Y Knight7a22b242015-08-06 20:26:32 +00003132DependentFunctionTemplateSpecializationInfo *
3133DependentFunctionTemplateSpecializationInfo::Create(
3134 ASTContext &Context, const UnresolvedSetImpl &Ts,
3135 const TemplateArgumentListInfo &TArgs) {
3136 void *Buffer = Context.Allocate(
3137 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3138 TArgs.size(), Ts.size()));
3139 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3140}
3141
John McCallb9c78482010-04-08 09:05:18 +00003142DependentFunctionTemplateSpecializationInfo::
3143DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3144 const TemplateArgumentListInfo &TArgs)
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003145 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
John McCallb9c78482010-04-08 09:05:18 +00003146
James Y Knight53c76162015-07-17 18:21:37 +00003147 NumTemplates = Ts.size();
3148 NumArgs = TArgs.size();
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003149
James Y Knight7a22b242015-08-06 20:26:32 +00003150 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
John McCallb9c78482010-04-08 09:05:18 +00003151 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3152 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3153
James Y Knight7a22b242015-08-06 20:26:32 +00003154 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
John McCallb9c78482010-04-08 09:05:18 +00003155 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3156 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3157}
3158
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003159TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00003160 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003161 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00003162 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00003163 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00003164 if (FTSInfo)
3165 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00003166
Douglas Gregord801b062009-10-07 23:56:10 +00003167 MemberSpecializationInfo *MSInfo
3168 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3169 if (MSInfo)
3170 return MSInfo->getTemplateSpecializationKind();
3171
3172 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003173}
3174
Mike Stump11289f42009-09-09 15:08:12 +00003175void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003176FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3177 SourceLocation PointOfInstantiation) {
3178 if (FunctionTemplateSpecializationInfo *FTSInfo
3179 = TemplateOrSpecialization.dyn_cast<
3180 FunctionTemplateSpecializationInfo*>()) {
3181 FTSInfo->setTemplateSpecializationKind(TSK);
3182 if (TSK != TSK_ExplicitSpecialization &&
3183 PointOfInstantiation.isValid() &&
3184 FTSInfo->getPointOfInstantiation().isInvalid())
3185 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3186 } else if (MemberSpecializationInfo *MSInfo
3187 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3188 MSInfo->setTemplateSpecializationKind(TSK);
3189 if (TSK != TSK_ExplicitSpecialization &&
3190 PointOfInstantiation.isValid() &&
3191 MSInfo->getPointOfInstantiation().isInvalid())
3192 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3193 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003194 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003195}
3196
3197SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00003198 if (FunctionTemplateSpecializationInfo *FTSInfo
3199 = TemplateOrSpecialization.dyn_cast<
3200 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003201 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00003202 else if (MemberSpecializationInfo *MSInfo
3203 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003204 return MSInfo->getPointOfInstantiation();
3205
3206 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00003207}
3208
Douglas Gregor6411b922009-09-11 20:15:17 +00003209bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00003210 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00003211 return true;
3212
3213 // If this function was instantiated from a member function of a
3214 // class template, check whether that member function was defined out-of-line.
3215 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3216 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003217 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003218 return Definition->isOutOfLine();
3219 }
3220
3221 // If this function was instantiated from a function template,
3222 // check whether that function template was defined out-of-line.
3223 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3224 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003225 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003226 return Definition->isOutOfLine();
3227 }
3228
3229 return false;
3230}
3231
Abramo Bagnaraea947882011-03-08 16:41:52 +00003232SourceRange FunctionDecl::getSourceRange() const {
3233 return SourceRange(getOuterLocStart(), EndRangeLoc);
3234}
3235
Anna Zaks28db7ce2012-01-18 02:45:01 +00003236unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00003237 IdentifierInfo *FnInfo = getIdentifier();
3238
3239 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00003240 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003241
3242 // Builtin handling.
3243 switch (getBuiltinID()) {
3244 case Builtin::BI__builtin_memset:
3245 case Builtin::BI__builtin___memset_chk:
3246 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003247 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003248
3249 case Builtin::BI__builtin_memcpy:
3250 case Builtin::BI__builtin___memcpy_chk:
3251 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003252 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003253
3254 case Builtin::BI__builtin_memmove:
3255 case Builtin::BI__builtin___memmove_chk:
3256 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003257 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003258
3259 case Builtin::BIstrlcpy:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003260 case Builtin::BI__builtin___strlcpy_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003261 return Builtin::BIstrlcpy;
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003262
Anna Zaks201d4892012-01-13 21:52:01 +00003263 case Builtin::BIstrlcat:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003264 case Builtin::BI__builtin___strlcat_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003265 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003266
3267 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003268 case Builtin::BImemcmp:
3269 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003270
3271 case Builtin::BI__builtin_strncpy:
3272 case Builtin::BI__builtin___strncpy_chk:
3273 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003274 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003275
3276 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003277 case Builtin::BIstrncmp:
3278 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003279
3280 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003281 case Builtin::BIstrncasecmp:
3282 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003283
3284 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003285 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003286 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003287 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003288
3289 case Builtin::BI__builtin_strndup:
3290 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003291 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003292
Anna Zaks314cd092012-02-01 19:08:57 +00003293 case Builtin::BI__builtin_strlen:
3294 case Builtin::BIstrlen:
3295 return Builtin::BIstrlen;
3296
Anna Zaks201d4892012-01-13 21:52:01 +00003297 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003298 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003299 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003300 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003301 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003302 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003303 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003304 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003305 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003306 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003307 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003308 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003309 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003310 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003311 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003312 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003313 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003314 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003315 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003316 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003317 else if (FnInfo->isStr("strlen"))
3318 return Builtin::BIstrlen;
Anna Zaks201d4892012-01-13 21:52:01 +00003319 }
3320 break;
3321 }
Anna Zaks22122702012-01-17 00:37:07 +00003322 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003323}
3324
Chris Lattner59a25942008-03-31 00:36:02 +00003325//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003326// FieldDecl Implementation
3327//===----------------------------------------------------------------------===//
3328
Jay Foad39c79802011-01-12 09:06:06 +00003329FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003330 SourceLocation StartLoc, SourceLocation IdLoc,
3331 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003332 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003333 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003334 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3335 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003336}
3337
Douglas Gregor72172e92012-01-05 21:55:30 +00003338FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003339 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3340 SourceLocation(), nullptr, QualType(), nullptr,
3341 nullptr, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00003342}
3343
Sebastian Redl833ef452010-01-26 22:01:41 +00003344bool FieldDecl::isAnonymousStructOrUnion() const {
3345 if (!isImplicit() || getDeclName())
3346 return false;
3347
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003348 if (const auto *Record = getType()->getAs<RecordType>())
Sebastian Redl833ef452010-01-26 22:01:41 +00003349 return Record->getDecl()->isAnonymousStructOrUnion();
3350
3351 return false;
3352}
3353
Richard Smithcaf33902011-10-10 18:28:20 +00003354unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3355 assert(isBitField() && "not a bitfield");
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003356 auto *BitWidth = static_cast<Expr *>(InitStorage.getPointer());
Richard Smithcaf33902011-10-10 18:28:20 +00003357 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3358}
3359
John McCall4e819612011-01-20 07:57:12 +00003360unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00003361 const FieldDecl *Canonical = getCanonicalDecl();
3362 if (Canonical != this)
3363 return Canonical->getFieldIndex();
3364
John McCall4e819612011-01-20 07:57:12 +00003365 if (CachedFieldIndex) return CachedFieldIndex - 1;
3366
Richard Smithd62306a2011-11-10 06:34:14 +00003367 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00003368 const RecordDecl *RD = getParent();
Richard Smithd62306a2011-11-10 06:34:14 +00003369
Hans Wennborga302cd92014-08-21 16:06:57 +00003370 for (auto *Field : RD->fields()) {
3371 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3372 ++Index;
3373 }
John McCall4e819612011-01-20 07:57:12 +00003374
Richard Smithd62306a2011-11-10 06:34:14 +00003375 assert(CachedFieldIndex && "failed to find field in parent");
3376 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00003377}
3378
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003379SourceRange FieldDecl::getSourceRange() const {
John McCallc90c1492014-10-10 18:44:34 +00003380 switch (InitStorage.getInt()) {
3381 // All three of these cases store an optional Expr*.
3382 case ISK_BitWidthOrNothing:
3383 case ISK_InClassCopyInit:
3384 case ISK_InClassListInit:
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003385 if (const auto *E = static_cast<const Expr *>(InitStorage.getPointer()))
John McCallc90c1492014-10-10 18:44:34 +00003386 return SourceRange(getInnerLocStart(), E->getLocEnd());
3387 // FALLTHROUGH
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003388
John McCallc90c1492014-10-10 18:44:34 +00003389 case ISK_CapturedVLAType:
3390 return DeclaratorDecl::getSourceRange();
3391 }
3392 llvm_unreachable("bad init storage kind");
Alexey Bataev39c81e22014-08-28 04:28:19 +00003393}
3394
3395void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
David Blaikie11ab0782014-10-31 17:18:09 +00003396 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
Alexey Bataev330de032014-10-29 12:21:55 +00003397 "capturing type in non-lambda or captured record.");
John McCallc90c1492014-10-10 18:44:34 +00003398 assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
3399 InitStorage.getPointer() == nullptr &&
Alexey Bataev39c81e22014-08-28 04:28:19 +00003400 "bit width, initializer or captured type already set");
John McCallc90c1492014-10-10 18:44:34 +00003401 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3402 ISK_CapturedVLAType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00003403}
3404
Sebastian Redl833ef452010-01-26 22:01:41 +00003405//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003406// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00003407//===----------------------------------------------------------------------===//
3408
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003409SourceLocation TagDecl::getOuterLocStart() const {
3410 return getTemplateOrInnerLocStart(this);
3411}
3412
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003413SourceRange TagDecl::getSourceRange() const {
3414 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003415 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003416}
3417
Rafael Espindola8db352d2013-10-17 15:37:26 +00003418TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00003419
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00003420void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer00350522015-08-31 18:48:39 +00003421 TypedefNameDeclOrQualifier = TDD;
Reid Klecknercae82a22014-04-23 22:03:04 +00003422 if (const Type *T = getTypeForDecl()) {
3423 (void)T;
Richard Smith5b21db82014-04-23 18:20:42 +00003424 assert(T->isLinkageValid());
Reid Klecknercae82a22014-04-23 22:03:04 +00003425 }
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003426 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00003427}
3428
Douglas Gregordee1be82009-01-17 00:42:38 +00003429void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003430 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00003431
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003432 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
Richard Smith053f6c62014-05-16 23:01:30 +00003433 struct CXXRecordDecl::DefinitionData *Data =
John McCall67da35c2010-02-04 22:26:26 +00003434 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00003435 for (auto I : redecls())
Richard Smith64c06302014-05-22 23:19:02 +00003436 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00003437 }
Douglas Gregordee1be82009-01-17 00:42:38 +00003438}
3439
3440void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00003441 assert((!isa<CXXRecordDecl>(this) ||
3442 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3443 "definition completed but not started");
3444
John McCallf937c022011-10-07 06:10:15 +00003445 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003446 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00003447
3448 if (ASTMutationListener *L = getASTMutationListener())
3449 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00003450}
3451
John McCallf937c022011-10-07 06:10:15 +00003452TagDecl *TagDecl::getDefinition() const {
3453 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003454 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003455
3456 // If it's possible for us to have an out-of-date definition, check now.
3457 if (MayHaveOutOfDateDef) {
3458 if (IdentifierInfo *II = getIdentifier()) {
3459 if (II->isOutOfDate()) {
3460 updateOutOfDate(*II);
3461 }
3462 }
3463 }
3464
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003465 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
Andrew Trickba266ee2010-10-19 21:54:32 +00003466 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003467
Aaron Ballman86c93902014-03-06 23:45:36 +00003468 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00003469 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00003470 return R;
Mike Stump11289f42009-09-09 15:08:12 +00003471
Craig Topper36250ad2014-05-12 05:36:57 +00003472 return nullptr;
Ted Kremenek21475702008-09-05 17:16:31 +00003473}
3474
Douglas Gregor14454802011-02-25 02:25:35 +00003475void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3476 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00003477 // Make sure the extended qualifier info is allocated.
3478 if (!hasExtInfo())
David Majnemer00350522015-08-31 18:48:39 +00003479 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00003480 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00003481 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003482 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00003483 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00003484 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00003485 if (getExtInfo()->NumTemplParamLists == 0) {
3486 getASTContext().Deallocate(getExtInfo());
David Majnemer00350522015-08-31 18:48:39 +00003487 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003488 }
3489 else
3490 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00003491 }
3492 }
3493}
3494
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003495void TagDecl::setTemplateParameterListsInfo(
3496 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
3497 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00003498 // Make sure the extended decl info is allocated.
3499 if (!hasExtInfo())
3500 // Allocate external info struct.
David Majnemer00350522015-08-31 18:48:39 +00003501 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003502 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003503 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00003504}
3505
Ted Kremenek21475702008-09-05 17:16:31 +00003506//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003507// EnumDecl Implementation
3508//===----------------------------------------------------------------------===//
3509
David Blaikie68e081d2011-12-20 02:48:34 +00003510void EnumDecl::anchor() { }
3511
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003512EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3513 SourceLocation StartLoc, SourceLocation IdLoc,
3514 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00003515 EnumDecl *PrevDecl, bool IsScoped,
3516 bool IsScopedUsingClassTag, bool IsFixed) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003517 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
3518 IsScoped, IsScopedUsingClassTag, IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003519 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00003520 C.getTypeDeclType(Enum, PrevDecl);
3521 return Enum;
3522}
3523
Douglas Gregor72172e92012-01-05 21:55:30 +00003524EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003525 EnumDecl *Enum =
3526 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3527 nullptr, nullptr, false, false, false);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003528 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3529 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003530}
3531
Alp Tokerb9fa5122014-01-06 11:31:18 +00003532SourceRange EnumDecl::getIntegerTypeRange() const {
3533 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3534 return TI->getTypeLoc().getSourceRange();
3535 return SourceRange();
3536}
3537
Douglas Gregord5058122010-02-11 01:19:42 +00003538void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00003539 QualType NewPromotionType,
3540 unsigned NumPositiveBits,
3541 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00003542 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00003543 if (!IntegerType)
3544 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00003545 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00003546 setNumPositiveBits(NumPositiveBits);
3547 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00003548 TagDecl::completeDefinition();
3549}
3550
Richard Smith7d137e32012-03-23 03:33:32 +00003551TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3552 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3553 return MSI->getTemplateSpecializationKind();
3554
3555 return TSK_Undeclared;
3556}
3557
3558void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3559 SourceLocation PointOfInstantiation) {
3560 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3561 assert(MSI && "Not an instantiated member enumeration?");
3562 MSI->setTemplateSpecializationKind(TSK);
3563 if (TSK != TSK_ExplicitSpecialization &&
3564 PointOfInstantiation.isValid() &&
3565 MSI->getPointOfInstantiation().isInvalid())
3566 MSI->setPointOfInstantiation(PointOfInstantiation);
3567}
3568
Richard Smith4b38ded2012-03-14 23:13:10 +00003569EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3570 if (SpecializationInfo)
3571 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3572
Craig Topper36250ad2014-05-12 05:36:57 +00003573 return nullptr;
Richard Smith4b38ded2012-03-14 23:13:10 +00003574}
3575
3576void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3577 TemplateSpecializationKind TSK) {
3578 assert(!SpecializationInfo && "Member enum is already a specialization");
3579 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3580}
3581
Sebastian Redl833ef452010-01-26 22:01:41 +00003582//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003583// RecordDecl Implementation
3584//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003585
Richard Smith053f6c62014-05-16 23:01:30 +00003586RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3587 DeclContext *DC, SourceLocation StartLoc,
3588 SourceLocation IdLoc, IdentifierInfo *Id,
3589 RecordDecl *PrevDecl)
3590 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003591 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003592 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003593 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00003594 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003595 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00003596 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003597}
3598
Jay Foad39c79802011-01-12 09:06:06 +00003599RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003600 SourceLocation StartLoc, SourceLocation IdLoc,
3601 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smith053f6c62014-05-16 23:01:30 +00003602 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
3603 StartLoc, IdLoc, Id, PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003604 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3605
Ted Kremenek21475702008-09-05 17:16:31 +00003606 C.getTypeDeclType(R, PrevDecl);
3607 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003608}
3609
Douglas Gregor72172e92012-01-05 21:55:30 +00003610RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003611 RecordDecl *R =
3612 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
3613 SourceLocation(), nullptr, nullptr);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003614 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3615 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003616}
3617
Douglas Gregordfcad112009-03-25 15:59:44 +00003618bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003619 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003620 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3621}
3622
Alexey Bataev39c81e22014-08-28 04:28:19 +00003623bool RecordDecl::isLambda() const {
3624 if (auto RD = dyn_cast<CXXRecordDecl>(this))
3625 return RD->isLambda();
3626 return false;
3627}
3628
Alexey Bataev330de032014-10-29 12:21:55 +00003629bool RecordDecl::isCapturedRecord() const {
3630 return hasAttr<CapturedRecordAttr>();
3631}
3632
3633void RecordDecl::setCapturedRecord() {
3634 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
3635}
3636
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003637RecordDecl::field_iterator RecordDecl::field_begin() const {
3638 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3639 LoadFieldsFromExternalStorage();
3640
3641 return field_iterator(decl_iterator(FirstDecl));
3642}
3643
Douglas Gregorb11aad82011-02-19 18:51:44 +00003644/// completeDefinition - Notes that the definition of this type is now
3645/// complete.
3646void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003647 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003648 TagDecl::completeDefinition();
3649}
3650
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003651/// isMsStruct - Get whether or not this record uses ms_struct layout.
3652/// This which can be turned on with an attribute, pragma, or the
3653/// -mms-bitfields command-line option.
3654bool RecordDecl::isMsStruct(const ASTContext &C) const {
David Majnemer8ab003a2015-02-02 19:30:52 +00003655 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003656}
3657
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003658void RecordDecl::LoadFieldsFromExternalStorage() const {
3659 ExternalASTSource *Source = getASTContext().getExternalSource();
3660 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3661
3662 // Notify that we have a RecordDecl doing some initialization.
3663 ExternalASTSource::Deserializing TheFields(Source);
3664
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003665 SmallVector<Decl*, 64> Decls;
Richard Smith3cb15722015-08-05 22:41:45 +00003666 LoadedFieldsFromExternalStorage = true;
3667 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
3668 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3669 }, Decls);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003670
3671#ifndef NDEBUG
3672 // Check that all decls we got were FieldDecls.
3673 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003674 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003675#endif
3676
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003677 if (Decls.empty())
3678 return;
3679
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003680 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003681 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003682}
3683
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003684bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
3685 ASTContext &Context = getASTContext();
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00003686 if (!Context.getLangOpts().Sanitize.hasOneOf(
3687 SanitizerKind::Address | SanitizerKind::KernelAddress) ||
Alexey Samsonova0416102014-11-11 01:26:14 +00003688 !Context.getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003689 return false;
Alexey Samsonov33e00e22014-10-16 23:50:26 +00003690 const auto &Blacklist = Context.getSanitizerBlacklist();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003691 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003692 // We may be able to relax some of these requirements.
3693 int ReasonToReject = -1;
3694 if (!CXXRD || CXXRD->isExternCContext())
3695 ReasonToReject = 0; // is not C++.
3696 else if (CXXRD->hasAttr<PackedAttr>())
3697 ReasonToReject = 1; // is packed.
3698 else if (CXXRD->isUnion())
3699 ReasonToReject = 2; // is a union.
3700 else if (CXXRD->isTriviallyCopyable())
3701 ReasonToReject = 3; // is trivially copyable.
3702 else if (CXXRD->hasTrivialDestructor())
3703 ReasonToReject = 4; // has trivial destructor.
3704 else if (CXXRD->isStandardLayout())
3705 ReasonToReject = 5; // is standard layout.
Alexey Samsonov33e00e22014-10-16 23:50:26 +00003706 else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003707 ReasonToReject = 6; // is in a blacklisted file.
3708 else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(),
3709 "field-padding"))
3710 ReasonToReject = 7; // is blacklisted.
3711
3712 if (EmitRemark) {
3713 if (ReasonToReject >= 0)
3714 Context.getDiagnostics().Report(
3715 getLocation(),
3716 diag::remark_sanitize_address_insert_extra_padding_rejected)
3717 << getQualifiedNameAsString() << ReasonToReject;
3718 else
3719 Context.getDiagnostics().Report(
3720 getLocation(),
3721 diag::remark_sanitize_address_insert_extra_padding_accepted)
3722 << getQualifiedNameAsString();
3723 }
3724 return ReasonToReject < 0;
3725}
3726
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003727const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
3728 for (const auto *I : fields()) {
3729 if (I->getIdentifier())
3730 return I;
3731
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003732 if (const auto *RT = I->getType()->getAs<RecordType>())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003733 if (const FieldDecl *NamedDataMember =
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003734 RT->getDecl()->findFirstNamedDataMember())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003735 return NamedDataMember;
3736 }
3737
3738 // We didn't find a named data member.
3739 return nullptr;
3740}
3741
3742
Steve Naroff415d3d52008-10-08 17:01:13 +00003743//===----------------------------------------------------------------------===//
3744// BlockDecl Implementation
3745//===----------------------------------------------------------------------===//
3746
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003747void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00003748 assert(!ParamInfo && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00003749
Steve Naroffc4b30e52009-03-13 16:56:44 +00003750 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003751 if (!NewParamInfo.empty()) {
3752 NumParams = NewParamInfo.size();
3753 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3754 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003755 }
3756}
3757
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00003758void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
3759 bool CapturesCXXThis) {
3760 this->CapturesCXXThis = CapturesCXXThis;
3761 this->NumCaptures = Captures.size();
John McCallc63de662011-02-02 13:00:07 +00003762
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00003763 if (Captures.empty()) {
3764 this->Captures = nullptr;
John McCallc63de662011-02-02 13:00:07 +00003765 return;
3766 }
3767
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00003768 this->Captures = Captures.copy(Context).data();
Steve Naroffc4b30e52009-03-13 16:56:44 +00003769}
Sebastian Redl833ef452010-01-26 22:01:41 +00003770
John McCallce45f882011-06-15 22:51:16 +00003771bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00003772 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00003773 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00003774 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00003775 return true;
3776
3777 return false;
3778}
3779
Douglas Gregor70226da2010-12-21 16:27:07 +00003780SourceRange BlockDecl::getSourceRange() const {
3781 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3782}
Sebastian Redl833ef452010-01-26 22:01:41 +00003783
3784//===----------------------------------------------------------------------===//
3785// Other Decl Allocation/Deallocation Method Implementations
3786//===----------------------------------------------------------------------===//
3787
David Blaikie68e081d2011-12-20 02:48:34 +00003788void TranslationUnitDecl::anchor() { }
3789
Sebastian Redl833ef452010-01-26 22:01:41 +00003790TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Craig Topper36250ad2014-05-12 05:36:57 +00003791 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00003792}
3793
Richard Smithf19e1272015-03-07 00:04:49 +00003794void ExternCContextDecl::anchor() { }
3795
3796ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
3797 TranslationUnitDecl *DC) {
3798 return new (C, DC) ExternCContextDecl(DC);
3799}
3800
David Blaikie68e081d2011-12-20 02:48:34 +00003801void LabelDecl::anchor() { }
3802
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003803LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003804 SourceLocation IdentL, IdentifierInfo *II) {
Craig Topper36250ad2014-05-12 05:36:57 +00003805 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003806}
3807
3808LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3809 SourceLocation IdentL, IdentifierInfo *II,
3810 SourceLocation GnuLabelL) {
3811 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Craig Topper36250ad2014-05-12 05:36:57 +00003812 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003813}
3814
Douglas Gregor72172e92012-01-05 21:55:30 +00003815LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003816 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
3817 SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00003818}
3819
Ehsan Akhgari31097582014-09-22 02:21:54 +00003820void LabelDecl::setMSAsmLabel(StringRef Name) {
3821 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
3822 memcpy(Buffer, Name.data(), Name.size());
3823 Buffer[Name.size()] = '\0';
3824 MSAsmName = Buffer;
3825}
3826
David Blaikie68e081d2011-12-20 02:48:34 +00003827void ValueDecl::anchor() { }
3828
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003829bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00003830 for (const auto *I : attrs())
3831 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003832 return true;
3833
3834 return isWeakImported();
3835}
3836
David Blaikie68e081d2011-12-20 02:48:34 +00003837void ImplicitParamDecl::anchor() { }
3838
Sebastian Redl833ef452010-01-26 22:01:41 +00003839ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003840 SourceLocation IdLoc,
3841 IdentifierInfo *Id,
3842 QualType Type) {
Richard Smith053f6c62014-05-16 23:01:30 +00003843 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00003844}
3845
Richard Smithf7981722013-11-22 09:01:48 +00003846ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00003847 unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003848 return new (C, ID) ImplicitParamDecl(C, nullptr, SourceLocation(), nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00003849 QualType());
Douglas Gregor72172e92012-01-05 21:55:30 +00003850}
3851
Sebastian Redl833ef452010-01-26 22:01:41 +00003852FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003853 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003854 const DeclarationNameInfo &NameInfo,
3855 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003856 StorageClass SC,
Richard Smithf7981722013-11-22 09:01:48 +00003857 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00003858 bool hasWrittenPrototype,
3859 bool isConstexprSpecified) {
Richard Smithf7981722013-11-22 09:01:48 +00003860 FunctionDecl *New =
Richard Smith053f6c62014-05-16 23:01:30 +00003861 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
3862 SC, isInlineSpecified, isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00003863 New->HasWrittenPrototype = hasWrittenPrototype;
3864 return New;
3865}
3866
Douglas Gregor72172e92012-01-05 21:55:30 +00003867FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003868 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00003869 DeclarationNameInfo(), QualType(), nullptr,
Richard Smithf7981722013-11-22 09:01:48 +00003870 SC_None, false, false);
Douglas Gregor72172e92012-01-05 21:55:30 +00003871}
3872
Sebastian Redl833ef452010-01-26 22:01:41 +00003873BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00003874 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00003875}
3876
Douglas Gregor72172e92012-01-05 21:55:30 +00003877BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003878 return new (C, ID) BlockDecl(nullptr, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00003879}
3880
Ben Langmuir37943a72013-05-03 19:00:33 +00003881CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
3882 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00003883 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Richard Smithf7981722013-11-22 09:01:48 +00003884 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003885}
3886
Ben Langmuirce914fc2013-05-03 19:20:19 +00003887CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00003888 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00003889 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Craig Topper36250ad2014-05-12 05:36:57 +00003890 CapturedDecl(nullptr, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00003891}
3892
Sebastian Redl833ef452010-01-26 22:01:41 +00003893EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3894 SourceLocation L,
3895 IdentifierInfo *Id, QualType T,
3896 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00003897 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00003898}
3899
Douglas Gregor72172e92012-01-05 21:55:30 +00003900EnumConstantDecl *
3901EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003902 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
3903 QualType(), nullptr, llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00003904}
3905
David Blaikie68e081d2011-12-20 02:48:34 +00003906void IndirectFieldDecl::anchor() { }
3907
Benjamin Kramer39593702010-11-21 14:11:41 +00003908IndirectFieldDecl *
3909IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3910 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3911 unsigned CHS) {
Richard Smithf7981722013-11-22 09:01:48 +00003912 return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003913}
3914
Douglas Gregor72172e92012-01-05 21:55:30 +00003915IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3916 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003917 return new (C, ID) IndirectFieldDecl(nullptr, SourceLocation(),
3918 DeclarationName(), QualType(), nullptr,
3919 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00003920}
3921
Douglas Gregorbe996932010-09-01 20:41:53 +00003922SourceRange EnumConstantDecl::getSourceRange() const {
3923 SourceLocation End = getLocation();
3924 if (Init)
3925 End = Init->getLocEnd();
3926 return SourceRange(getLocation(), End);
3927}
3928
David Blaikie68e081d2011-12-20 02:48:34 +00003929void TypeDecl::anchor() { }
3930
Sebastian Redl833ef452010-01-26 22:01:41 +00003931TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003932 SourceLocation StartLoc, SourceLocation IdLoc,
3933 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00003934 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00003935}
3936
David Blaikie68e081d2011-12-20 02:48:34 +00003937void TypedefNameDecl::anchor() { }
3938
Richard Smith42413142015-05-15 20:05:43 +00003939TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
3940 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
3941 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
3942 auto *ThisTypedef = this;
3943 if (AnyRedecl && OwningTypedef) {
3944 OwningTypedef = OwningTypedef->getCanonicalDecl();
3945 ThisTypedef = ThisTypedef->getCanonicalDecl();
3946 }
3947 if (OwningTypedef == ThisTypedef)
Richard Smitha5230222015-03-27 01:37:43 +00003948 return TT->getDecl();
Richard Smith42413142015-05-15 20:05:43 +00003949 }
Richard Smitha5230222015-03-27 01:37:43 +00003950
3951 return nullptr;
3952}
3953
Douglas Gregor72172e92012-01-05 21:55:30 +00003954TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003955 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00003956 nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00003957}
3958
Richard Smithdda56e42011-04-15 14:24:37 +00003959TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3960 SourceLocation StartLoc,
3961 SourceLocation IdLoc, IdentifierInfo *Id,
3962 TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00003963 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00003964}
3965
Douglas Gregor72172e92012-01-05 21:55:30 +00003966TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003967 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
3968 SourceLocation(), nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00003969}
3970
Abramo Bagnaraea947882011-03-08 16:41:52 +00003971SourceRange TypedefDecl::getSourceRange() const {
3972 SourceLocation RangeEnd = getLocation();
3973 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3974 if (typeIsPostfix(TInfo->getType()))
3975 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3976 }
3977 return SourceRange(getLocStart(), RangeEnd);
3978}
3979
Richard Smithdda56e42011-04-15 14:24:37 +00003980SourceRange TypeAliasDecl::getSourceRange() const {
3981 SourceLocation RangeEnd = getLocStart();
3982 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3983 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3984 return SourceRange(getLocStart(), RangeEnd);
3985}
3986
David Blaikie68e081d2011-12-20 02:48:34 +00003987void FileScopeAsmDecl::anchor() { }
3988
Sebastian Redl833ef452010-01-26 22:01:41 +00003989FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00003990 StringLiteral *Str,
3991 SourceLocation AsmLoc,
3992 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00003993 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00003994}
Douglas Gregorba345522011-12-02 23:23:56 +00003995
Richard Smithf7981722013-11-22 09:01:48 +00003996FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00003997 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003998 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
3999 SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00004000}
4001
Michael Han84324352013-02-22 17:15:32 +00004002void EmptyDecl::anchor() {}
4003
4004EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004005 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00004006}
4007
4008EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004009 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00004010}
4011
Douglas Gregorba345522011-12-02 23:23:56 +00004012//===----------------------------------------------------------------------===//
4013// ImportDecl Implementation
4014//===----------------------------------------------------------------------===//
4015
4016/// \brief Retrieve the number of module identifiers needed to name the given
4017/// module.
4018static unsigned getNumModuleIdentifiers(Module *Mod) {
4019 unsigned Result = 1;
4020 while (Mod->Parent) {
4021 Mod = Mod->Parent;
4022 ++Result;
4023 }
4024 return Result;
4025}
4026
Douglas Gregor22d09742012-01-03 18:04:46 +00004027ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004028 Module *Imported,
4029 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00004030 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00004031 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00004032{
4033 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004034 auto *StoredLocs = getTrailingObjects<SourceLocation>();
James Y Knight7a22b242015-08-06 20:26:32 +00004035 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4036 StoredLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004037}
4038
Douglas Gregor22d09742012-01-03 18:04:46 +00004039ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004040 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00004041 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00004042 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00004043{
James Y Knight7a22b242015-08-06 20:26:32 +00004044 *getTrailingObjects<SourceLocation>() = EndLoc;
Douglas Gregorba345522011-12-02 23:23:56 +00004045}
4046
Richard Smithf7981722013-11-22 09:01:48 +00004047ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004048 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004049 ArrayRef<SourceLocation> IdentifierLocs) {
James Y Knight7a22b242015-08-06 20:26:32 +00004050 return new (C, DC,
4051 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
Richard Smithf7981722013-11-22 09:01:48 +00004052 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004053}
4054
Richard Smithf7981722013-11-22 09:01:48 +00004055ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004056 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00004057 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004058 SourceLocation EndLoc) {
James Y Knight7a22b242015-08-06 20:26:32 +00004059 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
4060 ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00004061 Import->setImplicit();
4062 return Import;
4063}
4064
Douglas Gregor72172e92012-01-05 21:55:30 +00004065ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4066 unsigned NumLocations) {
James Y Knight7a22b242015-08-06 20:26:32 +00004067 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
Richard Smithf7981722013-11-22 09:01:48 +00004068 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00004069}
4070
4071ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4072 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004073 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00004074
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004075 const auto *StoredLocs = getTrailingObjects<SourceLocation>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00004076 return llvm::makeArrayRef(StoredLocs,
4077 getNumModuleIdentifiers(getImportedModule()));
Douglas Gregorba345522011-12-02 23:23:56 +00004078}
4079
4080SourceRange ImportDecl::getSourceRange() const {
4081 if (!ImportedAndComplete.getInt())
James Y Knight7a22b242015-08-06 20:26:32 +00004082 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
4083
Douglas Gregorba345522011-12-02 23:23:56 +00004084 return SourceRange(getLocation(), getIdentifierLocs().back());
4085}