blob: 267c6992af89784ed0c3ba2f6eedbded401f8de2 [file] [log] [blame]
Chris Lattnera11999d2006-10-15 22:34:45 +00001//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera11999d2006-10-15 22:34:45 +00007//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidis63018842008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Chris Lattnera11999d2006-10-15 22:34:45 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
Chris Lattnera7b32872008-03-15 06:12:44 +000015#include "clang/AST/ASTContext.h"
Faisal Valib90b2112014-04-03 16:32:21 +000016#include "clang/AST/ASTLambda.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/Attr.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000021#include "clang/AST/DeclOpenMP.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/AST/DeclTemplate.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000023#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000024#include "clang/AST/ExprCXX.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000025#include "clang/AST/PrettyPrinter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000026#include "clang/AST/Stmt.h"
27#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000028#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000029#include "clang/Basic/IdentifierTable.h"
Douglas Gregorba345522011-12-02 23:23:56 +000030#include "clang/Basic/Module.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000031#include "clang/Basic/Specifiers.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000032#include "clang/Basic/TargetInfo.h"
Kostya Serebryany293dc9b2014-10-16 20:54:52 +000033#include "clang/Frontend/FrontendDiagnostic.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000034#include "llvm/Support/ErrorHandling.h"
David Blaikie9c70e042011-09-21 18:16:56 +000035#include <algorithm>
36
Chris Lattner6d9a6852006-10-25 05:11:20 +000037using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000038
Richard Smith0b87e072013-10-07 08:02:11 +000039Decl *clang::getPrimaryMergedDecl(Decl *D) {
40 return D->getASTContext().getPrimaryMergedDecl(D);
41}
42
Richard Smith73b21d82014-09-03 02:33:22 +000043// Defined here so that it can be inlined into its direct callers.
44bool Decl::isOutOfLine() const {
45 return !getLexicalDeclContext()->Equals(getDeclContext());
46}
47
Richard Smith42413142015-05-15 20:05:43 +000048TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
49 : Decl(TranslationUnit, nullptr, SourceLocation()),
Richard Smith26342f92017-05-17 00:24:14 +000050 DeclContext(TranslationUnit), Ctx(ctx), AnonymousNamespace(nullptr) {}
Richard Smith42413142015-05-15 20:05:43 +000051
Chris Lattner88f70d62008-03-15 05:43:15 +000052//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000053// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000054//===----------------------------------------------------------------------===//
55
John McCalldf25c432013-02-16 00:17:33 +000056// Visibility rules aren't rigorously externally specified, but here
57// are the basic principles behind what we implement:
58//
59// 1. An explicit visibility attribute is generally a direct expression
60// of the user's intent and should be honored. Only the innermost
61// visibility attribute applies. If no visibility attribute applies,
62// global visibility settings are considered.
63//
64// 2. There is one caveat to the above: on or in a template pattern,
65// an explicit visibility attribute is just a default rule, and
66// visibility can be decreased by the visibility of template
67// arguments. But this, too, has an exception: an attribute on an
68// explicit specialization or instantiation causes all the visibility
69// restrictions of the template arguments to be ignored.
70//
71// 3. A variable that does not otherwise have explicit visibility can
72// be restricted by the visibility of its type.
73//
74// 4. A visibility restriction is explicit if it comes from an
75// attribute (or something like it), not a global visibility setting.
76// When emitting a reference to an external symbol, visibility
77// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +000078//
79// 5. When computing the visibility of a non-type, including a
80// non-type member of a class, only non-type visibility restrictions
81// are considered: the 'visibility' attribute, global value-visibility
82// settings, and a few special cases like __private_extern.
83//
84// 6. When computing the visibility of a type, including a type member
85// of a class, only type visibility restrictions are considered:
86// the 'type_visibility' attribute and global type-visibility settings.
87// However, a 'visibility' attribute counts as a 'type_visibility'
88// attribute on any declaration that only has the former.
89//
90// The visibility of a "secondary" entity, like a template argument,
91// is computed using the kind of that entity, not the kind of the
92// primary entity for which we are computing visibility. For example,
93// the visibility of a specialization of either of these templates:
94// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
95// template <class T, bool (&compare)(T, X)> class matcher;
96// is restricted according to the type visibility of the argument 'T',
97// the type visibility of 'bool(&)(T,X)', and the value visibility of
98// the argument function 'compare'. That 'has_match' is a value
99// and 'matcher' is a type only matters when looking for attributes
100// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +0000101
John McCall5f46c482013-02-21 23:42:58 +0000102const unsigned IgnoreExplicitVisibilityBit = 2;
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000103const unsigned IgnoreAllVisibilityBit = 4;
John McCall5f46c482013-02-21 23:42:58 +0000104
John McCalldf25c432013-02-16 00:17:33 +0000105/// Kinds of LV computation. The linkage side of the computation is
106/// always the same, but different things can change how visibility is
107/// computed.
108enum LVComputationKind {
John McCall5f46c482013-02-21 23:42:58 +0000109 /// Do an LV computation for, ultimately, a type.
110 /// Visibility may be restricted by type visibility settings and
111 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000112 LVForType = NamedDecl::VisibilityForType,
John McCalldf25c432013-02-16 00:17:33 +0000113
John McCall5f46c482013-02-21 23:42:58 +0000114 /// Do an LV computation for, ultimately, a non-type declaration.
115 /// Visibility may be restricted by value visibility settings and
116 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000117 LVForValue = NamedDecl::VisibilityForValue,
118
John McCall5f46c482013-02-21 23:42:58 +0000119 /// Do an LV computation for, ultimately, a type that already has
120 /// some sort of explicit visibility. Visibility may only be
121 /// restricted by the visibility of template arguments.
122 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
John McCalld041a9b2013-02-20 01:54:26 +0000123
John McCall5f46c482013-02-21 23:42:58 +0000124 /// Do an LV computation for, ultimately, a non-type declaration
125 /// that already has some sort of explicit visibility. Visibility
126 /// may only be restricted by the visibility of template arguments.
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000127 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
128
129 /// Do an LV computation when we only care about the linkage.
130 LVForLinkageOnly =
131 LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
John McCalldf25c432013-02-16 00:17:33 +0000132};
133
John McCalld041a9b2013-02-20 01:54:26 +0000134/// Does this computation kind permit us to consider additional
135/// visibility settings from attributes and the like?
136static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000137 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
John McCalld041a9b2013-02-20 01:54:26 +0000138}
139
140/// Given an LVComputationKind, return one of the same type/value sort
141/// that records that it already has explicit visibility.
142static LVComputationKind
143withExplicitVisibilityAlready(LVComputationKind oldKind) {
144 LVComputationKind newKind =
John McCall5f46c482013-02-21 23:42:58 +0000145 static_cast<LVComputationKind>(unsigned(oldKind) |
146 IgnoreExplicitVisibilityBit);
John McCalld041a9b2013-02-20 01:54:26 +0000147 assert(oldKind != LVForType || newKind == LVForExplicitType);
148 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
149 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
150 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
151 return newKind;
152}
153
David Blaikie05785d12013-02-20 22:23:23 +0000154static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
155 LVComputationKind kind) {
John McCalld041a9b2013-02-20 01:54:26 +0000156 assert(!hasExplicitVisibilityAlready(kind) &&
157 "asking for explicit visibility when we shouldn't be");
158 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
159}
160
John McCalldf25c432013-02-16 00:17:33 +0000161/// Is the given declaration a "type" or a "value" for the purposes of
162/// visibility computation?
163static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000164 return isa<TypeDecl>(D) ||
165 isa<ClassTemplateDecl>(D) ||
166 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000167}
168
John McCall5f46c482013-02-21 23:42:58 +0000169/// Does the given declaration have member specialization information,
170/// and if so, is it an explicit specialization?
171template <class T> static typename
Benjamin Kramered2f4762014-03-07 14:30:23 +0000172std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-02-21 23:42:58 +0000173isExplicitMemberSpecialization(const T *D) {
174 if (const MemberSpecializationInfo *member =
175 D->getMemberSpecializationInfo()) {
176 return member->isExplicitSpecialization();
177 }
178 return false;
179}
180
181/// For templates, this question is easier: a member template can't be
182/// explicitly instantiated, so there's a single bit indicating whether
183/// or not this is an explicit member specialization.
184static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
185 return D->isMemberSpecialization();
186}
187
John McCalld041a9b2013-02-20 01:54:26 +0000188/// Given a visibility attribute, return the explicit visibility
189/// associated with it.
190template <class T>
191static Visibility getVisibilityFromAttr(const T *attr) {
192 switch (attr->getVisibility()) {
193 case T::Default:
194 return DefaultVisibility;
195 case T::Hidden:
196 return HiddenVisibility;
197 case T::Protected:
198 return ProtectedVisibility;
199 }
200 llvm_unreachable("bad visibility kind");
201}
202
John McCalldf25c432013-02-16 00:17:33 +0000203/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000204static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000205 NamedDecl::ExplicitVisibilityKind kind) {
206 // If we're ultimately computing the visibility of a type, look for
207 // a 'type_visibility' attribute before looking for 'visibility'.
208 if (kind == NamedDecl::VisibilityForType) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000209 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000210 return getVisibilityFromAttr(A);
211 }
212 }
213
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000214 // If this declaration has an explicit visibility attribute, use it.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000215 if (const auto *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000216 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000217 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000218
219 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
220 // implies visibility(default).
Douglas Gregore8bbc122011-09-02 00:18:52 +0000221 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000222 for (const auto *A : D->specific_attrs<AvailabilityAttr>())
Manman Renccf25bb2016-06-28 20:55:30 +0000223 if (A->getPlatform()->getName().equals("macos"))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000224 return DefaultVisibility;
225 }
226
David Blaikie7a30dc52013-02-21 01:47:18 +0000227 return None;
John McCall457a04e2010-10-22 21:05:15 +0000228}
229
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000230static LinkageInfo
231getLVForType(const Type &T, LVComputationKind computation) {
232 if (computation == LVForLinkageOnly)
233 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
234 return T.getLinkageAndVisibility();
235}
236
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000237/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000238/// template parameter list. For visibility purposes, template
239/// parameters are part of the signature of a template.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000240static LinkageInfo
David Majnemerc7b85c42014-04-23 05:16:48 +0000241getLVForTemplateParameterList(const TemplateParameterList *Params,
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000242 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000243 LinkageInfo LV;
David Majnemerc7b85c42014-04-23 05:16:48 +0000244 for (const NamedDecl *P : *Params) {
John McCalldf25c432013-02-16 00:17:33 +0000245 // Template type parameters are the most common and never
246 // contribute to visibility, pack or not.
David Majnemerc7b85c42014-04-23 05:16:48 +0000247 if (isa<TemplateTypeParmDecl>(P))
John McCalldf25c432013-02-16 00:17:33 +0000248 continue;
249
250 // Non-type template parameters can be restricted by the value type, e.g.
251 // template <enum X> class A { ... };
252 // We have to be careful here, though, because we can be dealing with
253 // dependent types.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000254 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
John McCalldf25c432013-02-16 00:17:33 +0000255 // Handle the non-pack case first.
256 if (!NTTP->isExpandedParameterPack()) {
257 if (!NTTP->getType()->isDependentType()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000258 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000259 }
260 continue;
261 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000262
John McCalldf25c432013-02-16 00:17:33 +0000263 // Look at all the types in an expanded pack.
264 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
265 QualType type = NTTP->getExpansionType(i);
266 if (!type->isDependentType())
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000267 LV.merge(type->getLinkageAndVisibility());
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000268 }
John McCalldf25c432013-02-16 00:17:33 +0000269 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000270 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000271
John McCalldf25c432013-02-16 00:17:33 +0000272 // Template template parameters can be restricted by their
273 // template parameters, recursively.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000274 const auto *TTP = cast<TemplateTemplateParmDecl>(P);
John McCalldf25c432013-02-16 00:17:33 +0000275
276 // Handle the non-pack case first.
277 if (!TTP->isExpandedParameterPack()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000278 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
279 computation));
John McCalldf25c432013-02-16 00:17:33 +0000280 continue;
281 }
282
283 // Look at all expansions in an expanded pack.
284 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
285 i != n; ++i) {
286 LV.merge(getLVForTemplateParameterList(
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000287 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000288 }
289 }
290
John McCall457a04e2010-10-22 21:05:15 +0000291 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000292}
293
Rafael Espindola19de5612013-01-12 06:42:30 +0000294/// getLVForDecl - Get the linkage and visibility for the given declaration.
John McCalldf25c432013-02-16 00:17:33 +0000295static LinkageInfo getLVForDecl(const NamedDecl *D,
296 LVComputationKind computation);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000297
Eli Friedman7e346a82013-07-01 20:22:57 +0000298static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
Craig Topper36250ad2014-05-12 05:36:57 +0000299 const Decl *Ret = nullptr;
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000300 const DeclContext *DC = D->getDeclContext();
301 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman7e346a82013-07-01 20:22:57 +0000302 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
303 Ret = cast<Decl>(DC);
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000304 DC = DC->getParent();
305 }
306 return Ret;
307}
308
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000309/// \brief Get the most restrictive linkage for the types and
310/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000311///
312/// Note that we don't take an LVComputationKind because we always
313/// want to honor the visibility of template arguments in the same way.
David Majnemerc7b85c42014-04-23 05:16:48 +0000314static LinkageInfo getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
315 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000316 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000317
David Majnemerc7b85c42014-04-23 05:16:48 +0000318 for (const TemplateArgument &Arg : Args) {
319 switch (Arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000320 case TemplateArgument::Null:
321 case TemplateArgument::Integral:
322 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000323 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000324
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000325 case TemplateArgument::Type:
David Majnemerc7b85c42014-04-23 05:16:48 +0000326 LV.merge(getLVForType(*Arg.getAsType(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000327 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000328
329 case TemplateArgument::Declaration:
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000330 if (const auto *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
John McCalldf25c432013-02-16 00:17:33 +0000331 assert(!usesTypeVisibility(ND));
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000332 LV.merge(getLVForDecl(ND, computation));
John McCalldf25c432013-02-16 00:17:33 +0000333 }
334 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +0000335
336 case TemplateArgument::NullPtr:
David Majnemerc7b85c42014-04-23 05:16:48 +0000337 LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility());
John McCalldf25c432013-02-16 00:17:33 +0000338 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000339
340 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000341 case TemplateArgument::TemplateExpansion:
David Majnemerc7b85c42014-04-23 05:16:48 +0000342 if (TemplateDecl *Template =
343 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000344 LV.merge(getLVForDecl(Template, computation));
John McCalldf25c432013-02-16 00:17:33 +0000345 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000346
347 case TemplateArgument::Pack:
David Majnemerc7b85c42014-04-23 05:16:48 +0000348 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000349 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000350 }
John McCalldf25c432013-02-16 00:17:33 +0000351 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000352 }
353
John McCall457a04e2010-10-22 21:05:15 +0000354 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000355}
356
Rafael Espindola2f869a32012-01-14 00:30:36 +0000357static LinkageInfo
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000358getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
359 LVComputationKind computation) {
360 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall8823c652010-08-13 08:35:10 +0000361}
362
John McCall5f46c482013-02-21 23:42:58 +0000363static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
364 const FunctionTemplateSpecializationInfo *specInfo) {
365 // Include visibility from the template parameters and arguments
366 // only if this is not an explicit instantiation or specialization
367 // with direct explicit visibility. (Implicit instantiations won't
368 // have a direct attribute.)
369 if (!specInfo->isExplicitInstantiationOrSpecialization())
370 return true;
371
372 return !fn->hasAttr<VisibilityAttr>();
373}
374
John McCalldf25c432013-02-16 00:17:33 +0000375/// Merge in template-related linkage and visibility for the given
376/// function template specialization.
377///
378/// We don't need a computation kind here because we can assume
379/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000380///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000381/// \param[out] LV the computation to use for the parent
John McCall5f46c482013-02-21 23:42:58 +0000382static void
383mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000384 const FunctionTemplateSpecializationInfo *specInfo,
385 LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000386 bool considerVisibility =
387 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000388
389 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000390 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000391 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000392 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000393 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
394
395 // Merge information from the template arguments.
396 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000397 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCalldf25c432013-02-16 00:17:33 +0000398 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000399}
400
John McCall5f46c482013-02-21 23:42:58 +0000401/// Does the given declaration have a direct visibility attribute
402/// that would match the given rules?
403static bool hasDirectVisibilityAttribute(const NamedDecl *D,
404 LVComputationKind computation) {
405 switch (computation) {
406 case LVForType:
407 case LVForExplicitType:
408 if (D->hasAttr<TypeVisibilityAttr>())
409 return true;
410 // fallthrough
411 case LVForValue:
412 case LVForExplicitValue:
413 if (D->hasAttr<VisibilityAttr>())
414 return true;
415 return false;
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000416 case LVForLinkageOnly:
417 return false;
John McCall5f46c482013-02-21 23:42:58 +0000418 }
419 llvm_unreachable("bad visibility computation kind");
420}
421
John McCalld041a9b2013-02-20 01:54:26 +0000422/// Should we consider visibility associated with the template
423/// arguments and parameters of the given class template specialization?
424static bool shouldConsiderTemplateVisibility(
425 const ClassTemplateSpecializationDecl *spec,
426 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000427 // Include visibility from the template parameters and arguments
428 // only if this is not an explicit instantiation or specialization
429 // with direct explicit visibility (and note that implicit
430 // instantiations won't have a direct attribute).
431 //
432 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000433 // for an explicit specialization when computing the visibility of a
434 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000435 //
436 // This is a bit complex; let's unpack it.
437 //
438 // An explicit class specialization is an independent, top-level
439 // declaration. As such, if it or any of its members has an
440 // explicit visibility attribute, that must directly express the
441 // user's intent, and we should honor it. The same logic applies to
442 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000443
444 // Fast path: if this is not an explicit instantiation or
445 // specialization, we always want to consider template-related
446 // visibility restrictions.
447 if (!spec->isExplicitInstantiationOrSpecialization())
448 return true;
449
450 // This is the 'member thereof' check.
451 if (spec->isExplicitSpecialization() &&
452 hasExplicitVisibilityAlready(computation))
453 return false;
454
John McCall5f46c482013-02-21 23:42:58 +0000455 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000456}
457
458/// Merge in template-related linkage and visibility for the given
459/// class template specialization.
460static void mergeTemplateLV(LinkageInfo &LV,
461 const ClassTemplateSpecializationDecl *spec,
462 LVComputationKind computation) {
463 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000464
465 // Merge information from the template parameters, but ignore
466 // visibility if we're only considering template arguments.
467
John McCalld041a9b2013-02-20 01:54:26 +0000468 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000469 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000470 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000471 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000472 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000473
474 // Merge information from the template arguments. We ignore
475 // template-argument visibility if we've got an explicit
476 // instantiation with a visibility attribute.
477 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000478 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000479 if (considerVisibility)
480 LV.mergeVisibility(argsLV);
481 LV.mergeExternalVisibility(argsLV);
John McCallb8c604a2011-06-27 23:06:04 +0000482}
483
Larisse Voufo5899e192014-07-02 23:08:34 +0000484/// Should we consider visibility associated with the template
485/// arguments and parameters of the given variable template
486/// specialization? As usual, follow class template specialization
487/// logic up to initialization.
488static bool shouldConsiderTemplateVisibility(
489 const VarTemplateSpecializationDecl *spec,
490 LVComputationKind computation) {
491 // Include visibility from the template parameters and arguments
492 // only if this is not an explicit instantiation or specialization
493 // with direct explicit visibility (and note that implicit
494 // instantiations won't have a direct attribute).
495 if (!spec->isExplicitInstantiationOrSpecialization())
496 return true;
497
498 // An explicit variable specialization is an independent, top-level
499 // declaration. As such, if it has an explicit visibility attribute,
500 // that must directly express the user's intent, and we should honor
501 // it.
502 if (spec->isExplicitSpecialization() &&
503 hasExplicitVisibilityAlready(computation))
504 return false;
505
506 return !hasDirectVisibilityAttribute(spec, computation);
507}
508
509/// Merge in template-related linkage and visibility for the given
510/// variable template specialization. As usual, follow class template
511/// specialization logic up to initialization.
512static void mergeTemplateLV(LinkageInfo &LV,
513 const VarTemplateSpecializationDecl *spec,
514 LVComputationKind computation) {
515 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
516
517 // Merge information from the template parameters, but ignore
518 // visibility if we're only considering template arguments.
519
520 VarTemplateDecl *temp = spec->getSpecializedTemplate();
521 LinkageInfo tempLV =
522 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
523 LV.mergeMaybeWithVisibility(tempLV,
524 considerVisibility && !hasExplicitVisibilityAlready(computation));
525
526 // Merge information from the template arguments. We ignore
527 // template-argument visibility if we've got an explicit
528 // instantiation with a visibility attribute.
529 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
530 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
531 if (considerVisibility)
532 LV.mergeVisibility(argsLV);
533 LV.mergeExternalVisibility(argsLV);
534}
535
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000536static bool useInlineVisibilityHidden(const NamedDecl *D) {
537 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000538 const LangOptions &Opts = D->getASTContext().getLangOpts();
539 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000540 return false;
541
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000542 const auto *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000543 if (!FD)
544 return false;
545
546 TemplateSpecializationKind TSK = TSK_Undeclared;
547 if (FunctionTemplateSpecializationInfo *spec
548 = FD->getTemplateSpecializationInfo()) {
549 TSK = spec->getTemplateSpecializationKind();
550 } else if (MemberSpecializationInfo *MSI =
551 FD->getMemberSpecializationInfo()) {
552 TSK = MSI->getTemplateSpecializationKind();
553 }
554
Craig Topper36250ad2014-05-12 05:36:57 +0000555 const FunctionDecl *Def = nullptr;
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000556 // InlineVisibilityHidden only applies to definitions, and
557 // isInlined() only gives meaningful answers on definitions
558 // anyway.
559 return TSK != TSK_ExplicitInstantiationDeclaration &&
560 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000561 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000562}
563
Rafael Espindola593537a2013-05-05 20:15:21 +0000564template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000565 const T *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +0000566 return First->isInExternCContext();
Rafael Espindolaf4187652013-02-14 01:18:37 +0000567}
568
Richard Smith03c05032014-02-17 23:34:47 +0000569static bool isSingleLineLanguageLinkage(const Decl &D) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000570 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Richard Smith03c05032014-02-17 23:34:47 +0000571 if (!SD->hasBraces())
Rafael Espindola327be3c2013-04-26 01:30:23 +0000572 return true;
573 return false;
574}
575
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000576static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
John McCalldf25c432013-02-16 00:17:33 +0000577 LVComputationKind computation) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000578 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000579 "Not a name having namespace scope");
580 ASTContext &Context = D->getASTContext();
581
582 // C++ [basic.link]p3:
583 // A name having namespace scope (3.3.6) has internal linkage if it
584 // is the name of
585 // - an object, reference, function or function template that is
586 // explicitly declared static; or,
587 // (This bullet corresponds to C99 6.2.2p3.)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000588 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000589 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000590 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000591 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000592
Richard Smith62f19e72016-06-25 00:15:56 +0000593 // - a non-inline, non-volatile object or reference that is explicitly
594 // declared const or constexpr and neither explicitly declared extern
595 // nor previously declared to have external linkage; or (there is no
596 // 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() &&
Richard Smith62f19e72016-06-25 00:15:56 +0000599 !Var->getType().isVolatileQualified() &&
600 !Var->isInline()) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000601 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000602 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000603 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000604
605 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000606 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000607 !isSingleLineLanguageLinkage(*Var))
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000608 return LinkageInfo::internal();
609 }
610
611 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
612 PrevVar = PrevVar->getPreviousDecl()) {
613 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
614 Var->getStorageClass() == SC_None)
615 return PrevVar->getLinkageAndVisibility();
616 // Explicitly declared static.
617 if (PrevVar->getStorageClass() == SC_Static)
618 return LinkageInfo::internal();
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000619 }
Alp Tokera2794f92014-01-22 07:29:52 +0000620 } else if (const FunctionDecl *Function = D->getAsFunction()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000621 // C++ [temp]p4:
622 // A non-member function template can have internal linkage; any
623 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000624
625 // Explicitly declared static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000626 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000627 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
David Majnemer18fac3b2014-12-10 22:58:14 +0000628 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
629 // - a data member of an anonymous union.
630 const VarDecl *VD = IFD->getVarDecl();
631 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
632 return getLVForNamespaceScopeDecl(VD, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000633 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000634 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000635
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000636 if (D->isInAnonymousNamespace()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000637 const auto *Var = dyn_cast<VarDecl>(D);
638 const auto *Func = dyn_cast<FunctionDecl>(D);
Richard Smith97135cc2015-11-12 22:19:45 +0000639 // FIXME: In C++11 onwards, anonymous namespaces should give decls
640 // within them internal linkage, not unique external linkage.
Rafael Espindola593537a2013-05-05 20:15:21 +0000641 if ((!Var || !isFirstInExternCContext(Var)) &&
642 (!Func || !isFirstInExternCContext(Func)))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000643 return LinkageInfo::uniqueExternal();
644 }
John McCallb7139c42010-10-28 04:18:25 +0000645
John McCall457a04e2010-10-22 21:05:15 +0000646 // Set up the defaults.
647
648 // C99 6.2.2p5:
649 // If the declaration of an identifier for an object has file
650 // scope and no storage-class specifier, its linkage is
651 // external.
John McCallc273f242010-10-30 11:50:40 +0000652 LinkageInfo LV;
653
John McCalld041a9b2013-02-20 01:54:26 +0000654 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000655 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000656 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000657 } else {
658 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000659 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000660 for (const DeclContext *DC = D->getDeclContext();
661 !isa<TranslationUnitDecl>(DC);
662 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000663 const auto *ND = dyn_cast<NamespaceDecl>(DC);
Rafael Espindola78158af2012-04-16 18:46:26 +0000664 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000665 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000666 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000667 break;
668 }
669 }
670 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000671
John McCalldf25c432013-02-16 00:17:33 +0000672 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000673 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000674 // Use global type/value visibility as appropriate.
675 Visibility globalVisibility;
676 if (computation == LVForValue) {
Larisse Voufo404e1422015-02-04 02:34:32 +0000677 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
John McCallb4a99d32013-02-19 01:57:35 +0000678 } else {
679 assert(computation == LVForType);
680 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
681 }
682 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000683
684 // If we're paying attention to global visibility, apply
685 // -finline-visibility-hidden if this is an inline method.
686 if (useInlineVisibilityHidden(D))
687 LV.mergeVisibility(HiddenVisibility, true);
688 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000689 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000690
Douglas Gregorf73b2822009-11-25 22:24:25 +0000691 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000692
Douglas Gregorf73b2822009-11-25 22:24:25 +0000693 // A name having namespace scope has external linkage if it is the
694 // name of
695 //
696 // - an object or reference, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000697 if (const auto *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000698 // GCC applies the following optimization to variables and static
699 // data members, but not to functions:
700 //
John McCall457a04e2010-10-22 21:05:15 +0000701 // Modify the variable's LV by the LV of its type unless this is
702 // C or extern "C". This follows from [basic.link]p9:
703 // A type without linkage shall not be used as the type of a
704 // variable or function with external linkage unless
705 // - the entity has C language linkage, or
706 // - the entity is declared within an unnamed namespace, or
707 // - the entity is not used or is defined in the same
708 // translation unit.
709 // and [basic.link]p10:
710 // ...the types specified by all declarations referring to a
711 // given variable or function shall be identical...
712 // C does not have an equivalent rule.
713 //
John McCall5fe84122010-10-26 04:59:26 +0000714 // Ignore this if we've got an explicit attribute; the user
715 // probably knows what they're doing.
716 //
John McCall457a04e2010-10-22 21:05:15 +0000717 // Note that we don't want to make the variable non-external
718 // because of this, but unique-external linkage suits us.
Rafael Espindola593537a2013-05-05 20:15:21 +0000719 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000720 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Rafael Espindola4a5da442013-02-27 02:56:45 +0000721 if (TypeLV.getLinkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000722 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000723 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000724 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000725 }
726
John McCall23032652010-11-02 18:38:13 +0000727 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000728 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000729
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000730 // Note that Sema::MergeVarDecl already takes care of implementing
731 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
732 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000733
Larisse Voufo5899e192014-07-02 23:08:34 +0000734 // As per function and class template specializations (below),
735 // consider LV for the template and template arguments. We're at file
736 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000737 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000738 mergeTemplateLV(LV, spec, computation);
739 }
740
Douglas Gregorf73b2822009-11-25 22:24:25 +0000741 // - a function, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000742 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000743 // In theory, we can modify the function's LV by the LV of its
744 // type unless it has C linkage (see comment above about variables
745 // for justification). In practice, GCC doesn't do this, so it's
746 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000747
John McCall23032652010-11-02 18:38:13 +0000748 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000749 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000750
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000751 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
752 // merging storage classes and visibility attributes, so we don't have to
753 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000754
John McCallf768aa72011-02-10 06:50:24 +0000755 // In C++, then if the type of the function uses a type with
756 // unique-external linkage, it's not legally usable from outside
757 // this translation unit. However, we should use the C linkage
758 // rules instead for extern "C" declarations.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000759 if (Context.getLangOpts().CPlusPlus &&
Richard Smith50f4afc2013-05-12 23:17:59 +0000760 !Function->isInExternCContext()) {
761 // Only look at the type-as-written. If this function has an auto-deduced
762 // return type, we can't compute the linkage of that type because it could
763 // require looking at the linkage of this function, and we don't need this
764 // for correctness because the type is not part of the function's
765 // signature.
Faisal Valid2598e92013-10-08 04:15:04 +0000766 // FIXME: This is a hack. We should be able to solve this circularity and
767 // the one in getLVForClassMember for Functions some other way.
Richard Smith50f4afc2013-05-12 23:17:59 +0000768 QualType TypeAsWritten = Function->getType();
769 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
770 TypeAsWritten = TSI->getType();
771 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
772 return LinkageInfo::uniqueExternal();
773 }
John McCallf768aa72011-02-10 06:50:24 +0000774
John McCall5f46c482013-02-21 23:42:58 +0000775 // Consider LV from the template and the template arguments.
776 // We're at file scope, so we do not need to worry about nested
777 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000778 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000779 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000780 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000781 }
782
Douglas Gregorf73b2822009-11-25 22:24:25 +0000783 // - a named class (Clause 9), or an unnamed class defined in a
784 // typedef declaration in which the class has the typedef name
785 // for linkage purposes (7.1.3); or
786 // - a named enumeration (7.2), or an unnamed enumeration
787 // defined in a typedef declaration in which the enumeration
788 // has the typedef name for linkage purposes (7.1.3); or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000789 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000790 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000791 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000792 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000793
John McCall457a04e2010-10-22 21:05:15 +0000794 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000795 // linkage of the template and template arguments. We're at file
796 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000797 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000798 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000799 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000800
801 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000802 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000803 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000804 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000805 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000806 return LinkageInfo::none();
807 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000808
809 // - a template, unless it is a function template that has
810 // internal linkage (Clause 14);
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000811 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000812 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000813 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000814 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000815 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
816
Douglas Gregorf73b2822009-11-25 22:24:25 +0000817 // - a namespace (7.3), unless it is declared within an unnamed
818 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000819 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
820 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000821
John McCall457a04e2010-10-22 21:05:15 +0000822 // By extension, we assign external linkage to Objective-C
823 // interfaces.
824 } else if (isa<ObjCInterfaceDecl>(D)) {
825 // fallout
826
Richard Smith97135cc2015-11-12 22:19:45 +0000827 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
828 // A typedef declaration has linkage if it gives a type a name for
829 // linkage purposes.
830 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
831 return LinkageInfo::none();
832
John McCall457a04e2010-10-22 21:05:15 +0000833 // Everything not covered here has no linkage.
834 } else {
John McCallc273f242010-10-30 11:50:40 +0000835 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000836 }
837
838 // If we ended up with non-external linkage, visibility should
839 // always be default.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000840 if (LV.getLinkage() != ExternalLinkage)
841 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000842
John McCall457a04e2010-10-22 21:05:15 +0000843 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000844}
845
John McCalldf25c432013-02-16 00:17:33 +0000846static LinkageInfo getLVForClassMember(const NamedDecl *D,
847 LVComputationKind computation) {
John McCall457a04e2010-10-22 21:05:15 +0000848 // Only certain class members have linkage. Note that fields don't
849 // really have linkage, but it's convenient to say they do for the
850 // purposes of calculating linkage of pointer-to-data-member
851 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000852 //
853 // Templates also don't officially have linkage, but since we ignore
854 // the C++ standard and look at template arguments when determining
855 // linkage and visibility of a template specialization, we might hit
856 // a template template argument that way. If we do, we need to
857 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000858 if (!(isa<CXXMethodDecl>(D) ||
859 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000860 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000861 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000862 isa<TagDecl>(D) ||
863 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000864 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000865
John McCall07072662010-11-02 01:45:15 +0000866 LinkageInfo LV;
867
John McCall07072662010-11-02 01:45:15 +0000868 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000869 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000870 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000871 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000872 // If we're paying attention to global visibility, apply
873 // -finline-visibility-hidden if this is an inline method.
874 //
875 // Note that we do this before merging information about
876 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000877 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000878 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000879 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000880
881 // If this class member has an explicit visibility attribute, the only
882 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000883 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000884 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000885 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000886 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000887
John McCall5f46c482013-02-21 23:42:58 +0000888 LinkageInfo classLV =
889 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
John McCall8823c652010-08-13 08:35:10 +0000890 // If the class already has unique-external linkage, we can't improve.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000891 if (classLV.getLinkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000892 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000893
Rafael Espindolae6190db2013-05-28 02:22:10 +0000894 if (!isExternallyVisible(classLV.getLinkage()))
895 return LinkageInfo::none();
896
897
John McCall5f46c482013-02-21 23:42:58 +0000898 // Otherwise, don't merge in classLV yet, because in certain cases
899 // we need to completely ignore the visibility from it.
900
901 // Specifically, if this decl exists and has an explicit attribute.
Craig Topper36250ad2014-05-12 05:36:57 +0000902 const NamedDecl *explicitSpecSuppressor = nullptr;
John McCall5f46c482013-02-21 23:42:58 +0000903
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000904 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000905 // If the type of the function uses a type with unique-external
906 // linkage, it's not legally usable from outside this translation unit.
Nico Weber38267342015-04-22 03:44:51 +0000907 // But only look at the type-as-written. If this function has an
908 // auto-deduced return type, we can't compute the linkage of that type
909 // because it could require looking at the linkage of this function, and we
910 // don't need this for correctness because the type is not part of the
911 // function's signature.
912 // FIXME: This is a hack. We should be able to solve this circularity and
913 // the one in getLVForNamespaceScopeDecl for Functions some other way.
Faisal Valid2598e92013-10-08 04:15:04 +0000914 {
915 QualType TypeAsWritten = MD->getType();
916 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
917 TypeAsWritten = TSI->getType();
918 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
919 return LinkageInfo::uniqueExternal();
920 }
John McCall457a04e2010-10-22 21:05:15 +0000921 // If this is a method template specialization, use the linkage for
922 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000923 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000924 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000925 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000926 if (spec->isExplicitSpecialization()) {
927 explicitSpecSuppressor = MD;
928 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
929 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
930 }
931 } else if (isExplicitMemberSpecialization(MD)) {
932 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000933 }
John McCall457a04e2010-10-22 21:05:15 +0000934
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000935 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
936 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000937 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000938 if (spec->isExplicitSpecialization()) {
939 explicitSpecSuppressor = spec;
940 } else {
941 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
942 if (isExplicitMemberSpecialization(temp)) {
943 explicitSpecSuppressor = temp->getTemplatedDecl();
944 }
945 }
946 } else if (isExplicitMemberSpecialization(RD)) {
947 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000948 }
949
John McCall37bb6c92010-10-29 22:22:43 +0000950 // Static data members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000951 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
952 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
Larisse Voufo5899e192014-07-02 23:08:34 +0000953 mergeTemplateLV(LV, spec, computation);
954
John McCall36cd5cc2010-10-30 09:18:49 +0000955 // Modify the variable's linkage by its type, but ignore the
956 // type's visibility unless it's a definition.
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000957 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000958 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
959 LV.mergeVisibility(typeLV);
960 LV.mergeExternalVisibility(typeLV);
John McCall5f46c482013-02-21 23:42:58 +0000961
962 if (isExplicitMemberSpecialization(VD)) {
963 explicitSpecSuppressor = VD;
964 }
John McCalldf25c432013-02-16 00:17:33 +0000965
966 // Template members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000967 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +0000968 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +0000969 (!LV.isVisibilityExplicit() &&
970 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000971 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000972 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000973 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000974 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +0000975
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000976 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
John McCall5f46c482013-02-21 23:42:58 +0000977 if (isExplicitMemberSpecialization(redeclTemp)) {
978 explicitSpecSuppressor = temp->getTemplatedDecl();
979 }
980 }
John McCall37bb6c92010-10-29 22:22:43 +0000981 }
982
John McCall5f46c482013-02-21 23:42:58 +0000983 // We should never be looking for an attribute directly on a template.
984 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
985
986 // If this member is an explicit member specialization, and it has
987 // an explicit attribute, ignore visibility from the parent.
988 bool considerClassVisibility = true;
989 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +0000990 // optimization: hasDVA() is true only with explicit visibility.
991 LV.isVisibilityExplicit() &&
992 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +0000993 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
994 considerClassVisibility = false;
995 }
996
997 // Finally, merge in information from the class.
998 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +0000999 return LV;
John McCall8823c652010-08-13 08:35:10 +00001000}
1001
David Blaikie68e081d2011-12-20 02:48:34 +00001002void NamedDecl::anchor() { }
1003
Rafael Espindolaecf63c62013-05-29 04:55:30 +00001004static LinkageInfo computeLVForDecl(const NamedDecl *D,
1005 LVComputationKind computation);
1006
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001007bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001008 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001009 return true;
John McCalld396b972011-02-08 19:01:05 +00001010
Rafael Espindolaecf63c62013-05-29 04:55:30 +00001011 return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
Rafael Espindola50df3a02013-05-25 17:16:20 +00001012 getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +00001013}
1014
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001015ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1016 StringRef name = getName();
1017 if (name.empty()) return SFF_None;
1018
1019 if (name.front() == 'C')
1020 if (name == "CFStringCreateWithFormat" ||
1021 name == "CFStringCreateWithFormatAndArguments" ||
1022 name == "CFStringAppendFormat" ||
1023 name == "CFStringAppendFormatAndArguments")
1024 return SFF_CFString;
1025 return SFF_None;
1026}
1027
Rafael Espindola3ae00052013-05-13 00:12:11 +00001028Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +00001029 // We don't care about visibility here, so ask for the cheapest
1030 // possible visibility analysis.
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001031 return getLVForDecl(this, LVForLinkageOnly).getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001032}
1033
John McCallc273f242010-10-30 11:50:40 +00001034LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCalldf25c432013-02-16 00:17:33 +00001035 LVComputationKind computation =
1036 (usesTypeVisibility(this) ? LVForType : LVForValue);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001037 return getLVForDecl(this, computation);
John McCall033caa52010-10-29 00:29:13 +00001038}
Ted Kremenek926d8602010-04-20 23:15:35 +00001039
Rafael Espindola9ad61122013-11-26 16:09:08 +00001040static Optional<Visibility>
1041getExplicitVisibilityAux(const NamedDecl *ND,
1042 NamedDecl::ExplicitVisibilityKind kind,
1043 bool IsMostRecent) {
1044 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1045
Rafael Espindola3a52c442013-02-26 19:33:14 +00001046 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001047 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001048 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001049
Rafael Espindola3a52c442013-02-26 19:33:14 +00001050 // If this is a member class of a specialization of a class template
1051 // and the corresponding decl has explicit visibility, use that.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001052 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +00001053 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1054 if (InstantiatedFrom)
1055 return getVisibilityOf(InstantiatedFrom, kind);
1056 }
1057
1058 // If there wasn't explicit visibility there, and this is a
1059 // specialization of a class template, check for visibility
1060 // on the pattern.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001061 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001062 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1063 kind);
1064
1065 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +00001066 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +00001067 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1068 if (MostRecent != ND)
1069 return getExplicitVisibilityAux(MostRecent, kind, true);
1070 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001071
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001072 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +00001073 if (Var->isStaticDataMember()) {
1074 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1075 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001076 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +00001077 }
1078
David Majnemer35b02bc2014-04-29 07:32:26 +00001079 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1080 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1081 kind);
1082
David Blaikie7a30dc52013-02-21 01:47:18 +00001083 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +00001084 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001085 // Also handle function template specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001086 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001087 // If the function is a specialization of a template with an
1088 // explicit visibility attribute, use that.
1089 if (FunctionTemplateSpecializationInfo *templateInfo
1090 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +00001091 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1092 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001093
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001094 // If the function is a member of a specialization of a class template
1095 // and the corresponding decl has explicit visibility, use that.
1096 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1097 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001098 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001099
David Blaikie7a30dc52013-02-21 01:47:18 +00001100 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001101 }
1102
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001103 // The visibility of a template is stored in the templated decl.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001104 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001105 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001106
David Blaikie7a30dc52013-02-21 01:47:18 +00001107 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001108}
1109
Rafael Espindola9ad61122013-11-26 16:09:08 +00001110Optional<Visibility>
1111NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1112 return getExplicitVisibilityAux(this, kind, false);
1113}
1114
Eli Friedman7e346a82013-07-01 20:22:57 +00001115static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
1116 LVComputationKind computation) {
1117 // This lambda has its linkage/visibility determined by its owner.
1118 if (ContextDecl) {
1119 if (isa<ParmVarDecl>(ContextDecl))
1120 DC = ContextDecl->getDeclContext()->getRedeclContext();
1121 else
1122 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1123 }
Faisal Vali98b8e182013-09-29 20:27:06 +00001124
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001125 if (const auto *ND = dyn_cast<NamedDecl>(DC))
Eli Friedman7e346a82013-07-01 20:22:57 +00001126 return getLVForDecl(ND, computation);
Faisal Vali98b8e182013-09-29 20:27:06 +00001127
Eli Friedman7e346a82013-07-01 20:22:57 +00001128 return LinkageInfo::external();
1129}
1130
John McCalldf25c432013-02-16 00:17:33 +00001131static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1132 LVComputationKind computation) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001133 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001134 if (Function->isInAnonymousNamespace() &&
Rafael Espindola593537a2013-05-05 20:15:21 +00001135 !Function->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001136 return LinkageInfo::uniqueExternal();
1137
1138 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001139 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCalldf25c432013-02-16 00:17:33 +00001140 return LinkageInfo::internal();
1141
1142 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001143 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001144 if (Optional<Visibility> Vis =
1145 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001146 LV.mergeVisibility(*Vis, true);
1147 }
1148
1149 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1150 // merging storage classes and visibility attributes, so we don't have to
1151 // look at previous decls in here.
1152
1153 return LV;
1154 }
1155
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001156 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001157 if (Var->hasExternalStorage()) {
Rafael Espindola593537a2013-05-05 20:15:21 +00001158 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001159 return LinkageInfo::uniqueExternal();
1160
John McCalldf25c432013-02-16 00:17:33 +00001161 LinkageInfo LV;
1162 if (Var->getStorageClass() == SC_PrivateExtern)
1163 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001164 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001165 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001166 LV.mergeVisibility(*Vis, true);
1167 }
1168
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001169 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1170 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1171 if (PrevLV.getLinkage())
1172 LV.setLinkage(PrevLV.getLinkage());
1173 LV.mergeVisibility(PrevLV);
1174 }
1175
John McCalldf25c432013-02-16 00:17:33 +00001176 return LV;
1177 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001178
1179 if (!Var->isStaticLocal())
1180 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001181 }
1182
Rafael Espindolaa4184182013-06-17 20:04:51 +00001183 ASTContext &Context = D->getASTContext();
1184 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001185 return LinkageInfo::none();
1186
Eli Friedman7e346a82013-07-01 20:22:57 +00001187 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
Alexey Bataev0a47e652016-01-12 09:01:25 +00001188 if (!OuterD || OuterD->isInvalidDecl())
Rafael Espindola50df3a02013-05-25 17:16:20 +00001189 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001190
Eli Friedman7e346a82013-07-01 20:22:57 +00001191 LinkageInfo LV;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001192 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001193 if (!BD->getBlockManglingNumber())
1194 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001195
Eli Friedman7e346a82013-07-01 20:22:57 +00001196 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1197 BD->getBlockManglingContextDecl(), computation);
1198 } else {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001199 const auto *FD = cast<FunctionDecl>(OuterD);
Eli Friedman7e346a82013-07-01 20:22:57 +00001200 if (!FD->isInlined() &&
David Majnemer9963ade2014-12-16 04:52:14 +00001201 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
Eli Friedman7e346a82013-07-01 20:22:57 +00001202 return LinkageInfo::none();
1203
1204 LV = getLVForDecl(FD, computation);
1205 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001206 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001207 return LinkageInfo::none();
1208 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1209 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001210}
1211
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001212static inline const CXXRecordDecl*
1213getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1214 const CXXRecordDecl *Ret = Record;
1215 while (Record && Record->isLambda()) {
1216 Ret = Record;
1217 if (!Record->getParent()) break;
1218 // Get the Containing Class of this Lambda Class
1219 Record = dyn_cast_or_null<CXXRecordDecl>(
1220 Record->getParent()->getParent());
1221 }
1222 return Ret;
1223}
1224
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001225static LinkageInfo computeLVForDecl(const NamedDecl *D,
1226 LVComputationKind computation) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001227 // Internal_linkage attribute overrides other considerations.
1228 if (D->hasAttr<InternalLinkageAttr>())
1229 return LinkageInfo::internal();
1230
Ted Kremenek926d8602010-04-20 23:15:35 +00001231 // Objective-C: treat all Objective-C declarations as having external
1232 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001233 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001234 default:
1235 break;
Richard Smith97135cc2015-11-12 22:19:45 +00001236
1237 // Per C++ [basic.link]p2, only the names of objects, references,
1238 // functions, types, templates, namespaces, and values ever have linkage.
1239 //
1240 // Note that the name of a typedef, namespace alias, using declaration,
1241 // and so on are not the name of the corresponding type, namespace, or
1242 // declaration, so they do *not* have linkage.
Richard Smith97135cc2015-11-12 22:19:45 +00001243 case Decl::ImplicitParam:
1244 case Decl::Label:
1245 case Decl::NamespaceAlias:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001246 case Decl::ParmVar:
Richard Smith97135cc2015-11-12 22:19:45 +00001247 case Decl::Using:
1248 case Decl::UsingShadow:
1249 case Decl::UsingDirective:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001250 return LinkageInfo::none();
Richard Smith97135cc2015-11-12 22:19:45 +00001251
Richard Smith26210db2015-11-13 03:52:13 +00001252 case Decl::EnumConstant:
1253 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
Bruno Cardoso Lopes057c82c2017-07-01 00:06:27 +00001254 if (D->getASTContext().getLangOpts().CPlusPlus)
1255 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1256 return LinkageInfo::visible_none();
Richard Smith26210db2015-11-13 03:52:13 +00001257
Richard Smith97135cc2015-11-12 22:19:45 +00001258 case Decl::Typedef:
1259 case Decl::TypeAlias:
1260 // A typedef declaration has linkage if it gives a type a name for
1261 // linkage purposes.
Ben Langmuir90717ad2015-11-14 03:26:14 +00001262 if (!D->getASTContext().getLangOpts().CPlusPlus ||
1263 !cast<TypedefNameDecl>(D)
Richard Smith97135cc2015-11-12 22:19:45 +00001264 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1265 return LinkageInfo::none();
1266 break;
1267
John McCall457a04e2010-10-22 21:05:15 +00001268 case Decl::TemplateTemplateParm: // count these as external
1269 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001270 case Decl::ObjCAtDefsField:
1271 case Decl::ObjCCategory:
1272 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001273 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001274 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001275 case Decl::ObjCMethod:
1276 case Decl::ObjCProperty:
1277 case Decl::ObjCPropertyImpl:
1278 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +00001279 return LinkageInfo::external();
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001280
1281 case Decl::CXXRecord: {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001282 const auto *Record = cast<CXXRecordDecl>(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001283 if (Record->isLambda()) {
1284 if (!Record->getLambdaManglingNumber()) {
1285 // This lambda has no mangling number, so it's internal.
1286 return LinkageInfo::internal();
1287 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001288
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001289 // This lambda has its linkage/visibility determined:
1290 // - either by the outermost lambda if that lambda has no mangling
1291 // number.
1292 // - or by the parent of the outer most lambda
1293 // This prevents infinite recursion in settings such as nested lambdas
1294 // used in NSDMI's, for e.g.
1295 // struct L {
1296 // int t{};
1297 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1298 // };
1299 const CXXRecordDecl *OuterMostLambda =
1300 getOutermostEnclosingLambda(Record);
1301 if (!OuterMostLambda->getLambdaManglingNumber())
1302 return LinkageInfo::internal();
1303
1304 return getLVForClosure(
1305 OuterMostLambda->getDeclContext()->getRedeclContext(),
1306 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001307 }
1308
1309 break;
1310 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001311 }
1312
Douglas Gregorf73b2822009-11-25 22:24:25 +00001313 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001314 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCalldf25c432013-02-16 00:17:33 +00001315 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001316
1317 // C++ [basic.link]p5:
1318 // In addition, a member function, static data member, a named
1319 // class or enumeration of class scope, or an unnamed class or
1320 // enumeration defined in a class-scope typedef declaration such
1321 // that the class or enumeration has the typedef name for linkage
1322 // purposes (7.1.3), has external linkage if the name of the class
1323 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001324 if (D->getDeclContext()->isRecord())
John McCalldf25c432013-02-16 00:17:33 +00001325 return getLVForClassMember(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001326
1327 // C++ [basic.link]p6:
1328 // The name of a function declared in block scope and the name of
1329 // an object declared by a block scope extern declaration have
1330 // linkage. If there is a visible declaration of an entity with
1331 // linkage having the same name and type, ignoring entities
1332 // declared outside the innermost enclosing namespace scope, the
1333 // block scope declaration declares that same entity and receives
1334 // the linkage of the previous declaration. If there is more than
1335 // one such matching entity, the program is ill-formed. Otherwise,
1336 // if no matching entity is found, the block scope entity receives
1337 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001338 if (D->getDeclContext()->isFunctionOrMethod())
1339 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001340
1341 // C++ [basic.link]p6:
1342 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001343 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001344}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001345
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001346namespace clang {
1347class LinkageComputer {
1348public:
1349 static LinkageInfo getLVForDecl(const NamedDecl *D,
1350 LVComputationKind computation) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001351 // Internal_linkage attribute overrides other considerations.
1352 if (D->hasAttr<InternalLinkageAttr>())
1353 return LinkageInfo::internal();
1354
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001355 if (computation == LVForLinkageOnly && D->hasCachedLinkage())
1356 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1357
1358 LinkageInfo LV = computeLVForDecl(D, computation);
1359 if (D->hasCachedLinkage())
1360 assert(D->getCachedLinkage() == LV.getLinkage());
1361
1362 D->setCachedLinkage(LV.getLinkage());
1363
1364#ifndef NDEBUG
1365 // In C (because of gnu inline) and in c++ with microsoft extensions an
1366 // static can follow an extern, so we can have two decls with different
1367 // linkages.
1368 const LangOptions &Opts = D->getASTContext().getLangOpts();
1369 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1370 return LV;
1371
1372 // We have just computed the linkage for this decl. By induction we know
1373 // that all other computed linkages match, check that the one we just
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001374 // computed also does.
Craig Topper36250ad2014-05-12 05:36:57 +00001375 NamedDecl *Old = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +00001376 for (auto I : D->redecls()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001377 auto *T = cast<NamedDecl>(I);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001378 if (T == D)
1379 continue;
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001380 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001381 Old = T;
1382 break;
1383 }
1384 }
1385 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1386#endif
1387
1388 return LV;
1389 }
1390};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001391}
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001392
1393static LinkageInfo getLVForDecl(const NamedDecl *D,
1394 LVComputationKind computation) {
1395 return clang::LinkageComputer::getLVForDecl(D, computation);
1396}
1397
Richard Smith7873de02016-08-11 22:25:46 +00001398void NamedDecl::printName(raw_ostream &os) const {
1399 os << Name;
1400}
1401
Douglas Gregor2ada0482009-02-04 17:27:36 +00001402std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001403 std::string QualName;
1404 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001405 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001406 return OS.str();
1407}
1408
1409void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1410 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1411}
1412
1413void NamedDecl::printQualifiedName(raw_ostream &OS,
1414 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001415 const DeclContext *Ctx = getDeclContext();
1416
Argyrios Kyrtzidisa166a2b2017-03-07 09:26:07 +00001417 // For ObjC methods, look through categories and use the interface as context.
1418 if (auto *MD = dyn_cast<ObjCMethodDecl>(this))
1419 if (auto *ID = MD->getClassInterface())
1420 Ctx = ID;
1421
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001422 if (Ctx->isFunctionOrMethod()) {
1423 printName(OS);
1424 return;
1425 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001426
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001427 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001428 ContextsTy Contexts;
1429
1430 // Collect contexts.
1431 while (Ctx && isa<NamedDecl>(Ctx)) {
1432 Contexts.push_back(Ctx);
1433 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001434 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001435
David Majnemerf7e36092016-06-23 00:15:04 +00001436 for (const DeclContext *DC : reverse(Contexts)) {
1437 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001438 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001439 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
David Majnemer6fbeee32016-07-07 04:43:07 +00001440 TemplateSpecializationType::PrintTemplateArgumentList(
1441 OS, TemplateArgs.asArray(), P);
David Majnemerf7e36092016-06-23 00:15:04 +00001442 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
Richard Smith46dd5bb2014-05-30 22:16:51 +00001443 if (P.SuppressUnwrittenScope &&
1444 (ND->isAnonymousNamespace() || ND->isInline()))
1445 continue;
Reid Kleckner60103382015-12-16 02:04:40 +00001446 if (ND->isAnonymousNamespace()) {
1447 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1448 : "(anonymous namespace)");
1449 }
Sam Weinig07d211e2009-12-24 23:15:03 +00001450 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001451 OS << *ND;
David Majnemerf7e36092016-06-23 00:15:04 +00001452 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001453 if (!RD->getIdentifier())
David Blaikieabe1a392014-04-02 05:58:29 +00001454 OS << "(anonymous " << RD->getKindName() << ')';
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001455 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001456 OS << *RD;
David Majnemerf7e36092016-06-23 00:15:04 +00001457 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
Craig Topper36250ad2014-05-12 05:36:57 +00001458 const FunctionProtoType *FT = nullptr;
Sam Weinigb999f682009-12-28 03:19:38 +00001459 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001460 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001461
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001462 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001463 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001464 unsigned NumParams = FD->getNumParams();
1465 for (unsigned i = 0; i < NumParams; ++i) {
1466 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001467 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001468 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001469 }
1470
1471 if (FT->isVariadic()) {
1472 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001473 OS << ", ";
1474 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001475 }
1476 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001477 OS << ')';
David Majnemerf7e36092016-06-23 00:15:04 +00001478 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
Alexander Kornienko4f355322015-11-09 16:45:17 +00001479 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1480 // enumerator is declared in the scope that immediately contains
1481 // the enum-specifier. Each scoped enumerator is declared in the
1482 // scope of the enumeration.
1483 if (ED->isScoped() || ED->getIdentifier())
1484 OS << *ED;
1485 else
1486 continue;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001487 } else {
David Majnemerf7e36092016-06-23 00:15:04 +00001488 OS << *cast<NamedDecl>(DC);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001489 }
1490 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001491 }
1492
Richard Smith7873de02016-08-11 22:25:46 +00001493 if (getDeclName() || isa<DecompositionDecl>(this))
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001494 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001495 else
David Blaikieabe1a392014-04-02 05:58:29 +00001496 OS << "(anonymous)";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001497}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001498
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001499void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1500 const PrintingPolicy &Policy,
1501 bool Qualified) const {
1502 if (Qualified)
1503 printQualifiedName(OS, Policy);
1504 else
1505 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001506}
1507
Richard Smithe8292b12015-02-10 03:28:10 +00001508template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1509 return true;
1510}
1511static bool isRedeclarableImpl(...) { return false; }
1512static bool isRedeclarable(Decl::Kind K) {
1513 switch (K) {
1514#define DECL(Type, Base) \
1515 case Decl::Type: \
1516 return isRedeclarableImpl((Type##Decl *)nullptr);
1517#define ABSTRACT_DECL(DECL)
1518#include "clang/AST/DeclNodes.inc"
1519 }
1520 llvm_unreachable("unknown decl kind");
1521}
1522
1523bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001524 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1525
Richard Smithfe620d22015-03-05 23:24:12 +00001526 // Never replace one imported declaration with another; we need both results
1527 // when re-exporting.
1528 if (OldD->isFromASTFile() && isFromASTFile())
1529 return false;
1530
Richard Smith5cd86f82015-11-03 03:13:11 +00001531 // A kind mismatch implies that the declaration is not replaced.
1532 if (OldD->getKind() != getKind())
Richard Smithe8292b12015-02-10 03:28:10 +00001533 return false;
1534
Richard Smith5cd86f82015-11-03 03:13:11 +00001535 // For method declarations, we never replace. (Why?)
1536 if (isa<ObjCMethodDecl>(this))
1537 return false;
1538
1539 // For parameters, pick the newer one. This is either an error or (in
1540 // Objective-C) permitted as an extension.
1541 if (isa<ParmVarDecl>(this))
1542 return true;
1543
Richard Smithe8292b12015-02-10 03:28:10 +00001544 // Inline namespaces can give us two declarations with the same
1545 // name and kind in the same scope but different contexts; we should
1546 // keep both declarations in this case.
1547 if (!this->getDeclContext()->getRedeclContext()->Equals(
1548 OldD->getDeclContext()->getRedeclContext()))
1549 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001550
Richard Smith5cd86f82015-11-03 03:13:11 +00001551 // Using declarations can be replaced if they import the same name from the
1552 // same context.
Richard Smithe8292b12015-02-10 03:28:10 +00001553 if (auto *UD = dyn_cast<UsingDecl>(this)) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001554 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001555 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001556 Context.getCanonicalNestedNameSpecifier(
Richard Smithe8292b12015-02-10 03:28:10 +00001557 cast<UsingDecl>(OldD)->getQualifier());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001558 }
Richard Smithe8292b12015-02-10 03:28:10 +00001559 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001560 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001561 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001562 Context.getCanonicalNestedNameSpecifier(
1563 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1564 }
1565
Richard Smithe8292b12015-02-10 03:28:10 +00001566 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
Richard Smith5cd86f82015-11-03 03:13:11 +00001567 // They can be replaced if they nominate the same namespace.
1568 // FIXME: Is this true even if they have different module visibility?
Richard Smithe8292b12015-02-10 03:28:10 +00001569 if (auto *UD = dyn_cast<UsingDirectiveDecl>(this))
1570 return UD->getNominatedNamespace()->getOriginalNamespace() ==
1571 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1572 ->getOriginalNamespace();
Richard Smithbaf3ca52014-03-17 21:46:03 +00001573
Richard Smith5cd86f82015-11-03 03:13:11 +00001574 if (isRedeclarable(getKind())) {
1575 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1576 return false;
1577
1578 if (IsKnownNewer)
1579 return true;
1580
Richard Smithe8292b12015-02-10 03:28:10 +00001581 // Check whether this is actually newer than OldD. We want to keep the
1582 // newer declaration. This loop will usually only iterate once, because
1583 // OldD is usually the previous declaration.
1584 for (auto D : redecls()) {
1585 if (D == OldD)
1586 break;
1587
1588 // If we reach the canonical declaration, then OldD is not actually older
1589 // than this one.
1590 //
1591 // FIXME: In this case, we should not add this decl to the lookup table.
1592 if (D->isCanonicalDecl())
1593 return false;
1594 }
Richard Smith5cd86f82015-11-03 03:13:11 +00001595
1596 // It's a newer declaration of the same kind of declaration in the same
1597 // scope: we want this decl instead of the existing one.
1598 return true;
Richard Smithe8292b12015-02-10 03:28:10 +00001599 }
1600
Richard Smith5cd86f82015-11-03 03:13:11 +00001601 // In all other cases, we need to keep both declarations in case they have
1602 // different visibility. Any attempt to use the name will result in an
1603 // ambiguity if more than one is visible.
1604 return false;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001605}
1606
Douglas Gregoreddf4332009-02-24 20:03:32 +00001607bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001608 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001609}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001610
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001611NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001612 NamedDecl *ND = this;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001613 while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001614 ND = UD->getTargetDecl();
1615
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001616 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001617 return AD->getClassInterface();
1618
Richard Smithf2005d32015-12-29 23:34:32 +00001619 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1620 return AD->getNamespace();
1621
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001622 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001623}
1624
John McCalla8ae2222010-04-06 21:38:20 +00001625bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001626 if (!isCXXClassMember())
1627 return false;
1628
John McCalla8ae2222010-04-06 21:38:20 +00001629 const NamedDecl *D = this;
1630 if (isa<UsingShadowDecl>(D))
1631 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1632
John McCall5e77d762013-04-16 07:28:30 +00001633 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001634 return true;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001635 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
Alp Tokera2794f92014-01-22 07:29:52 +00001636 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001637 return false;
1638}
1639
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001640//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001641// DeclaratorDecl Implementation
1642//===----------------------------------------------------------------------===//
1643
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001644template <typename DeclT>
1645static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1646 if (decl->getNumTemplateParameterLists() > 0)
1647 return decl->getTemplateParameterList(0)->getTemplateLoc();
1648 else
1649 return decl->getInnerLocStart();
1650}
1651
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001652SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001653 TypeSourceInfo *TSI = getTypeSourceInfo();
1654 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001655 return SourceLocation();
1656}
1657
Douglas Gregor14454802011-02-25 02:25:35 +00001658void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1659 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001660 // Make sure the extended decl info is allocated.
1661 if (!hasExtInfo()) {
1662 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001663 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
John McCall3e11ebe2010-03-15 10:12:16 +00001664 // Allocate external info struct.
1665 DeclInfo = new (getASTContext()) ExtInfo;
1666 // Restore savedTInfo into (extended) decl info.
1667 getExtInfo()->TInfo = savedTInfo;
1668 }
1669 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001670 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001671 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001672 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001673 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001674 if (getExtInfo()->NumTemplParamLists == 0) {
1675 // Save type source info pointer.
1676 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1677 // Deallocate the extended decl info.
1678 getASTContext().Deallocate(getExtInfo());
1679 // Restore savedTInfo into (non-extended) decl info.
1680 DeclInfo = savedTInfo;
1681 }
1682 else
1683 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001684 }
1685 }
1686}
1687
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001688void DeclaratorDecl::setTemplateParameterListsInfo(
1689 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1690 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00001691 // Make sure the extended decl info is allocated.
1692 if (!hasExtInfo()) {
1693 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001694 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
Abramo Bagnara60804e12011-03-18 15:16:37 +00001695 // Allocate external info struct.
1696 DeclInfo = new (getASTContext()) ExtInfo;
1697 // Restore savedTInfo into (extended) decl info.
1698 getExtInfo()->TInfo = savedTInfo;
1699 }
1700 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001701 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00001702}
1703
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001704SourceLocation DeclaratorDecl::getOuterLocStart() const {
1705 return getTemplateOrInnerLocStart(this);
1706}
1707
Abramo Bagnaraea947882011-03-08 16:41:52 +00001708namespace {
1709
1710// Helper function: returns true if QT is or contains a type
1711// having a postfix component.
1712bool typeIsPostfix(clang::QualType QT) {
1713 while (true) {
1714 const Type* T = QT.getTypePtr();
1715 switch (T->getTypeClass()) {
1716 default:
1717 return false;
1718 case Type::Pointer:
1719 QT = cast<PointerType>(T)->getPointeeType();
1720 break;
1721 case Type::BlockPointer:
1722 QT = cast<BlockPointerType>(T)->getPointeeType();
1723 break;
1724 case Type::MemberPointer:
1725 QT = cast<MemberPointerType>(T)->getPointeeType();
1726 break;
1727 case Type::LValueReference:
1728 case Type::RValueReference:
1729 QT = cast<ReferenceType>(T)->getPointeeType();
1730 break;
1731 case Type::PackExpansion:
1732 QT = cast<PackExpansionType>(T)->getPattern();
1733 break;
1734 case Type::Paren:
1735 case Type::ConstantArray:
1736 case Type::DependentSizedArray:
1737 case Type::IncompleteArray:
1738 case Type::VariableArray:
1739 case Type::FunctionProto:
1740 case Type::FunctionNoProto:
1741 return true;
1742 }
1743 }
1744}
1745
1746} // namespace
1747
1748SourceRange DeclaratorDecl::getSourceRange() const {
1749 SourceLocation RangeEnd = getLocation();
1750 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001751 // If the declaration has no name or the type extends past the name take the
1752 // end location of the type.
1753 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001754 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1755 }
1756 return SourceRange(getOuterLocStart(), RangeEnd);
1757}
1758
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001759void QualifierInfo::setTemplateParameterListsInfo(
1760 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001761 // Free previous template parameters (if any).
1762 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001763 Context.Deallocate(TemplParamLists);
Craig Topper36250ad2014-05-12 05:36:57 +00001764 TemplParamLists = nullptr;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001765 NumTemplParamLists = 0;
1766 }
1767 // Set info on matched template parameter lists (if any).
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001768 if (!TPLists.empty()) {
1769 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1770 NumTemplParamLists = TPLists.size();
1771 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001772 }
1773}
1774
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001775//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001776// VarDecl Implementation
1777//===----------------------------------------------------------------------===//
1778
Sebastian Redl833ef452010-01-26 22:01:41 +00001779const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1780 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001781 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001782 case SC_Auto: return "auto";
1783 case SC_Extern: return "extern";
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001784 case SC_PrivateExtern: return "__private_extern__";
1785 case SC_Register: return "register";
1786 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001787 }
1788
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001789 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001790}
1791
Richard Smith053f6c62014-05-16 23:01:30 +00001792VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1793 SourceLocation StartLoc, SourceLocation IdLoc,
1794 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1795 StorageClass SC)
1796 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1797 redeclarable_base(C), Init() {
Benjamin Kramera939c232014-03-15 18:54:13 +00001798 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1799 "VarDeclBitfields too large!");
1800 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1801 "ParmVarDeclBitfields too large!");
David Majnemerfa7bc782015-05-19 00:57:16 +00001802 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1803 "NonParmVarDeclBitfields too large!");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001804 AllBits = 0;
1805 VarDeclBits.SClass = SC;
1806 // Everything else is implicitly initialized to false.
1807}
1808
Abramo Bagnaradff19302011-03-08 08:55:46 +00001809VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1810 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001811 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001812 StorageClass S) {
Richard Smith053f6c62014-05-16 23:01:30 +00001813 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001814}
1815
Douglas Gregor72172e92012-01-05 21:55:30 +00001816VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00001817 return new (C, ID)
1818 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1819 QualType(), nullptr, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001820}
1821
Douglas Gregorbf62d642010-12-06 18:36:25 +00001822void VarDecl::setStorageClass(StorageClass SC) {
1823 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001824 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001825}
1826
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001827VarDecl::TLSKind VarDecl::getTLSKind() const {
1828 switch (VarDeclBits.TSCSpec) {
1829 case TSCS_unspecified:
Samuel Antaof8b50122015-07-13 22:54:53 +00001830 if (!hasAttr<ThreadAttr>() &&
1831 !(getASTContext().getLangOpts().OpenMPUseTLS &&
1832 getASTContext().getTargetInfo().isTLSSupported() &&
1833 hasAttr<OMPThreadPrivateDeclAttr>()))
David Majnemer1b5baff2015-05-14 05:19:23 +00001834 return TLS_None;
Samuel Antaof8b50122015-07-13 22:54:53 +00001835 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1836 LangOptions::MSVC2015)) ||
1837 hasAttr<OMPThreadPrivateDeclAttr>())
David Majnemer1b5baff2015-05-14 05:19:23 +00001838 ? TLS_Dynamic
1839 : TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001840 case TSCS___thread: // Fall through.
1841 case TSCS__Thread_local:
Samuel Antaof8b50122015-07-13 22:54:53 +00001842 return TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001843 case TSCS_thread_local:
1844 return TLS_Dynamic;
1845 }
1846 llvm_unreachable("Unknown thread storage class specifier!");
1847}
1848
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001849SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001850 if (const Expr *Init = getInit()) {
1851 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001852 // If Init is implicit, ignore its source range and fallback on
1853 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1854 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001855 return SourceRange(getOuterLocStart(), InitEnd);
1856 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001857 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001858}
1859
Rafael Espindola88510672013-01-04 21:18:45 +00001860template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001861static LanguageLinkage getDeclLanguageLinkage(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001862 // C++ [dcl.link]p1: All function types, function names with external linkage,
1863 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001864 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001865 return NoLanguageLinkage;
1866
1867 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001868 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001869 ASTContext &Context = D.getASTContext();
1870 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001871 return CLanguageLinkage;
1872
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001873 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1874 // language linkage of the names of class members and the function type of
1875 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001876 const DeclContext *DC = D.getDeclContext();
1877 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001878 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001879
1880 // If the first decl is in an extern "C" context, any other redeclaration
1881 // will have C language linkage. If the first one is not in an extern "C"
1882 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00001883 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00001884 return CLanguageLinkage;
1885 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001886}
1887
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001888template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001889static bool isDeclExternC(const T &D) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001890 // Since the context is ignored for class members, they can only have C++
1891 // language linkage or no language linkage.
1892 const DeclContext *DC = D.getDeclContext();
1893 if (DC->isRecord()) {
1894 assert(D.getASTContext().getLangOpts().CPlusPlus);
1895 return false;
1896 }
1897
1898 return D.getLanguageLinkage() == CLanguageLinkage;
1899}
1900
Rafael Espindolaf4187652013-02-14 01:18:37 +00001901LanguageLinkage VarDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00001902 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001903}
1904
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001905bool VarDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00001906 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001907}
1908
Rafael Espindola593537a2013-05-05 20:15:21 +00001909bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001910 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001911}
1912
1913bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001914 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001915}
1916
Rafael Espindola8db352d2013-10-17 15:37:26 +00001917VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00001918
Nico Weber7f5015a2015-04-15 21:53:00 +00001919VarDecl::DefinitionKind
1920VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001921 // C++ [basic.def]p2:
1922 // A declaration is a definition unless [...] it contains the 'extern'
1923 // specifier or a linkage-specification and neither an initializer [...],
Richard Smith62f19e72016-06-25 00:15:56 +00001924 // it declares a non-inline static data member in a class declaration [...],
1925 // it declares a static data member outside a class definition and the variable
1926 // was defined within the class with the constexpr specifier [...],
Richard Smith8809a0c2013-09-27 20:14:12 +00001927 // C++1y [temp.expl.spec]p15:
1928 // An explicit specialization of a static data member or an explicit
1929 // specialization of a static data member template is a definition if the
1930 // declaration includes an initializer; otherwise, it is a declaration.
1931 //
1932 // FIXME: How do you declare (but not define) a partial specialization of
1933 // a static data member template outside the containing class?
Richard Smithedbc6e92016-10-14 21:41:24 +00001934 if (isThisDeclarationADemotedDefinition())
1935 return DeclarationOnly;
1936
Sebastian Redl35351a92010-01-31 22:27:38 +00001937 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00001938 if (isOutOfLine() &&
Richard Smith62f19e72016-06-25 00:15:56 +00001939 !(getCanonicalDecl()->isInline() &&
1940 getCanonicalDecl()->isConstexpr()) &&
Richard Smith8809a0c2013-09-27 20:14:12 +00001941 (hasInit() ||
1942 // If the first declaration is out-of-line, this may be an
1943 // instantiation of an out-of-line partial specialization of a variable
1944 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00001945 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00001946 ? getTemplateSpecializationKind() == TSK_Undeclared
1947 : getTemplateSpecializationKind() !=
1948 TSK_ExplicitSpecialization) ||
1949 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00001950 return Definition;
Richard Smith62f19e72016-06-25 00:15:56 +00001951 else if (!isOutOfLine() && isInline())
1952 return Definition;
Sebastian Redl35351a92010-01-31 22:27:38 +00001953 else
1954 return DeclarationOnly;
1955 }
1956 // C99 6.7p5:
1957 // A definition of an identifier is a declaration for that identifier that
1958 // [...] causes storage to be reserved for that object.
1959 // Note: that applies for all non-file-scope objects.
1960 // C99 6.9.2p1:
1961 // If the declaration of an identifier for an object has file scope and an
1962 // initializer, the declaration is an external definition for the identifier
1963 if (hasInit())
1964 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00001965
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001966 if (hasDefiningAttr())
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001967 return Definition;
1968
David Majnemerdd0bed12015-05-14 05:19:20 +00001969 if (const auto *SAA = getAttr<SelectAnyAttr>())
1970 if (!SAA->isInherited())
1971 return Definition;
1972
Richard Smith8809a0c2013-09-27 20:14:12 +00001973 // A variable template specialization (other than a static data member
1974 // template or an explicit specialization) is a declaration until we
1975 // instantiate its initializer.
1976 if (isa<VarTemplateSpecializationDecl>(this) &&
1977 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1978 return DeclarationOnly;
1979
Nico Weber608e7682015-04-15 23:04:24 +00001980 if (hasExternalStorage())
Sebastian Redl35351a92010-01-31 22:27:38 +00001981 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00001982
Rafael Espindolabff59562013-04-25 12:11:36 +00001983 // [dcl.link] p7:
1984 // A declaration directly contained in a linkage-specification is treated
1985 // as if it contains the extern specifier for the purpose of determining
1986 // the linkage of the declared name and whether it is a definition.
Nico Weber608e7682015-04-15 23:04:24 +00001987 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00001988 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00001989
Sebastian Redl35351a92010-01-31 22:27:38 +00001990 // C99 6.9.2p2:
1991 // A declaration of an object that has file scope without an initializer,
1992 // and without a storage class specifier or the scs 'static', constitutes
1993 // a tentative definition.
1994 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001995 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00001996 return TentativeDefinition;
1997
1998 // What's left is (in C, block-scope) declarations without initializers or
1999 // external storage. These are definitions.
2000 return Definition;
2001}
2002
Sebastian Redl35351a92010-01-31 22:27:38 +00002003VarDecl *VarDecl::getActingDefinition() {
2004 DefinitionKind Kind = isThisDeclarationADefinition();
2005 if (Kind != TentativeDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00002006 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002007
Craig Topper36250ad2014-05-12 05:36:57 +00002008 VarDecl *LastTentative = nullptr;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002009 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002010 for (auto I : First->redecls()) {
2011 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00002012 if (Kind == Definition)
Craig Topper36250ad2014-05-12 05:36:57 +00002013 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002014 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00002015 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00002016 }
2017 return LastTentative;
2018}
2019
Daniel Dunbar9d355812012-03-09 01:51:51 +00002020VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002021 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002022 for (auto I : First->redecls()) {
2023 if (I->isThisDeclarationADefinition(C) == Definition)
2024 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002025 }
Craig Topper36250ad2014-05-12 05:36:57 +00002026 return nullptr;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002027}
2028
Daniel Dunbar9d355812012-03-09 01:51:51 +00002029VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00002030 DefinitionKind Kind = DeclarationOnly;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002031
Rafael Espindola8db352d2013-10-17 15:37:26 +00002032 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002033 for (auto I : First->redecls()) {
2034 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00002035 if (Kind == Definition)
2036 break;
2037 }
John McCall37bb6c92010-10-29 22:22:43 +00002038
2039 return Kind;
2040}
2041
Sebastian Redl5ca79842010-02-01 20:16:42 +00002042const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002043 for (auto I : redecls()) {
2044 if (auto Expr = I->getInit()) {
2045 D = I;
2046 return Expr;
2047 }
Sebastian Redl833ef452010-01-26 22:01:41 +00002048 }
Craig Topper36250ad2014-05-12 05:36:57 +00002049 return nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002050}
2051
Chandler Carruth813faed2015-12-30 02:51:00 +00002052bool VarDecl::hasInit() const {
2053 if (auto *P = dyn_cast<ParmVarDecl>(this))
2054 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2055 return false;
2056
2057 return !Init.isNull();
2058}
2059
2060Expr *VarDecl::getInit() {
2061 if (!hasInit())
2062 return nullptr;
2063
2064 if (auto *S = Init.dyn_cast<Stmt *>())
2065 return cast<Expr>(S);
2066
2067 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2068}
2069
2070Stmt **VarDecl::getInitAddress() {
2071 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2072 return &ES->Value;
2073
2074 return Init.getAddrOfPtr1();
2075}
2076
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002077bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002078 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002079 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00002080
2081 if (!isStaticDataMember())
2082 return false;
2083
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002084 // If this static data member was instantiated from a static data member of
2085 // a class template, check whether that static data member was defined
2086 // out-of-line.
2087 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2088 return VD->isOutOfLine();
2089
2090 return false;
2091}
2092
Douglas Gregord5058122010-02-11 01:19:42 +00002093void VarDecl::setInit(Expr *I) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002094 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
Sebastian Redl833ef452010-01-26 22:01:41 +00002095 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00002096 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00002097 }
2098
2099 Init = I;
2100}
2101
Daniel Dunbar9d355812012-03-09 01:51:51 +00002102bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002103 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00002104
Richard Smith35ecb362012-03-02 04:14:40 +00002105 if (!Lang.CPlusPlus)
2106 return false;
2107
2108 // In C++11, any variable of reference type can be used in a constant
2109 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002110 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00002111 return true;
2112
2113 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00002114 // not require the variable to be non-volatile, but we consider this to be a
2115 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00002116 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00002117 return false;
2118
2119 // In C++, const, non-volatile variables of integral or enumeration types
2120 // can be used in constant expressions.
2121 if (getType()->isIntegralOrEnumerationType())
2122 return true;
2123
Richard Smith35ecb362012-03-02 04:14:40 +00002124 // Additionally, in C++11, non-volatile constexpr variables can be used in
2125 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002126 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00002127}
2128
Richard Smithd0b4dd62011-12-19 06:19:21 +00002129/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2130/// form, which contains extra information on the evaluated value of the
2131/// initializer.
2132EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002133 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002134 if (!Eval) {
Manuel Klimeka7328992013-06-03 13:51:33 +00002135 // Note: EvaluatedStmt contains an APValue, which usually holds
2136 // resources not allocated from the ASTContext. We need to do some
2137 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2138 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002139 Eval = new (getASTContext()) EvaluatedStmt;
Chandler Carruth813faed2015-12-30 02:51:00 +00002140 Eval->Value = Init.get<Stmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002141 Init = Eval;
2142 }
2143 return Eval;
2144}
2145
Richard Smithdafff942012-01-14 04:30:29 +00002146APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002147 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00002148 return evaluateValue(Notes);
2149}
2150
2151APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002152 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002153 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2154
2155 // We only produce notes indicating why an initializer is non-constant the
2156 // first time it is evaluated. FIXME: The notes won't always be emitted the
2157 // first time we try evaluation, so might not be produced at all.
2158 if (Eval->WasEvaluated)
Craig Topper36250ad2014-05-12 05:36:57 +00002159 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002160
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002161 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002162 assert(!Init->isValueDependent());
2163
2164 if (Eval->IsEvaluating) {
2165 // FIXME: Produce a diagnostic for self-initialization.
2166 Eval->CheckedICE = true;
2167 Eval->IsICE = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002168 return nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002169 }
2170
2171 Eval->IsEvaluating = true;
2172
2173 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2174 this, Notes);
2175
Manuel Klimeka7328992013-06-03 13:51:33 +00002176 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2177 // or that it's empty (so that there's nothing to clean up) if evaluation
2178 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002179 if (!Result)
2180 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00002181 else if (Eval->Evaluated.needsCleanup())
George Burgess IVb61bfbd2017-02-14 05:37:36 +00002182 getASTContext().addDestruction(&Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002183
2184 Eval->IsEvaluating = false;
2185 Eval->WasEvaluated = true;
2186
2187 // In C++11, we have determined whether the initializer was a constant
2188 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002189 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002190 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00002191 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002192 }
2193
Craig Topper36250ad2014-05-12 05:36:57 +00002194 return Result ? &Eval->Evaluated : nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002195}
2196
Chandler Carruth813faed2015-12-30 02:51:00 +00002197APValue *VarDecl::getEvaluatedValue() const {
2198 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2199 if (Eval->WasEvaluated)
2200 return &Eval->Evaluated;
2201
2202 return nullptr;
2203}
2204
2205bool VarDecl::isInitKnownICE() const {
2206 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2207 return Eval->CheckedICE;
2208
2209 return false;
2210}
2211
2212bool VarDecl::isInitICE() const {
2213 assert(isInitKnownICE() &&
2214 "Check whether we already know that the initializer is an ICE");
2215 return Init.get<EvaluatedStmt *>()->IsICE;
2216}
2217
Richard Smithd0b4dd62011-12-19 06:19:21 +00002218bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00002219 // Initializers of weak variables are never ICEs.
2220 if (isWeak())
2221 return false;
2222
Richard Smithd0b4dd62011-12-19 06:19:21 +00002223 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2224 if (Eval->CheckedICE)
2225 // We have already checked whether this subexpression is an
2226 // integral constant expression.
2227 return Eval->IsICE;
2228
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002229 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002230 assert(!Init->isValueDependent());
2231
2232 // In C++11, evaluate the initializer to check whether it's a constant
2233 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002234 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002235 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002236 evaluateValue(Notes);
2237 return Eval->IsICE;
2238 }
2239
2240 // It's an ICE whether or not the definition we found is
2241 // out-of-line. See DR 721 and the discussion in Clang PR
2242 // 6206 for details.
2243
2244 if (Eval->CheckingICE)
2245 return false;
2246 Eval->CheckingICE = true;
2247
2248 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2249 Eval->CheckingICE = false;
2250 Eval->CheckedICE = true;
2251 return Eval->IsICE;
2252}
2253
Richard Smith2195ec92017-04-21 01:15:13 +00002254template<typename DeclT>
2255static DeclT *getDefinitionOrSelf(DeclT *D) {
2256 assert(D);
2257 if (auto *Def = D->getDefinition())
2258 return Def;
2259 return D;
2260}
2261
Richard Smithedbc6e92016-10-14 21:41:24 +00002262VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2263 // If it's a variable template specialization, find the template or partial
2264 // specialization from which it was instantiated.
2265 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2266 auto From = VDTemplSpec->getInstantiatedFrom();
2267 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2268 while (auto *NewVTD = VTD->getInstantiatedFromMemberTemplate()) {
2269 if (NewVTD->isMemberSpecialization())
2270 break;
2271 VTD = NewVTD;
2272 }
Richard Smith2195ec92017-04-21 01:15:13 +00002273 return getDefinitionOrSelf(VTD->getTemplatedDecl());
Richard Smithedbc6e92016-10-14 21:41:24 +00002274 }
2275 if (auto *VTPSD =
2276 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2277 while (auto *NewVTPSD = VTPSD->getInstantiatedFromMember()) {
2278 if (NewVTPSD->isMemberSpecialization())
2279 break;
2280 VTPSD = NewVTPSD;
2281 }
Richard Smith2195ec92017-04-21 01:15:13 +00002282 return getDefinitionOrSelf<VarDecl>(VTPSD);
Richard Smithedbc6e92016-10-14 21:41:24 +00002283 }
2284 }
2285
2286 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
2287 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2288 VarDecl *VD = getInstantiatedFromStaticDataMember();
2289 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2290 VD = NewVD;
Richard Smith2195ec92017-04-21 01:15:13 +00002291 return getDefinitionOrSelf(VD);
Richard Smithedbc6e92016-10-14 21:41:24 +00002292 }
2293 }
2294
2295 if (VarTemplateDecl *VarTemplate = getDescribedVarTemplate()) {
Richard Smithedbc6e92016-10-14 21:41:24 +00002296 while (VarTemplate->getInstantiatedFromMemberTemplate()) {
2297 if (VarTemplate->isMemberSpecialization())
2298 break;
2299 VarTemplate = VarTemplate->getInstantiatedFromMemberTemplate();
2300 }
2301
Richard Smith2195ec92017-04-21 01:15:13 +00002302 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
Richard Smithedbc6e92016-10-14 21:41:24 +00002303 }
2304 return nullptr;
2305}
2306
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002307VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002308 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002309 return cast<VarDecl>(MSI->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002310
2311 return nullptr;
Douglas Gregor86d142a2009-10-08 07:24:58 +00002312}
2313
Douglas Gregor3c74d412009-10-14 20:14:33 +00002314TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002315 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002316 return Spec->getSpecializationKind();
2317
Sebastian Redl35351a92010-01-31 22:27:38 +00002318 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002319 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002320
Douglas Gregor86d142a2009-10-08 07:24:58 +00002321 return TSK_Undeclared;
2322}
2323
Richard Smith8809a0c2013-09-27 20:14:12 +00002324SourceLocation VarDecl::getPointOfInstantiation() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002325 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Richard Smith8809a0c2013-09-27 20:14:12 +00002326 return Spec->getPointOfInstantiation();
2327
2328 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2329 return MSI->getPointOfInstantiation();
2330
2331 return SourceLocation();
2332}
2333
Larisse Voufo39a1e502013-08-06 01:03:05 +00002334VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2335 return getASTContext().getTemplateOrSpecializationInfo(this)
2336 .dyn_cast<VarTemplateDecl *>();
2337}
2338
2339void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2340 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2341}
2342
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002343MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002344 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002345 // FIXME: Remove ?
2346 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2347 return getASTContext().getTemplateOrSpecializationInfo(this)
2348 .dyn_cast<MemberSpecializationInfo *>();
Craig Topper36250ad2014-05-12 05:36:57 +00002349 return nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002350}
2351
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002352void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2353 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002354 assert((isa<VarTemplateSpecializationDecl>(this) ||
2355 getMemberSpecializationInfo()) &&
2356 "not a variable or static data member template specialization");
2357
Larisse Voufo39a1e502013-08-06 01:03:05 +00002358 if (VarTemplateSpecializationDecl *Spec =
2359 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2360 Spec->setSpecializationKind(TSK);
2361 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2362 Spec->getPointOfInstantiation().isInvalid())
2363 Spec->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002364 }
2365
2366 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2367 MSI->setTemplateSpecializationKind(TSK);
2368 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2369 MSI->getPointOfInstantiation().isInvalid())
2370 MSI->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002371 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002372}
2373
2374void
2375VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2376 TemplateSpecializationKind TSK) {
2377 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2378 "Previous template or instantiation?");
2379 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002380}
2381
Sebastian Redl833ef452010-01-26 22:01:41 +00002382//===----------------------------------------------------------------------===//
2383// ParmVarDecl Implementation
2384//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002385
Sebastian Redl833ef452010-01-26 22:01:41 +00002386ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002387 SourceLocation StartLoc,
2388 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002389 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002390 StorageClass S, Expr *DefArg) {
Richard Smith053f6c62014-05-16 23:01:30 +00002391 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smithf7981722013-11-22 09:01:48 +00002392 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002393}
2394
Reid Kleckner8a365022013-06-24 17:51:48 +00002395QualType ParmVarDecl::getOriginalType() const {
2396 TypeSourceInfo *TSI = getTypeSourceInfo();
2397 QualType T = TSI ? TSI->getType() : getType();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002398 if (const auto *DT = dyn_cast<DecayedType>(T))
Reid Kleckner8a365022013-06-24 17:51:48 +00002399 return DT->getOriginalType();
2400 return T;
2401}
2402
Douglas Gregor72172e92012-01-05 21:55:30 +00002403ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00002404 return new (C, ID)
2405 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2406 nullptr, QualType(), nullptr, SC_None, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00002407}
2408
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002409SourceRange ParmVarDecl::getSourceRange() const {
2410 if (!hasInheritedDefaultArg()) {
2411 SourceRange ArgRange = getDefaultArgRange();
2412 if (ArgRange.isValid())
2413 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2414 }
2415
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002416 // DeclaratorDecl considers the range of postfix types as overlapping with the
2417 // declaration name, but this is not the case with parameters in ObjC methods.
2418 if (isa<ObjCMethodDecl>(getDeclContext()))
2419 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2420
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002421 return DeclaratorDecl::getSourceRange();
2422}
2423
Sebastian Redl833ef452010-01-26 22:01:41 +00002424Expr *ParmVarDecl::getDefaultArg() {
2425 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2426 assert(!hasUninstantiatedDefaultArg() &&
2427 "Default argument is not yet instantiated!");
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002428
Sebastian Redl833ef452010-01-26 22:01:41 +00002429 Expr *Arg = getInit();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002430 if (auto *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002431 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002432
Sebastian Redl833ef452010-01-26 22:01:41 +00002433 return Arg;
2434}
2435
Chandler Carruth813faed2015-12-30 02:51:00 +00002436void ParmVarDecl::setDefaultArg(Expr *defarg) {
2437 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2438 Init = defarg;
2439}
Sebastian Redl833ef452010-01-26 22:01:41 +00002440
Chandler Carruth813faed2015-12-30 02:51:00 +00002441SourceRange ParmVarDecl::getDefaultArgRange() const {
2442 switch (ParmVarDeclBits.DefaultArgKind) {
2443 case DAK_None:
2444 case DAK_Unparsed:
2445 // Nothing we can do here.
2446 return SourceRange();
2447
2448 case DAK_Uninstantiated:
Sebastian Redl833ef452010-01-26 22:01:41 +00002449 return getUninstantiatedDefaultArg()->getSourceRange();
2450
Chandler Carruth813faed2015-12-30 02:51:00 +00002451 case DAK_Normal:
2452 if (const Expr *E = getInit())
2453 return E->getSourceRange();
2454
2455 // Missing an actual expression, may be invalid.
2456 return SourceRange();
2457 }
2458 llvm_unreachable("Invalid default argument kind.");
2459}
2460
2461void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2462 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2463 Init = arg;
2464}
2465
2466Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2467 assert(hasUninstantiatedDefaultArg() &&
2468 "Wrong kind of initialization expression!");
2469 return cast_or_null<Expr>(Init.get<Stmt *>());
2470}
2471
2472bool ParmVarDecl::hasDefaultArg() const {
2473 // FIXME: We should just return false for DAK_None here once callers are
2474 // prepared for the case that we encountered an invalid default argument and
2475 // were unable to even build an invalid expression.
2476 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2477 !Init.isNull();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002478}
2479
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00002480bool ParmVarDecl::isParameterPack() const {
2481 return isa<PackExpansionType>(getType());
2482}
2483
Ted Kremenek540017e2011-10-06 05:00:56 +00002484void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2485 getASTContext().setParameterIndex(this, parameterIndex);
2486 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2487}
2488
2489unsigned ParmVarDecl::getParameterIndexLarge() const {
2490 return getASTContext().getParameterIndex(this);
2491}
2492
Nuno Lopes394ec982008-12-17 23:39:55 +00002493//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002494// FunctionDecl Implementation
2495//===----------------------------------------------------------------------===//
2496
Benjamin Kramer9170e912013-02-22 15:46:01 +00002497void FunctionDecl::getNameForDiagnostic(
2498 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2499 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002500 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2501 if (TemplateArgs)
Benjamin Kramer9170e912013-02-22 15:46:01 +00002502 TemplateSpecializationType::PrintTemplateArgumentList(
David Majnemer6fbeee32016-07-07 04:43:07 +00002503 OS, TemplateArgs->asArray(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002504}
2505
Ted Kremenek186a0742010-04-29 16:49:01 +00002506bool FunctionDecl::isVariadic() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002507 if (const auto *FT = getType()->getAs<FunctionProtoType>())
Ted Kremenek186a0742010-04-29 16:49:01 +00002508 return FT->isVariadic();
2509 return false;
2510}
2511
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002512bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002513 for (auto I : redecls()) {
Serge Pavlov9a618e12017-02-15 12:30:35 +00002514 if (I->doesThisDeclarationHaveABody()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002515 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002516 return true;
2517 }
2518 }
2519
2520 return false;
2521}
2522
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002523bool FunctionDecl::hasTrivialBody() const
2524{
2525 Stmt *S = getBody();
2526 if (!S) {
2527 // Since we don't have a body for this function, we don't know if it's
2528 // trivial or not.
2529 return false;
2530 }
2531
2532 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2533 return true;
2534 return false;
2535}
2536
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002537bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002538 for (auto I : redecls()) {
Serge Pavlov10673c92017-06-04 12:53:12 +00002539 if (I->isThisDeclarationADefinition()) {
2540 Definition = I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002541 return true;
2542 }
2543 }
2544
2545 return false;
2546}
2547
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002548Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002549 if (!hasBody(Definition))
Craig Topper36250ad2014-05-12 05:36:57 +00002550 return nullptr;
Rafael Espindola44503012013-10-19 01:37:17 +00002551
2552 if (Definition->Body)
2553 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002554
Craig Topper36250ad2014-05-12 05:36:57 +00002555 return nullptr;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002556}
2557
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002558void FunctionDecl::setBody(Stmt *B) {
2559 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002560 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002561 EndRangeLoc = B->getLocEnd();
2562}
2563
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002564void FunctionDecl::setPure(bool P) {
2565 IsPure = P;
2566 if (P)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002567 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002568 Parent->markedVirtualFunctionPure();
2569}
2570
Richard Smith8d0dc312013-07-21 23:12:18 +00002571template<std::size_t Len>
2572static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2573 IdentifierInfo *II = ND->getIdentifier();
2574 return II && II->isStr(Str);
2575}
2576
Douglas Gregor16618f22009-09-12 00:17:51 +00002577bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002578 const TranslationUnitDecl *tunit =
2579 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2580 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002581 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002582 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002583}
2584
David Majnemerc729b0b2013-09-16 22:44:20 +00002585bool FunctionDecl::isMSVCRTEntryPoint() const {
2586 const TranslationUnitDecl *TUnit =
2587 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2588 if (!TUnit)
2589 return false;
2590
2591 // Even though we aren't really targeting MSVCRT if we are freestanding,
2592 // semantic analysis for these functions remains the same.
2593
2594 // MSVCRT entry points only exist on MSVCRT targets.
2595 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2596 return false;
2597
2598 // Nameless functions like constructors cannot be entry points.
2599 if (!getIdentifier())
2600 return false;
2601
2602 return llvm::StringSwitch<bool>(getName())
2603 .Cases("main", // an ANSI console app
2604 "wmain", // a Unicode console App
2605 "WinMain", // an ANSI GUI app
2606 "wWinMain", // a Unicode GUI app
2607 "DllMain", // a DLL
2608 true)
2609 .Default(false);
2610}
2611
John McCall53ffd372011-05-15 17:49:20 +00002612bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2613 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2614 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2615 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2616 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2617 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2618
Richard Smithf6004412014-01-19 23:25:37 +00002619 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2620 return false;
John McCall53ffd372011-05-15 17:49:20 +00002621
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002622 const auto *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002623 if (proto->getNumParams() != 2 || proto->isVariadic())
2624 return false;
John McCall53ffd372011-05-15 17:49:20 +00002625
2626 ASTContext &Context =
2627 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2628 ->getASTContext();
2629
2630 // The result type and first argument type are constant across all
2631 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002632 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002633}
2634
Akira Hatanakacae83f72017-06-29 18:48:40 +00002635bool FunctionDecl::isReplaceableGlobalAllocationFunction(bool *IsAligned) const {
Richard Smith8d0dc312013-07-21 23:12:18 +00002636 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2637 return false;
2638 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2639 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2640 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2641 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2642 return false;
2643
2644 if (isa<CXXRecordDecl>(getDeclContext()))
2645 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002646
2647 // This can only fail for an invalid 'operator new' declaration.
2648 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2649 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002650
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002651 const auto *FPT = getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00002652 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002653 return false;
2654
2655 // If this is a single-parameter function, it must be a replaceable global
2656 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002657 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002658 return true;
2659
Richard Smithb2f0f052016-10-10 18:54:32 +00002660 unsigned Params = 1;
2661 QualType Ty = FPT->getParamType(Params);
Richard Smith1cdec012013-09-29 04:40:38 +00002662 ASTContext &Ctx = getASTContext();
Richard Smithb2f0f052016-10-10 18:54:32 +00002663
2664 auto Consume = [&] {
2665 ++Params;
2666 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
2667 };
2668
2669 // In C++14, the next parameter can be a 'std::size_t' for sized delete.
2670 bool IsSizedDelete = false;
Richard Smithb47c36f2013-11-05 09:12:18 +00002671 if (Ctx.getLangOpts().SizedDeallocation &&
Richard Smithb2f0f052016-10-10 18:54:32 +00002672 (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2673 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
2674 Ctx.hasSameType(Ty, Ctx.getSizeType())) {
2675 IsSizedDelete = true;
2676 Consume();
2677 }
2678
2679 // In C++17, the next parameter can be a 'std::align_val_t' for aligned
2680 // new/delete.
Akira Hatanakacae83f72017-06-29 18:48:40 +00002681 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
2682 if (IsAligned)
2683 *IsAligned = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00002684 Consume();
Akira Hatanakacae83f72017-06-29 18:48:40 +00002685 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002686
2687 // Finally, if this is not a sized delete, the final parameter can
2688 // be a 'const std::nothrow_t&'.
2689 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
2690 Ty = Ty->getPointeeType();
2691 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2692 return false;
2693 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2694 if (RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace())
2695 Consume();
2696 }
2697
2698 return Params == FPT->getNumParams();
Richard Smith8d0dc312013-07-21 23:12:18 +00002699}
2700
Rafael Espindolaf4187652013-02-14 01:18:37 +00002701LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00002702 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002703}
2704
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002705bool FunctionDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00002706 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002707}
2708
Rafael Espindola593537a2013-05-05 20:15:21 +00002709bool FunctionDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002710 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002711}
2712
2713bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002714 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002715}
2716
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002717bool FunctionDecl::isGlobal() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002718 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002719 return Method->isStatic();
2720
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002721 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002722 return false;
2723
Mike Stump11289f42009-09-09 15:08:12 +00002724 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002725 DC->isNamespace();
2726 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002727 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002728 if (!Namespace->getDeclName())
2729 return false;
2730 break;
2731 }
2732 }
2733
2734 return true;
2735}
2736
Richard Smith10876ef2013-01-17 01:30:42 +00002737bool FunctionDecl::isNoReturn() const {
Adrian Prantl721c7cb2016-08-17 16:42:15 +00002738 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2739 hasAttr<C11NoReturnAttr>())
2740 return true;
2741
2742 if (auto *FnTy = getType()->getAs<FunctionType>())
2743 return FnTy->getNoReturnAttr();
2744
2745 return false;
Richard Smith10876ef2013-01-17 01:30:42 +00002746}
2747
Sebastian Redl833ef452010-01-26 22:01:41 +00002748void
2749FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002750 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002751
2752 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2753 FunctionTemplateDecl *PrevFunTmpl
Craig Topper36250ad2014-05-12 05:36:57 +00002754 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002755 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00002756 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002757 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002758
Axel Naumannfbc7b982011-11-08 18:21:06 +00002759 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002760 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002761}
2762
Rafael Espindola8db352d2013-10-17 15:37:26 +00002763FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002764
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002765/// \brief Returns a value indicating whether this function
2766/// corresponds to a builtin function.
2767///
2768/// The function corresponds to a built-in function if it is
2769/// declared at translation scope or within an extern "C" block and
2770/// its name matches with the name of a builtin. The returned value
2771/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002772/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002773/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002774unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002775 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002776 return 0;
2777
2778 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002779 if (!BuiltinID)
2780 return 0;
2781
2782 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00002783 if (Context.getLangOpts().CPlusPlus) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002784 const auto *LinkageDecl =
2785 dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
Warren Hunt445d83e2013-11-01 23:46:51 +00002786 // In C++, the first declaration of a builtin is always inside an implicit
2787 // extern "C".
2788 // FIXME: A recognised library function may not be directly in an extern "C"
2789 // declaration, for instance "extern "C" { namespace std { decl } }".
David Majnemerba3e5ec2015-03-13 18:26:17 +00002790 if (!LinkageDecl) {
2791 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
David Majnemer145abde2016-01-26 01:12:17 +00002792 Context.getTargetInfo().getCXXABI().isMicrosoft())
David Majnemerba3e5ec2015-03-13 18:26:17 +00002793 return Builtin::BI__GetExceptionInfo;
2794 return 0;
2795 }
2796 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
Warren Hunt445d83e2013-11-01 23:46:51 +00002797 return 0;
2798 }
2799
2800 // If the function is marked "overloadable", it has a different mangled name
2801 // and is not the C library function.
Aaron Ballman9ead1242013-12-19 02:39:40 +00002802 if (hasAttr<OverloadableAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00002803 return 0;
2804
Douglas Gregore711f702009-02-14 18:57:46 +00002805 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2806 return BuiltinID;
2807
2808 // This function has the name of a known C library
2809 // function. Determine whether it actually refers to the C library
2810 // function or whether it just has the same name.
2811
Douglas Gregora908e7f2009-02-17 03:23:10 +00002812 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002813 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002814 return 0;
2815
Anastasia Stulova1202de32016-02-12 12:07:04 +00002816 // OpenCL v1.2 s6.9.f - The library functions defined in
2817 // the C99 standard headers are not available.
2818 if (Context.getLangOpts().OpenCL &&
2819 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2820 return 0;
2821
Warren Hunt445d83e2013-11-01 23:46:51 +00002822 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002823}
2824
2825
Chris Lattner47c0d002009-04-25 06:03:53 +00002826/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002827/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002828/// after it has been created.
2829unsigned FunctionDecl::getNumParams() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002830 const auto *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002831 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002832}
2833
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002834void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002835 ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00002836 assert(!ParamInfo && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002837 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002838
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002839 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002840 if (!NewParamInfo.empty()) {
2841 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2842 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002843 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002844}
Chris Lattner41943152007-01-25 04:52:46 +00002845
Chris Lattner58258242008-04-10 02:22:51 +00002846/// getMinRequiredArguments - Returns the minimum number of arguments
2847/// needed to call this function. This may be fewer than the number of
2848/// function parameters, if some of the parameters have default
Richard Smith91151782014-04-01 19:18:16 +00002849/// arguments (in C++) or are parameter packs (C++11).
Chris Lattner58258242008-04-10 02:22:51 +00002850unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002851 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002852 return getNumParams();
Chris Lattner58258242008-04-10 02:22:51 +00002853
Richard Smith91151782014-04-01 19:18:16 +00002854 unsigned NumRequiredArgs = 0;
David Majnemer59f77922016-06-24 04:05:48 +00002855 for (auto *Param : parameters())
Richard Smith91151782014-04-01 19:18:16 +00002856 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2857 ++NumRequiredArgs;
Chris Lattner58258242008-04-10 02:22:51 +00002858 return NumRequiredArgs;
2859}
2860
David Majnemer54e3ba52014-04-02 23:17:29 +00002861/// \brief The combination of the extern and inline keywords under MSVC forces
2862/// the function to be required.
2863///
2864/// Note: This function assumes that we will only get called when isInlined()
2865/// would return true for this FunctionDecl.
2866bool FunctionDecl::isMSExternInline() const {
2867 assert(isInlined() && "expected to get called on an inlined function!");
2868
2869 const ASTContext &Context = getASTContext();
David Majnemer3f021502015-10-08 04:53:31 +00002870 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2871 !hasAttr<DLLExportAttr>())
David Majnemer54e3ba52014-04-02 23:17:29 +00002872 return false;
2873
David Majnemer73768702015-03-20 00:02:27 +00002874 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
2875 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002876 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002877 return true;
2878
2879 return false;
2880}
2881
2882static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
2883 if (Redecl->getStorageClass() != SC_Extern)
2884 return false;
2885
2886 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
2887 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002888 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002889 return false;
2890
2891 return true;
2892}
2893
Eli Friedman1b125c32012-02-07 03:50:18 +00002894static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2895 // Only consider file-scope declarations in this test.
2896 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2897 return false;
2898
2899 // Only consider explicit declarations; the presence of a builtin for a
2900 // libcall shouldn't affect whether a definition is externally visible.
2901 if (Redecl->isImplicit())
2902 return false;
2903
2904 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2905 return true; // Not an inline definition
2906
2907 return false;
2908}
2909
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002910/// \brief For a function declaration in C or C++, determine whether this
2911/// declaration causes the definition to be externally visible.
2912///
David Majnemer54e3ba52014-04-02 23:17:29 +00002913/// For instance, this determines if adding the current declaration to the set
Eli Friedman1b125c32012-02-07 03:50:18 +00002914/// of redeclarations of the given functions causes
2915/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002916bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
Justin Lebar0241c962016-10-28 16:46:39 +00002917 assert(!doesThisDeclarationHaveABody() &&
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002918 "Must have a declaration without a body.");
2919
2920 ASTContext &Context = getASTContext();
2921
David Majnemer54e3ba52014-04-02 23:17:29 +00002922 if (Context.getLangOpts().MSVCCompat) {
2923 const FunctionDecl *Definition;
2924 if (hasBody(Definition) && Definition->isInlined() &&
2925 redeclForcesDefMSVC(this))
2926 return true;
2927 }
2928
David Blaikiebbafb8a2012-03-11 07:00:24 +00002929 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002930 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2931 // an externally visible definition.
2932 //
2933 // FIXME: What happens if gnu_inline gets added on after the first
2934 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002935 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002936 return false;
2937
2938 const FunctionDecl *Prev = this;
2939 bool FoundBody = false;
2940 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002941 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002942
2943 if (Prev->Body) {
2944 // If it's not the case that both 'inline' and 'extern' are
2945 // specified on the definition, then it is always externally visible.
2946 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002947 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002948 return false;
2949 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002950 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002951 return false;
2952 }
2953 }
2954 return FoundBody;
2955 }
2956
David Blaikiebbafb8a2012-03-11 07:00:24 +00002957 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002958 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002959
2960 // C99 6.7.4p6:
2961 // [...] If all of the file scope declarations for a function in a
2962 // translation unit include the inline function specifier without extern,
2963 // then the definition in that translation unit is an inline definition.
2964 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002965 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002966 const FunctionDecl *Prev = this;
2967 bool FoundBody = false;
2968 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002969 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002970 if (RedeclForcesDefC99(Prev))
2971 return false;
2972 }
2973 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002974}
2975
Alp Tokerd0787eb2014-07-02 01:47:15 +00002976SourceRange FunctionDecl::getReturnTypeSourceRange() const {
2977 const TypeSourceInfo *TSI = getTypeSourceInfo();
2978 if (!TSI)
2979 return SourceRange();
Alp Tokerf5b10792014-07-02 12:55:58 +00002980 FunctionTypeLoc FTL =
2981 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
2982 if (!FTL)
Alp Tokerd0787eb2014-07-02 01:47:15 +00002983 return SourceRange();
2984
Alp Tokerf5b10792014-07-02 12:55:58 +00002985 // Skip self-referential return types.
2986 const SourceManager &SM = getASTContext().getSourceManager();
2987 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
2988 SourceLocation Boundary = getNameInfo().getLocStart();
2989 if (RTRange.isInvalid() || Boundary.isInvalid() ||
2990 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
2991 return SourceRange();
Alp Tokerd0787eb2014-07-02 01:47:15 +00002992
Alp Tokerf5b10792014-07-02 12:55:58 +00002993 return RTRange;
Alp Tokerd0787eb2014-07-02 01:47:15 +00002994}
2995
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00002996SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
2997 const TypeSourceInfo *TSI = getTypeSourceInfo();
2998 if (!TSI)
2999 return SourceRange();
3000 FunctionTypeLoc FTL =
3001 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
3002 if (!FTL)
3003 return SourceRange();
3004
3005 return FTL.getExceptionSpecRange();
3006}
3007
Aaron Ballmane7964782016-03-07 22:44:55 +00003008const Attr *FunctionDecl::getUnusedResultAttr() const {
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003009 QualType RetType = getReturnType();
3010 if (RetType->isRecordType()) {
Erich Keane4b87d812017-04-19 21:24:55 +00003011 if (const CXXRecordDecl *Ret = RetType->getAsCXXRecordDecl()) {
Aaron Ballmane7964782016-03-07 22:44:55 +00003012 if (const auto *R = Ret->getAttr<WarnUnusedResultAttr>())
3013 return R;
3014 }
3015 } else if (const auto *ET = RetType->getAs<EnumType>()) {
3016 if (const EnumDecl *ED = ET->getDecl()) {
3017 if (const auto *R = ED->getAttr<WarnUnusedResultAttr>())
3018 return R;
3019 }
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003020 }
Aaron Ballmane7964782016-03-07 22:44:55 +00003021 return getAttr<WarnUnusedResultAttr>();
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003022}
3023
Richard Smithf3814ad2013-01-25 00:08:28 +00003024/// \brief For an inline function definition in C, or for a gnu_inline function
3025/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00003026///
3027/// Inline function definitions are always available for inlining optimizations.
3028/// However, depending on the language dialect, declaration specifiers, and
3029/// attributes, the definition of an inline function may or may not be
3030/// "externally" visible to other translation units in the program.
3031///
3032/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00003033/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00003034/// inline definition becomes externally visible (C99 6.7.4p6).
3035///
3036/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3037/// definition, we use the GNU semantics for inline, which are nearly the
3038/// opposite of C99 semantics. In particular, "inline" by itself will create
3039/// an externally visible symbol, but "extern inline" will not create an
3040/// externally visible symbol.
3041bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Manuel Klimekda7456a2016-11-01 10:30:50 +00003042 assert((doesThisDeclarationHaveABody() || willHaveBody()) &&
3043 "Must be a function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003044 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00003045 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00003046
David Blaikiebbafb8a2012-03-11 07:00:24 +00003047 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003048 // Note: If you change the logic here, please change
3049 // doesDeclarationForceExternallyVisibleDefinition as well.
3050 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00003051 // If it's not the case that both 'inline' and 'extern' are
3052 // specified on the definition, then this inline definition is
3053 // externally visible.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003054 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00003055 return true;
3056
3057 // If any declaration is 'inline' but not 'extern', then this definition
3058 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00003059 for (auto Redecl : redecls()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00003060 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003061 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00003062 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00003063 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00003064
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003065 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003066 }
Eli Friedman1b125c32012-02-07 03:50:18 +00003067
Richard Smithf3814ad2013-01-25 00:08:28 +00003068 // The rest of this function is C-only.
3069 assert(!Context.getLangOpts().CPlusPlus &&
3070 "should not use C inline rules in C++");
3071
Douglas Gregor299d76e2009-09-13 07:46:26 +00003072 // C99 6.7.4p6:
3073 // [...] If all of the file scope declarations for a function in a
3074 // translation unit include the inline function specifier without extern,
3075 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00003076 for (auto Redecl : redecls()) {
3077 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00003078 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003079 }
3080
3081 // C99 6.7.4p6:
3082 // An inline definition does not provide an external definition for the
3083 // function, and does not forbid an external definition in another
3084 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003085 return false;
3086}
3087
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003088/// getOverloadedOperator - Which C++ overloaded operator this
3089/// function represents, if any.
3090OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00003091 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3092 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003093 else
3094 return OO_None;
3095}
3096
Alexis Huntc88db062010-01-13 09:01:02 +00003097/// getLiteralIdentifier - The literal suffix identifier this function
3098/// represents, if any.
3099const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3100 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3101 return getDeclName().getCXXLiteralIdentifier();
3102 else
Craig Topper36250ad2014-05-12 05:36:57 +00003103 return nullptr;
Alexis Huntc88db062010-01-13 09:01:02 +00003104}
3105
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003106FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3107 if (TemplateOrSpecialization.isNull())
3108 return TK_NonTemplate;
3109 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3110 return TK_FunctionTemplate;
3111 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3112 return TK_MemberSpecialization;
3113 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3114 return TK_FunctionTemplateSpecialization;
3115 if (TemplateOrSpecialization.is
3116 <DependentFunctionTemplateSpecializationInfo*>())
3117 return TK_DependentFunctionTemplateSpecialization;
3118
David Blaikie83d382b2011-09-23 05:06:16 +00003119 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003120}
3121
Douglas Gregord801b062009-10-07 23:56:10 +00003122FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00003123 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00003124 return cast<FunctionDecl>(Info->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00003125
3126 return nullptr;
Douglas Gregord801b062009-10-07 23:56:10 +00003127}
3128
Chandler Carruth21c90602015-12-30 03:24:14 +00003129MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3130 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>();
3131}
3132
Douglas Gregord801b062009-10-07 23:56:10 +00003133void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003134FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3135 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00003136 TemplateSpecializationKind TSK) {
3137 assert(TemplateOrSpecialization.isNull() &&
3138 "Member function is already a specialization");
3139 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003140 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00003141 TemplateOrSpecialization = Info;
3142}
3143
Chandler Carruth21c90602015-12-30 03:24:14 +00003144FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3145 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3146}
3147
3148void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3149 TemplateOrSpecialization = Template;
3150}
3151
Douglas Gregorafca3b42009-10-27 20:53:28 +00003152bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00003153 // If the function is invalid, it can't be implicitly instantiated.
3154 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00003155 return false;
3156
3157 switch (getTemplateSpecializationKind()) {
3158 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00003159 case TSK_ExplicitInstantiationDefinition:
3160 return false;
3161
3162 case TSK_ImplicitInstantiation:
3163 return true;
3164
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003165 // It is possible to instantiate TSK_ExplicitSpecialization kind
3166 // if the FunctionDecl has a class scope specialization pattern.
3167 case TSK_ExplicitSpecialization:
Craig Topper36250ad2014-05-12 05:36:57 +00003168 return getClassScopeSpecializationPattern() != nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003169
Douglas Gregorafca3b42009-10-27 20:53:28 +00003170 case TSK_ExplicitInstantiationDeclaration:
3171 // Handled below.
3172 break;
3173 }
3174
3175 // Find the actual template from which we will instantiate.
3176 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003177 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003178 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003179 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00003180
3181 // C++0x [temp.explicit]p9:
3182 // Except for inline functions, other explicit instantiation declarations
3183 // have the effect of suppressing the implicit instantiation of the entity
3184 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003185 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00003186 return true;
3187
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003188 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00003189}
3190
3191bool FunctionDecl::isTemplateInstantiation() const {
3192 switch (getTemplateSpecializationKind()) {
3193 case TSK_Undeclared:
3194 case TSK_ExplicitSpecialization:
3195 return false;
3196 case TSK_ImplicitInstantiation:
3197 case TSK_ExplicitInstantiationDeclaration:
3198 case TSK_ExplicitInstantiationDefinition:
3199 return true;
3200 }
3201 llvm_unreachable("All TSK values handled.");
3202}
Douglas Gregorafca3b42009-10-27 20:53:28 +00003203
3204FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003205 // Handle class scope explicit specialization special case.
Richard Smith2195ec92017-04-21 01:15:13 +00003206 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
3207 if (auto *Spec = getClassScopeSpecializationPattern())
3208 return getDefinitionOrSelf(Spec);
3209 return nullptr;
3210 }
3211
Faisal Valib90b2112014-04-03 16:32:21 +00003212 // If this is a generic lambda call operator specialization, its
3213 // instantiation pattern is always its primary template's pattern
3214 // even if its primary template was instantiated from another
3215 // member template (which happens with nested generic lambdas).
3216 // Since a lambda's call operator's body is transformed eagerly,
3217 // we don't have to go hunting for a prototype definition template
3218 // (i.e. instantiated-from-member-template) to use as an instantiation
3219 // pattern.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003220
Faisal Valib90b2112014-04-03 16:32:21 +00003221 if (isGenericLambdaCallOperatorSpecialization(
3222 dyn_cast<CXXMethodDecl>(this))) {
Richard Smith2195ec92017-04-21 01:15:13 +00003223 assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3224 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
Faisal Valib90b2112014-04-03 16:32:21 +00003225 }
Richard Smith2195ec92017-04-21 01:15:13 +00003226
Douglas Gregorafca3b42009-10-27 20:53:28 +00003227 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3228 while (Primary->getInstantiatedFromMemberTemplate()) {
3229 // If we have hit a point where the user provided a specialization of
3230 // this template, we're done looking.
3231 if (Primary->isMemberSpecialization())
3232 break;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003233 Primary = Primary->getInstantiatedFromMemberTemplate();
3234 }
Richard Smith2195ec92017-04-21 01:15:13 +00003235
3236 return getDefinitionOrSelf(Primary->getTemplatedDecl());
Douglas Gregorafca3b42009-10-27 20:53:28 +00003237 }
Richard Smith2195ec92017-04-21 01:15:13 +00003238
3239 if (auto *MFD = getInstantiatedFromMemberFunction())
3240 return getDefinitionOrSelf(MFD);
3241
3242 return nullptr;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003243}
3244
Douglas Gregor70d83e22009-06-29 17:30:29 +00003245FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00003246 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003247 = TemplateOrSpecialization
3248 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00003249 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00003250 }
Craig Topper36250ad2014-05-12 05:36:57 +00003251 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003252}
3253
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003254FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3255 return getASTContext().getClassScopeSpecializationPattern(this);
3256}
3257
Chandler Carruth21c90602015-12-30 03:24:14 +00003258FunctionTemplateSpecializationInfo *
3259FunctionDecl::getTemplateSpecializationInfo() const {
3260 return TemplateOrSpecialization
3261 .dyn_cast<FunctionTemplateSpecializationInfo *>();
3262}
3263
Douglas Gregor70d83e22009-06-29 17:30:29 +00003264const TemplateArgumentList *
3265FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00003266 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00003267 = TemplateOrSpecialization
3268 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003269 return Info->TemplateArguments;
3270 }
Craig Topper36250ad2014-05-12 05:36:57 +00003271 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003272}
3273
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00003274const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003275FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3276 if (FunctionTemplateSpecializationInfo *Info
3277 = TemplateOrSpecialization
3278 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3279 return Info->TemplateArgumentsAsWritten;
3280 }
Craig Topper36250ad2014-05-12 05:36:57 +00003281 return nullptr;
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003282}
3283
Mike Stump11289f42009-09-09 15:08:12 +00003284void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003285FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3286 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003287 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003288 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003289 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00003290 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3291 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003292 assert(TSK != TSK_Undeclared &&
3293 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00003294 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003295 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003296 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00003297 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3298 TemplateArgs,
3299 TemplateArgsAsWritten,
3300 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003301 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00003302 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003303}
3304
John McCallb9c78482010-04-08 09:05:18 +00003305void
3306FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3307 const UnresolvedSetImpl &Templates,
3308 const TemplateArgumentListInfo &TemplateArgs) {
3309 assert(TemplateOrSpecialization.isNull());
John McCallb9c78482010-04-08 09:05:18 +00003310 DependentFunctionTemplateSpecializationInfo *Info =
James Y Knight7a22b242015-08-06 20:26:32 +00003311 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3312 TemplateArgs);
John McCallb9c78482010-04-08 09:05:18 +00003313 TemplateOrSpecialization = Info;
3314}
3315
James Y Knight7a22b242015-08-06 20:26:32 +00003316DependentFunctionTemplateSpecializationInfo *
Chandler Carruth21c90602015-12-30 03:24:14 +00003317FunctionDecl::getDependentSpecializationInfo() const {
3318 return TemplateOrSpecialization
3319 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3320}
3321
3322DependentFunctionTemplateSpecializationInfo *
James Y Knight7a22b242015-08-06 20:26:32 +00003323DependentFunctionTemplateSpecializationInfo::Create(
3324 ASTContext &Context, const UnresolvedSetImpl &Ts,
3325 const TemplateArgumentListInfo &TArgs) {
3326 void *Buffer = Context.Allocate(
3327 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3328 TArgs.size(), Ts.size()));
3329 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3330}
3331
John McCallb9c78482010-04-08 09:05:18 +00003332DependentFunctionTemplateSpecializationInfo::
3333DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3334 const TemplateArgumentListInfo &TArgs)
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003335 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
John McCallb9c78482010-04-08 09:05:18 +00003336
James Y Knight53c76162015-07-17 18:21:37 +00003337 NumTemplates = Ts.size();
3338 NumArgs = TArgs.size();
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003339
James Y Knight7a22b242015-08-06 20:26:32 +00003340 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
John McCallb9c78482010-04-08 09:05:18 +00003341 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3342 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3343
James Y Knight7a22b242015-08-06 20:26:32 +00003344 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
John McCallb9c78482010-04-08 09:05:18 +00003345 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3346 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3347}
3348
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003349TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00003350 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003351 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00003352 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00003353 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00003354 if (FTSInfo)
3355 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00003356
Douglas Gregord801b062009-10-07 23:56:10 +00003357 MemberSpecializationInfo *MSInfo
3358 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3359 if (MSInfo)
3360 return MSInfo->getTemplateSpecializationKind();
3361
3362 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003363}
3364
Mike Stump11289f42009-09-09 15:08:12 +00003365void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003366FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3367 SourceLocation PointOfInstantiation) {
3368 if (FunctionTemplateSpecializationInfo *FTSInfo
3369 = TemplateOrSpecialization.dyn_cast<
3370 FunctionTemplateSpecializationInfo*>()) {
3371 FTSInfo->setTemplateSpecializationKind(TSK);
3372 if (TSK != TSK_ExplicitSpecialization &&
3373 PointOfInstantiation.isValid() &&
3374 FTSInfo->getPointOfInstantiation().isInvalid())
3375 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3376 } else if (MemberSpecializationInfo *MSInfo
3377 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3378 MSInfo->setTemplateSpecializationKind(TSK);
3379 if (TSK != TSK_ExplicitSpecialization &&
3380 PointOfInstantiation.isValid() &&
3381 MSInfo->getPointOfInstantiation().isInvalid())
3382 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3383 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003384 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003385}
3386
3387SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00003388 if (FunctionTemplateSpecializationInfo *FTSInfo
3389 = TemplateOrSpecialization.dyn_cast<
3390 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003391 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00003392 else if (MemberSpecializationInfo *MSInfo
3393 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003394 return MSInfo->getPointOfInstantiation();
3395
3396 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00003397}
3398
Douglas Gregor6411b922009-09-11 20:15:17 +00003399bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00003400 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00003401 return true;
3402
3403 // If this function was instantiated from a member function of a
3404 // class template, check whether that member function was defined out-of-line.
3405 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3406 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003407 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003408 return Definition->isOutOfLine();
3409 }
3410
3411 // If this function was instantiated from a function template,
3412 // check whether that function template was defined out-of-line.
3413 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3414 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003415 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003416 return Definition->isOutOfLine();
3417 }
3418
3419 return false;
3420}
3421
Abramo Bagnaraea947882011-03-08 16:41:52 +00003422SourceRange FunctionDecl::getSourceRange() const {
3423 return SourceRange(getOuterLocStart(), EndRangeLoc);
3424}
3425
Anna Zaks28db7ce2012-01-18 02:45:01 +00003426unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00003427 IdentifierInfo *FnInfo = getIdentifier();
3428
3429 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00003430 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003431
3432 // Builtin handling.
3433 switch (getBuiltinID()) {
3434 case Builtin::BI__builtin_memset:
3435 case Builtin::BI__builtin___memset_chk:
3436 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003437 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003438
3439 case Builtin::BI__builtin_memcpy:
3440 case Builtin::BI__builtin___memcpy_chk:
3441 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003442 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003443
3444 case Builtin::BI__builtin_memmove:
3445 case Builtin::BI__builtin___memmove_chk:
3446 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003447 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003448
3449 case Builtin::BIstrlcpy:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003450 case Builtin::BI__builtin___strlcpy_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003451 return Builtin::BIstrlcpy;
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003452
Anna Zaks201d4892012-01-13 21:52:01 +00003453 case Builtin::BIstrlcat:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003454 case Builtin::BI__builtin___strlcat_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003455 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003456
3457 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003458 case Builtin::BImemcmp:
3459 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003460
3461 case Builtin::BI__builtin_strncpy:
3462 case Builtin::BI__builtin___strncpy_chk:
3463 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003464 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003465
3466 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003467 case Builtin::BIstrncmp:
3468 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003469
3470 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003471 case Builtin::BIstrncasecmp:
3472 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003473
3474 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003475 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003476 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003477 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003478
3479 case Builtin::BI__builtin_strndup:
3480 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003481 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003482
Anna Zaks314cd092012-02-01 19:08:57 +00003483 case Builtin::BI__builtin_strlen:
3484 case Builtin::BIstrlen:
3485 return Builtin::BIstrlen;
3486
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003487 case Builtin::BI__builtin_bzero:
3488 case Builtin::BIbzero:
3489 return Builtin::BIbzero;
3490
Anna Zaks201d4892012-01-13 21:52:01 +00003491 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003492 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003493 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003494 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003495 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003496 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003497 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003498 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003499 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003500 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003501 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003502 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003503 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003504 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003505 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003506 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003507 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003508 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003509 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003510 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003511 else if (FnInfo->isStr("strlen"))
3512 return Builtin::BIstrlen;
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003513 else if (FnInfo->isStr("bzero"))
3514 return Builtin::BIbzero;
Anna Zaks201d4892012-01-13 21:52:01 +00003515 }
3516 break;
3517 }
Anna Zaks22122702012-01-17 00:37:07 +00003518 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003519}
3520
Chris Lattner59a25942008-03-31 00:36:02 +00003521//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003522// FieldDecl Implementation
3523//===----------------------------------------------------------------------===//
3524
Jay Foad39c79802011-01-12 09:06:06 +00003525FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003526 SourceLocation StartLoc, SourceLocation IdLoc,
3527 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003528 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003529 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003530 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3531 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003532}
3533
Douglas Gregor72172e92012-01-05 21:55:30 +00003534FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003535 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3536 SourceLocation(), nullptr, QualType(), nullptr,
3537 nullptr, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00003538}
3539
Sebastian Redl833ef452010-01-26 22:01:41 +00003540bool FieldDecl::isAnonymousStructOrUnion() const {
3541 if (!isImplicit() || getDeclName())
3542 return false;
3543
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003544 if (const auto *Record = getType()->getAs<RecordType>())
Sebastian Redl833ef452010-01-26 22:01:41 +00003545 return Record->getDecl()->isAnonymousStructOrUnion();
3546
3547 return false;
3548}
3549
Richard Smithcaf33902011-10-10 18:28:20 +00003550unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3551 assert(isBitField() && "not a bitfield");
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003552 auto *BitWidth = static_cast<Expr *>(InitStorage.getPointer());
Richard Smithcaf33902011-10-10 18:28:20 +00003553 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3554}
3555
John McCall4e819612011-01-20 07:57:12 +00003556unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00003557 const FieldDecl *Canonical = getCanonicalDecl();
3558 if (Canonical != this)
3559 return Canonical->getFieldIndex();
3560
John McCall4e819612011-01-20 07:57:12 +00003561 if (CachedFieldIndex) return CachedFieldIndex - 1;
3562
Richard Smithd62306a2011-11-10 06:34:14 +00003563 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00003564 const RecordDecl *RD = getParent();
Richard Smithd62306a2011-11-10 06:34:14 +00003565
Hans Wennborga302cd92014-08-21 16:06:57 +00003566 for (auto *Field : RD->fields()) {
3567 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3568 ++Index;
3569 }
John McCall4e819612011-01-20 07:57:12 +00003570
Richard Smithd62306a2011-11-10 06:34:14 +00003571 assert(CachedFieldIndex && "failed to find field in parent");
3572 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00003573}
3574
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003575SourceRange FieldDecl::getSourceRange() const {
John McCallc90c1492014-10-10 18:44:34 +00003576 switch (InitStorage.getInt()) {
3577 // All three of these cases store an optional Expr*.
3578 case ISK_BitWidthOrNothing:
3579 case ISK_InClassCopyInit:
3580 case ISK_InClassListInit:
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003581 if (const auto *E = static_cast<const Expr *>(InitStorage.getPointer()))
John McCallc90c1492014-10-10 18:44:34 +00003582 return SourceRange(getInnerLocStart(), E->getLocEnd());
3583 // FALLTHROUGH
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003584
John McCallc90c1492014-10-10 18:44:34 +00003585 case ISK_CapturedVLAType:
3586 return DeclaratorDecl::getSourceRange();
3587 }
3588 llvm_unreachable("bad init storage kind");
Alexey Bataev39c81e22014-08-28 04:28:19 +00003589}
3590
3591void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
David Blaikie11ab0782014-10-31 17:18:09 +00003592 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
Alexey Bataev330de032014-10-29 12:21:55 +00003593 "capturing type in non-lambda or captured record.");
John McCallc90c1492014-10-10 18:44:34 +00003594 assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
3595 InitStorage.getPointer() == nullptr &&
Alexey Bataev39c81e22014-08-28 04:28:19 +00003596 "bit width, initializer or captured type already set");
John McCallc90c1492014-10-10 18:44:34 +00003597 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3598 ISK_CapturedVLAType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00003599}
3600
Sebastian Redl833ef452010-01-26 22:01:41 +00003601//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003602// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00003603//===----------------------------------------------------------------------===//
3604
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003605SourceLocation TagDecl::getOuterLocStart() const {
3606 return getTemplateOrInnerLocStart(this);
3607}
3608
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003609SourceRange TagDecl::getSourceRange() const {
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003610 SourceLocation RBraceLoc = BraceRange.getEnd();
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003611 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003612 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003613}
3614
Rafael Espindola8db352d2013-10-17 15:37:26 +00003615TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00003616
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00003617void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer00350522015-08-31 18:48:39 +00003618 TypedefNameDeclOrQualifier = TDD;
Reid Klecknercae82a22014-04-23 22:03:04 +00003619 if (const Type *T = getTypeForDecl()) {
3620 (void)T;
Richard Smith5b21db82014-04-23 18:20:42 +00003621 assert(T->isLinkageValid());
Reid Klecknercae82a22014-04-23 22:03:04 +00003622 }
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003623 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00003624}
3625
Douglas Gregordee1be82009-01-17 00:42:38 +00003626void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003627 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00003628
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003629 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
Richard Smith053f6c62014-05-16 23:01:30 +00003630 struct CXXRecordDecl::DefinitionData *Data =
John McCall67da35c2010-02-04 22:26:26 +00003631 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00003632 for (auto I : redecls())
Richard Smith64c06302014-05-22 23:19:02 +00003633 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00003634 }
Douglas Gregordee1be82009-01-17 00:42:38 +00003635}
3636
3637void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00003638 assert((!isa<CXXRecordDecl>(this) ||
3639 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3640 "definition completed but not started");
3641
John McCallf937c022011-10-07 06:10:15 +00003642 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003643 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00003644
3645 if (ASTMutationListener *L = getASTMutationListener())
3646 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00003647}
3648
John McCallf937c022011-10-07 06:10:15 +00003649TagDecl *TagDecl::getDefinition() const {
3650 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003651 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003652
3653 // If it's possible for us to have an out-of-date definition, check now.
3654 if (MayHaveOutOfDateDef) {
3655 if (IdentifierInfo *II = getIdentifier()) {
3656 if (II->isOutOfDate()) {
3657 updateOutOfDate(*II);
3658 }
3659 }
3660 }
3661
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003662 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
Andrew Trickba266ee2010-10-19 21:54:32 +00003663 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003664
Aaron Ballman86c93902014-03-06 23:45:36 +00003665 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00003666 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00003667 return R;
Mike Stump11289f42009-09-09 15:08:12 +00003668
Craig Topper36250ad2014-05-12 05:36:57 +00003669 return nullptr;
Ted Kremenek21475702008-09-05 17:16:31 +00003670}
3671
Douglas Gregor14454802011-02-25 02:25:35 +00003672void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3673 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00003674 // Make sure the extended qualifier info is allocated.
3675 if (!hasExtInfo())
David Majnemer00350522015-08-31 18:48:39 +00003676 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00003677 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00003678 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003679 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00003680 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00003681 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00003682 if (getExtInfo()->NumTemplParamLists == 0) {
3683 getASTContext().Deallocate(getExtInfo());
David Majnemer00350522015-08-31 18:48:39 +00003684 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003685 }
3686 else
3687 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00003688 }
3689 }
3690}
3691
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003692void TagDecl::setTemplateParameterListsInfo(
3693 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
3694 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00003695 // Make sure the extended decl info is allocated.
3696 if (!hasExtInfo())
3697 // Allocate external info struct.
David Majnemer00350522015-08-31 18:48:39 +00003698 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003699 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003700 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00003701}
3702
Ted Kremenek21475702008-09-05 17:16:31 +00003703//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003704// EnumDecl Implementation
3705//===----------------------------------------------------------------------===//
3706
David Blaikie68e081d2011-12-20 02:48:34 +00003707void EnumDecl::anchor() { }
3708
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003709EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3710 SourceLocation StartLoc, SourceLocation IdLoc,
3711 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00003712 EnumDecl *PrevDecl, bool IsScoped,
3713 bool IsScopedUsingClassTag, bool IsFixed) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003714 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
3715 IsScoped, IsScopedUsingClassTag, IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003716 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00003717 C.getTypeDeclType(Enum, PrevDecl);
3718 return Enum;
3719}
3720
Douglas Gregor72172e92012-01-05 21:55:30 +00003721EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003722 EnumDecl *Enum =
3723 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3724 nullptr, nullptr, false, false, false);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003725 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3726 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003727}
3728
Alp Tokerb9fa5122014-01-06 11:31:18 +00003729SourceRange EnumDecl::getIntegerTypeRange() const {
3730 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3731 return TI->getTypeLoc().getSourceRange();
3732 return SourceRange();
3733}
3734
Douglas Gregord5058122010-02-11 01:19:42 +00003735void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00003736 QualType NewPromotionType,
3737 unsigned NumPositiveBits,
3738 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00003739 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00003740 if (!IntegerType)
3741 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00003742 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00003743 setNumPositiveBits(NumPositiveBits);
3744 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00003745 TagDecl::completeDefinition();
3746}
3747
Akira Hatanaka3c268af2017-03-21 02:23:00 +00003748bool EnumDecl::isClosed() const {
3749 if (const auto *A = getAttr<EnumExtensibilityAttr>())
3750 return A->getExtensibility() == EnumExtensibilityAttr::Closed;
3751 return true;
3752}
3753
3754bool EnumDecl::isClosedFlag() const {
3755 return isClosed() && hasAttr<FlagEnumAttr>();
3756}
3757
3758bool EnumDecl::isClosedNonFlag() const {
3759 return isClosed() && !hasAttr<FlagEnumAttr>();
3760}
3761
Richard Smith7d137e32012-03-23 03:33:32 +00003762TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3763 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3764 return MSI->getTemplateSpecializationKind();
3765
3766 return TSK_Undeclared;
3767}
3768
3769void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3770 SourceLocation PointOfInstantiation) {
3771 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3772 assert(MSI && "Not an instantiated member enumeration?");
3773 MSI->setTemplateSpecializationKind(TSK);
3774 if (TSK != TSK_ExplicitSpecialization &&
3775 PointOfInstantiation.isValid() &&
3776 MSI->getPointOfInstantiation().isInvalid())
3777 MSI->setPointOfInstantiation(PointOfInstantiation);
3778}
3779
Richard Smith6739a102016-05-05 00:56:12 +00003780EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
3781 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
3782 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
3783 EnumDecl *ED = getInstantiatedFromMemberEnum();
3784 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
3785 ED = NewED;
Richard Smith2195ec92017-04-21 01:15:13 +00003786 return getDefinitionOrSelf(ED);
Richard Smith6739a102016-05-05 00:56:12 +00003787 }
3788 }
3789
3790 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
3791 "couldn't find pattern for enum instantiation");
3792 return nullptr;
3793}
3794
Richard Smith4b38ded2012-03-14 23:13:10 +00003795EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3796 if (SpecializationInfo)
3797 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3798
Craig Topper36250ad2014-05-12 05:36:57 +00003799 return nullptr;
Richard Smith4b38ded2012-03-14 23:13:10 +00003800}
3801
3802void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3803 TemplateSpecializationKind TSK) {
3804 assert(!SpecializationInfo && "Member enum is already a specialization");
3805 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3806}
3807
Sebastian Redl833ef452010-01-26 22:01:41 +00003808//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003809// RecordDecl Implementation
3810//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003811
Richard Smith053f6c62014-05-16 23:01:30 +00003812RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3813 DeclContext *DC, SourceLocation StartLoc,
3814 SourceLocation IdLoc, IdentifierInfo *Id,
3815 RecordDecl *PrevDecl)
3816 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003817 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003818 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003819 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00003820 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003821 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00003822 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003823}
3824
Jay Foad39c79802011-01-12 09:06:06 +00003825RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003826 SourceLocation StartLoc, SourceLocation IdLoc,
3827 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smith053f6c62014-05-16 23:01:30 +00003828 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
3829 StartLoc, IdLoc, Id, PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003830 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3831
Ted Kremenek21475702008-09-05 17:16:31 +00003832 C.getTypeDeclType(R, PrevDecl);
3833 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003834}
3835
Douglas Gregor72172e92012-01-05 21:55:30 +00003836RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003837 RecordDecl *R =
3838 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
3839 SourceLocation(), nullptr, nullptr);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003840 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3841 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003842}
3843
Douglas Gregordfcad112009-03-25 15:59:44 +00003844bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003845 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003846 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3847}
3848
Alexey Bataev39c81e22014-08-28 04:28:19 +00003849bool RecordDecl::isLambda() const {
3850 if (auto RD = dyn_cast<CXXRecordDecl>(this))
3851 return RD->isLambda();
3852 return false;
3853}
3854
Alexey Bataev330de032014-10-29 12:21:55 +00003855bool RecordDecl::isCapturedRecord() const {
3856 return hasAttr<CapturedRecordAttr>();
3857}
3858
3859void RecordDecl::setCapturedRecord() {
3860 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
3861}
3862
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003863RecordDecl::field_iterator RecordDecl::field_begin() const {
3864 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3865 LoadFieldsFromExternalStorage();
3866
3867 return field_iterator(decl_iterator(FirstDecl));
3868}
3869
Douglas Gregorb11aad82011-02-19 18:51:44 +00003870/// completeDefinition - Notes that the definition of this type is now
3871/// complete.
3872void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003873 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003874 TagDecl::completeDefinition();
3875}
3876
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003877/// isMsStruct - Get whether or not this record uses ms_struct layout.
3878/// This which can be turned on with an attribute, pragma, or the
3879/// -mms-bitfields command-line option.
3880bool RecordDecl::isMsStruct(const ASTContext &C) const {
David Majnemer8ab003a2015-02-02 19:30:52 +00003881 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003882}
3883
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003884void RecordDecl::LoadFieldsFromExternalStorage() const {
3885 ExternalASTSource *Source = getASTContext().getExternalSource();
3886 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3887
3888 // Notify that we have a RecordDecl doing some initialization.
3889 ExternalASTSource::Deserializing TheFields(Source);
3890
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003891 SmallVector<Decl*, 64> Decls;
Richard Smith3cb15722015-08-05 22:41:45 +00003892 LoadedFieldsFromExternalStorage = true;
3893 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
3894 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3895 }, Decls);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003896
3897#ifndef NDEBUG
3898 // Check that all decls we got were FieldDecls.
3899 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003900 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003901#endif
3902
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003903 if (Decls.empty())
3904 return;
3905
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003906 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003907 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003908}
3909
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003910bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
3911 ASTContext &Context = getASTContext();
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00003912 if (!Context.getLangOpts().Sanitize.hasOneOf(
3913 SanitizerKind::Address | SanitizerKind::KernelAddress) ||
Alexey Samsonova0416102014-11-11 01:26:14 +00003914 !Context.getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003915 return false;
Alexey Samsonov33e00e22014-10-16 23:50:26 +00003916 const auto &Blacklist = Context.getSanitizerBlacklist();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003917 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003918 // We may be able to relax some of these requirements.
3919 int ReasonToReject = -1;
3920 if (!CXXRD || CXXRD->isExternCContext())
3921 ReasonToReject = 0; // is not C++.
3922 else if (CXXRD->hasAttr<PackedAttr>())
3923 ReasonToReject = 1; // is packed.
3924 else if (CXXRD->isUnion())
3925 ReasonToReject = 2; // is a union.
3926 else if (CXXRD->isTriviallyCopyable())
3927 ReasonToReject = 3; // is trivially copyable.
3928 else if (CXXRD->hasTrivialDestructor())
3929 ReasonToReject = 4; // has trivial destructor.
3930 else if (CXXRD->isStandardLayout())
3931 ReasonToReject = 5; // is standard layout.
Alexey Samsonov33e00e22014-10-16 23:50:26 +00003932 else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003933 ReasonToReject = 6; // is in a blacklisted file.
3934 else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(),
3935 "field-padding"))
3936 ReasonToReject = 7; // is blacklisted.
3937
3938 if (EmitRemark) {
3939 if (ReasonToReject >= 0)
3940 Context.getDiagnostics().Report(
3941 getLocation(),
3942 diag::remark_sanitize_address_insert_extra_padding_rejected)
3943 << getQualifiedNameAsString() << ReasonToReject;
3944 else
3945 Context.getDiagnostics().Report(
3946 getLocation(),
3947 diag::remark_sanitize_address_insert_extra_padding_accepted)
3948 << getQualifiedNameAsString();
3949 }
3950 return ReasonToReject < 0;
3951}
3952
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003953const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
3954 for (const auto *I : fields()) {
3955 if (I->getIdentifier())
3956 return I;
3957
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003958 if (const auto *RT = I->getType()->getAs<RecordType>())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003959 if (const FieldDecl *NamedDataMember =
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003960 RT->getDecl()->findFirstNamedDataMember())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003961 return NamedDataMember;
3962 }
3963
3964 // We didn't find a named data member.
3965 return nullptr;
3966}
3967
3968
Steve Naroff415d3d52008-10-08 17:01:13 +00003969//===----------------------------------------------------------------------===//
3970// BlockDecl Implementation
3971//===----------------------------------------------------------------------===//
3972
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003973void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00003974 assert(!ParamInfo && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00003975
Steve Naroffc4b30e52009-03-13 16:56:44 +00003976 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003977 if (!NewParamInfo.empty()) {
3978 NumParams = NewParamInfo.size();
3979 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3980 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003981 }
3982}
3983
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00003984void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
3985 bool CapturesCXXThis) {
3986 this->CapturesCXXThis = CapturesCXXThis;
3987 this->NumCaptures = Captures.size();
John McCallc63de662011-02-02 13:00:07 +00003988
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00003989 if (Captures.empty()) {
3990 this->Captures = nullptr;
John McCallc63de662011-02-02 13:00:07 +00003991 return;
3992 }
3993
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00003994 this->Captures = Captures.copy(Context).data();
Steve Naroffc4b30e52009-03-13 16:56:44 +00003995}
Sebastian Redl833ef452010-01-26 22:01:41 +00003996
John McCallce45f882011-06-15 22:51:16 +00003997bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00003998 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00003999 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00004000 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00004001 return true;
4002
4003 return false;
4004}
4005
Douglas Gregor70226da2010-12-21 16:27:07 +00004006SourceRange BlockDecl::getSourceRange() const {
4007 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
4008}
Sebastian Redl833ef452010-01-26 22:01:41 +00004009
4010//===----------------------------------------------------------------------===//
4011// Other Decl Allocation/Deallocation Method Implementations
4012//===----------------------------------------------------------------------===//
4013
David Blaikie68e081d2011-12-20 02:48:34 +00004014void TranslationUnitDecl::anchor() { }
4015
Sebastian Redl833ef452010-01-26 22:01:41 +00004016TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Craig Topper36250ad2014-05-12 05:36:57 +00004017 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00004018}
4019
Nico Weber66220292016-03-02 17:28:48 +00004020void PragmaCommentDecl::anchor() { }
4021
4022PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4023 TranslationUnitDecl *DC,
4024 SourceLocation CommentLoc,
4025 PragmaMSCommentKind CommentKind,
4026 StringRef Arg) {
4027 PragmaCommentDecl *PCD =
4028 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4029 PragmaCommentDecl(DC, CommentLoc, CommentKind);
4030 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4031 PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4032 return PCD;
4033}
4034
4035PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4036 unsigned ID,
4037 unsigned ArgSize) {
4038 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
4039 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
4040}
4041
Nico Webercbbaeb12016-03-02 19:28:54 +00004042void PragmaDetectMismatchDecl::anchor() { }
4043
4044PragmaDetectMismatchDecl *
4045PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4046 SourceLocation Loc, StringRef Name,
4047 StringRef Value) {
4048 size_t ValueStart = Name.size() + 1;
4049 PragmaDetectMismatchDecl *PDMD =
4050 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4051 PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4052 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4053 PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4054 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4055 Value.size());
4056 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4057 return PDMD;
4058}
4059
4060PragmaDetectMismatchDecl *
4061PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4062 unsigned NameValueSize) {
4063 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4064 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4065}
Nico Weber66220292016-03-02 17:28:48 +00004066
Richard Smithf19e1272015-03-07 00:04:49 +00004067void ExternCContextDecl::anchor() { }
4068
4069ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4070 TranslationUnitDecl *DC) {
4071 return new (C, DC) ExternCContextDecl(DC);
4072}
4073
David Blaikie68e081d2011-12-20 02:48:34 +00004074void LabelDecl::anchor() { }
4075
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004076LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004077 SourceLocation IdentL, IdentifierInfo *II) {
Craig Topper36250ad2014-05-12 05:36:57 +00004078 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004079}
4080
4081LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4082 SourceLocation IdentL, IdentifierInfo *II,
4083 SourceLocation GnuLabelL) {
4084 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Craig Topper36250ad2014-05-12 05:36:57 +00004085 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004086}
4087
Douglas Gregor72172e92012-01-05 21:55:30 +00004088LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004089 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
4090 SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00004091}
4092
Ehsan Akhgari31097582014-09-22 02:21:54 +00004093void LabelDecl::setMSAsmLabel(StringRef Name) {
4094 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
4095 memcpy(Buffer, Name.data(), Name.size());
4096 Buffer[Name.size()] = '\0';
4097 MSAsmName = Buffer;
4098}
4099
David Blaikie68e081d2011-12-20 02:48:34 +00004100void ValueDecl::anchor() { }
4101
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004102bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00004103 for (const auto *I : attrs())
4104 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004105 return true;
4106
4107 return isWeakImported();
4108}
4109
David Blaikie68e081d2011-12-20 02:48:34 +00004110void ImplicitParamDecl::anchor() { }
4111
Sebastian Redl833ef452010-01-26 22:01:41 +00004112ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004113 SourceLocation IdLoc,
Alexey Bataev56223232017-06-09 13:40:18 +00004114 IdentifierInfo *Id, QualType Type,
4115 ImplicitParamKind ParamKind) {
4116 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
4117}
4118
4119ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
4120 ImplicitParamKind ParamKind) {
4121 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
Sebastian Redl833ef452010-01-26 22:01:41 +00004122}
4123
Richard Smithf7981722013-11-22 09:01:48 +00004124ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004125 unsigned ID) {
Alexey Bataev56223232017-06-09 13:40:18 +00004126 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
Douglas Gregor72172e92012-01-05 21:55:30 +00004127}
4128
Sebastian Redl833ef452010-01-26 22:01:41 +00004129FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004130 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004131 const DeclarationNameInfo &NameInfo,
4132 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004133 StorageClass SC,
Richard Smithf7981722013-11-22 09:01:48 +00004134 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00004135 bool hasWrittenPrototype,
4136 bool isConstexprSpecified) {
Richard Smithf7981722013-11-22 09:01:48 +00004137 FunctionDecl *New =
Richard Smith053f6c62014-05-16 23:01:30 +00004138 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
4139 SC, isInlineSpecified, isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00004140 New->HasWrittenPrototype = hasWrittenPrototype;
4141 return New;
4142}
4143
Douglas Gregor72172e92012-01-05 21:55:30 +00004144FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004145 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004146 DeclarationNameInfo(), QualType(), nullptr,
Richard Smithf7981722013-11-22 09:01:48 +00004147 SC_None, false, false);
Douglas Gregor72172e92012-01-05 21:55:30 +00004148}
4149
Sebastian Redl833ef452010-01-26 22:01:41 +00004150BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004151 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00004152}
4153
Douglas Gregor72172e92012-01-05 21:55:30 +00004154BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004155 return new (C, ID) BlockDecl(nullptr, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00004156}
4157
Chandler Carruth21c90602015-12-30 03:24:14 +00004158CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
4159 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4160 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
4161
Ben Langmuir37943a72013-05-03 19:00:33 +00004162CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
4163 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004164 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Richard Smithf7981722013-11-22 09:01:48 +00004165 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004166}
4167
Ben Langmuirce914fc2013-05-03 19:20:19 +00004168CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00004169 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004170 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Craig Topper36250ad2014-05-12 05:36:57 +00004171 CapturedDecl(nullptr, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00004172}
4173
Chandler Carruth21c90602015-12-30 03:24:14 +00004174Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4175void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4176
4177bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4178void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4179
Sebastian Redl833ef452010-01-26 22:01:41 +00004180EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4181 SourceLocation L,
4182 IdentifierInfo *Id, QualType T,
4183 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00004184 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00004185}
4186
Douglas Gregor72172e92012-01-05 21:55:30 +00004187EnumConstantDecl *
4188EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004189 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4190 QualType(), nullptr, llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00004191}
4192
David Blaikie68e081d2011-12-20 02:48:34 +00004193void IndirectFieldDecl::anchor() { }
4194
Richard Smith9f951822016-01-06 22:49:11 +00004195IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4196 SourceLocation L, DeclarationName N,
David Majnemer59f77922016-06-24 04:05:48 +00004197 QualType T,
4198 MutableArrayRef<NamedDecl *> CH)
4199 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4200 ChainingSize(CH.size()) {
Richard Smith9f951822016-01-06 22:49:11 +00004201 // In C++, indirect field declarations conflict with tag declarations in the
4202 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4203 if (C.getLangOpts().CPlusPlus)
4204 IdentifierNamespace |= IDNS_Tag;
4205}
4206
Benjamin Kramer39593702010-11-21 14:11:41 +00004207IndirectFieldDecl *
4208IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
David Majnemer59f77922016-06-24 04:05:48 +00004209 IdentifierInfo *Id, QualType T,
4210 llvm::MutableArrayRef<NamedDecl *> CH) {
4211 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
Francois Pichet783dd6e2010-11-21 06:08:52 +00004212}
4213
Douglas Gregor72172e92012-01-05 21:55:30 +00004214IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4215 unsigned ID) {
Richard Smith9f951822016-01-06 22:49:11 +00004216 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
David Majnemer59f77922016-06-24 04:05:48 +00004217 DeclarationName(), QualType(), None);
Douglas Gregor72172e92012-01-05 21:55:30 +00004218}
4219
Douglas Gregorbe996932010-09-01 20:41:53 +00004220SourceRange EnumConstantDecl::getSourceRange() const {
4221 SourceLocation End = getLocation();
4222 if (Init)
4223 End = Init->getLocEnd();
4224 return SourceRange(getLocation(), End);
4225}
4226
David Blaikie68e081d2011-12-20 02:48:34 +00004227void TypeDecl::anchor() { }
4228
Sebastian Redl833ef452010-01-26 22:01:41 +00004229TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00004230 SourceLocation StartLoc, SourceLocation IdLoc,
4231 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004232 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00004233}
4234
David Blaikie68e081d2011-12-20 02:48:34 +00004235void TypedefNameDecl::anchor() { }
4236
Richard Smith42413142015-05-15 20:05:43 +00004237TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4238 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4239 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4240 auto *ThisTypedef = this;
4241 if (AnyRedecl && OwningTypedef) {
4242 OwningTypedef = OwningTypedef->getCanonicalDecl();
4243 ThisTypedef = ThisTypedef->getCanonicalDecl();
4244 }
4245 if (OwningTypedef == ThisTypedef)
Richard Smitha5230222015-03-27 01:37:43 +00004246 return TT->getDecl();
Richard Smith42413142015-05-15 20:05:43 +00004247 }
Richard Smitha5230222015-03-27 01:37:43 +00004248
4249 return nullptr;
4250}
4251
Argyrios Kyrtzidis3b25c912017-03-21 16:56:02 +00004252bool TypedefNameDecl::isTransparentTagSlow() const {
4253 auto determineIsTransparent = [&]() {
4254 if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
4255 if (auto *TD = TT->getDecl()) {
4256 if (TD->getName() != getName())
4257 return false;
4258 SourceLocation TTLoc = getLocation();
4259 SourceLocation TDLoc = TD->getLocation();
4260 if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
4261 return false;
4262 SourceManager &SM = getASTContext().getSourceManager();
4263 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
4264 }
4265 }
4266 return false;
4267 };
4268
4269 bool isTransparent = determineIsTransparent();
4270 CacheIsTransparentTag = 1;
4271 if (isTransparent)
4272 CacheIsTransparentTag |= 0x2;
4273 return isTransparent;
4274}
4275
Douglas Gregor72172e92012-01-05 21:55:30 +00004276TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004277 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004278 nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004279}
4280
Richard Smithdda56e42011-04-15 14:24:37 +00004281TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4282 SourceLocation StartLoc,
4283 SourceLocation IdLoc, IdentifierInfo *Id,
4284 TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004285 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00004286}
4287
Douglas Gregor72172e92012-01-05 21:55:30 +00004288TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004289 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
4290 SourceLocation(), nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004291}
4292
Abramo Bagnaraea947882011-03-08 16:41:52 +00004293SourceRange TypedefDecl::getSourceRange() const {
4294 SourceLocation RangeEnd = getLocation();
4295 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4296 if (typeIsPostfix(TInfo->getType()))
4297 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4298 }
4299 return SourceRange(getLocStart(), RangeEnd);
4300}
4301
Richard Smithdda56e42011-04-15 14:24:37 +00004302SourceRange TypeAliasDecl::getSourceRange() const {
4303 SourceLocation RangeEnd = getLocStart();
4304 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4305 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4306 return SourceRange(getLocStart(), RangeEnd);
4307}
4308
David Blaikie68e081d2011-12-20 02:48:34 +00004309void FileScopeAsmDecl::anchor() { }
4310
Sebastian Redl833ef452010-01-26 22:01:41 +00004311FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00004312 StringLiteral *Str,
4313 SourceLocation AsmLoc,
4314 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00004315 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00004316}
Douglas Gregorba345522011-12-02 23:23:56 +00004317
Richard Smithf7981722013-11-22 09:01:48 +00004318FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004319 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004320 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4321 SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00004322}
4323
Michael Han84324352013-02-22 17:15:32 +00004324void EmptyDecl::anchor() {}
4325
4326EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004327 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00004328}
4329
4330EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004331 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00004332}
4333
Douglas Gregorba345522011-12-02 23:23:56 +00004334//===----------------------------------------------------------------------===//
4335// ImportDecl Implementation
4336//===----------------------------------------------------------------------===//
4337
4338/// \brief Retrieve the number of module identifiers needed to name the given
4339/// module.
4340static unsigned getNumModuleIdentifiers(Module *Mod) {
4341 unsigned Result = 1;
4342 while (Mod->Parent) {
4343 Mod = Mod->Parent;
4344 ++Result;
4345 }
4346 return Result;
4347}
4348
Douglas Gregor22d09742012-01-03 18:04:46 +00004349ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004350 Module *Imported,
4351 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00004352 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00004353 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00004354{
4355 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004356 auto *StoredLocs = getTrailingObjects<SourceLocation>();
James Y Knight7a22b242015-08-06 20:26:32 +00004357 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4358 StoredLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004359}
4360
Douglas Gregor22d09742012-01-03 18:04:46 +00004361ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004362 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00004363 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00004364 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00004365{
James Y Knight7a22b242015-08-06 20:26:32 +00004366 *getTrailingObjects<SourceLocation>() = EndLoc;
Douglas Gregorba345522011-12-02 23:23:56 +00004367}
4368
Richard Smithf7981722013-11-22 09:01:48 +00004369ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004370 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004371 ArrayRef<SourceLocation> IdentifierLocs) {
James Y Knight7a22b242015-08-06 20:26:32 +00004372 return new (C, DC,
4373 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
Richard Smithf7981722013-11-22 09:01:48 +00004374 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004375}
4376
Richard Smithf7981722013-11-22 09:01:48 +00004377ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004378 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00004379 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004380 SourceLocation EndLoc) {
James Y Knight7a22b242015-08-06 20:26:32 +00004381 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
4382 ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00004383 Import->setImplicit();
4384 return Import;
4385}
4386
Douglas Gregor72172e92012-01-05 21:55:30 +00004387ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4388 unsigned NumLocations) {
James Y Knight7a22b242015-08-06 20:26:32 +00004389 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
Richard Smithf7981722013-11-22 09:01:48 +00004390 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00004391}
4392
4393ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4394 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004395 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00004396
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004397 const auto *StoredLocs = getTrailingObjects<SourceLocation>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00004398 return llvm::makeArrayRef(StoredLocs,
4399 getNumModuleIdentifiers(getImportedModule()));
Douglas Gregorba345522011-12-02 23:23:56 +00004400}
4401
4402SourceRange ImportDecl::getSourceRange() const {
4403 if (!ImportedAndComplete.getInt())
James Y Knight7a22b242015-08-06 20:26:32 +00004404 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
4405
Douglas Gregorba345522011-12-02 23:23:56 +00004406 return SourceRange(getLocation(), getIdentifierLocs().back());
4407}
Richard Smith8df390f2016-09-08 23:14:54 +00004408
4409//===----------------------------------------------------------------------===//
4410// ExportDecl Implementation
4411//===----------------------------------------------------------------------===//
4412
4413void ExportDecl::anchor() {}
4414
4415ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
4416 SourceLocation ExportLoc) {
4417 return new (C, DC) ExportDecl(DC, ExportLoc);
4418}
4419
4420ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4421 return new (C, ID) ExportDecl(nullptr, SourceLocation());
4422}