blob: 8d98e1fc02e41b6461fcf0142e7eaef2e8bb706e [file] [log] [blame]
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001//===- Decl.cpp - Declaration AST Node Implementation ---------------------===//
Chris Lattnera11999d2006-10-15 22:34:45 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnera11999d2006-10-15 22:34:45 +00006//
7//===----------------------------------------------------------------------===//
8//
Argyrios Kyrtzidis63018842008-06-04 13:04:04 +00009// This file implements the Decl subclasses.
Chris Lattnera11999d2006-10-15 22:34:45 +000010//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/Decl.h"
George Burgess IV99db3ea2017-08-09 04:02:49 +000014#include "Linkage.h"
Chris Lattnera7b32872008-03-15 06:12:44 +000015#include "clang/AST/ASTContext.h"
Richard Trieu0f25c742018-12-14 03:35:10 +000016#include "clang/AST/ASTDiagnostic.h"
Faisal Valib90b2112014-04-03 16:32:21 +000017#include "clang/AST/ASTLambda.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000018#include "clang/AST/ASTMutationListener.h"
Reid Kleckner60573ae2019-11-15 17:31:55 -080019#include "clang/AST/Attr.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000020#include "clang/AST/CanonicalType.h"
21#include "clang/AST/DeclBase.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000024#include "clang/AST/DeclOpenMP.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/AST/DeclTemplate.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000026#include "clang/AST/DeclarationName.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000027#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000028#include "clang/AST/ExprCXX.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000029#include "clang/AST/ExternalASTSource.h"
Richard Trieue6caa262017-12-23 00:41:01 +000030#include "clang/AST/ODRHash.h"
Jordan Rose1e879d82018-03-23 00:07:18 +000031#include "clang/AST/PrettyDeclStackTrace.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000032#include "clang/AST/PrettyPrinter.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000033#include "clang/AST/Redeclarable.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000034#include "clang/AST/Stmt.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000035#include "clang/AST/TemplateBase.h"
36#include "clang/AST/Type.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000037#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000038#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000039#include "clang/Basic/IdentifierTable.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000040#include "clang/Basic/LLVM.h"
41#include "clang/Basic/LangOptions.h"
42#include "clang/Basic/Linkage.h"
Douglas Gregorba345522011-12-02 23:23:56 +000043#include "clang/Basic/Module.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000044#include "clang/Basic/PartialDiagnostic.h"
45#include "clang/Basic/SanitizerBlacklist.h"
46#include "clang/Basic/Sanitizers.h"
47#include "clang/Basic/SourceLocation.h"
48#include "clang/Basic/SourceManager.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000049#include "clang/Basic/Specifiers.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000050#include "clang/Basic/TargetCXXABI.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000051#include "clang/Basic/TargetInfo.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000052#include "clang/Basic/Visibility.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000053#include "llvm/ADT/APSInt.h"
54#include "llvm/ADT/ArrayRef.h"
55#include "llvm/ADT/None.h"
56#include "llvm/ADT/Optional.h"
57#include "llvm/ADT/STLExtras.h"
58#include "llvm/ADT/SmallVector.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000059#include "llvm/ADT/StringRef.h"
Reid Kleckner60573ae2019-11-15 17:31:55 -080060#include "llvm/ADT/StringSwitch.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000061#include "llvm/ADT/Triple.h"
62#include "llvm/Support/Casting.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000063#include "llvm/Support/ErrorHandling.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000064#include "llvm/Support/raw_ostream.h"
David Blaikie9c70e042011-09-21 18:16:56 +000065#include <algorithm>
Eugene Zelenkode0215c2017-11-13 23:01:27 +000066#include <cassert>
67#include <cstddef>
68#include <cstring>
69#include <memory>
70#include <string>
71#include <tuple>
72#include <type_traits>
David Blaikie9c70e042011-09-21 18:16:56 +000073
Chris Lattner6d9a6852006-10-25 05:11:20 +000074using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000075
Richard Smith0b87e072013-10-07 08:02:11 +000076Decl *clang::getPrimaryMergedDecl(Decl *D) {
77 return D->getASTContext().getPrimaryMergedDecl(D);
78}
79
Jordan Rose1e879d82018-03-23 00:07:18 +000080void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
81 SourceLocation Loc = this->Loc;
82 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
83 if (Loc.isValid()) {
84 Loc.print(OS, Context.getSourceManager());
85 OS << ": ";
86 }
87 OS << Message;
88
89 if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
90 OS << " '";
91 ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
92 OS << "'";
93 }
94
95 OS << '\n';
96}
97
Richard Smith73b21d82014-09-03 02:33:22 +000098// Defined here so that it can be inlined into its direct callers.
99bool Decl::isOutOfLine() const {
100 return !getLexicalDeclContext()->Equals(getDeclContext());
101}
102
Richard Smith42413142015-05-15 20:05:43 +0000103TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
104 : Decl(TranslationUnit, nullptr, SourceLocation()),
Eugene Zelenkode0215c2017-11-13 23:01:27 +0000105 DeclContext(TranslationUnit), Ctx(ctx) {}
Richard Smith42413142015-05-15 20:05:43 +0000106
Chris Lattner88f70d62008-03-15 05:43:15 +0000107//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000108// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000109//===----------------------------------------------------------------------===//
110
John McCalldf25c432013-02-16 00:17:33 +0000111// Visibility rules aren't rigorously externally specified, but here
112// are the basic principles behind what we implement:
113//
114// 1. An explicit visibility attribute is generally a direct expression
115// of the user's intent and should be honored. Only the innermost
116// visibility attribute applies. If no visibility attribute applies,
117// global visibility settings are considered.
118//
119// 2. There is one caveat to the above: on or in a template pattern,
120// an explicit visibility attribute is just a default rule, and
121// visibility can be decreased by the visibility of template
122// arguments. But this, too, has an exception: an attribute on an
123// explicit specialization or instantiation causes all the visibility
124// restrictions of the template arguments to be ignored.
125//
126// 3. A variable that does not otherwise have explicit visibility can
127// be restricted by the visibility of its type.
128//
129// 4. A visibility restriction is explicit if it comes from an
130// attribute (or something like it), not a global visibility setting.
131// When emitting a reference to an external symbol, visibility
132// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +0000133//
134// 5. When computing the visibility of a non-type, including a
135// non-type member of a class, only non-type visibility restrictions
136// are considered: the 'visibility' attribute, global value-visibility
137// settings, and a few special cases like __private_extern.
138//
139// 6. When computing the visibility of a type, including a type member
140// of a class, only type visibility restrictions are considered:
141// the 'type_visibility' attribute and global type-visibility settings.
142// However, a 'visibility' attribute counts as a 'type_visibility'
143// attribute on any declaration that only has the former.
144//
145// The visibility of a "secondary" entity, like a template argument,
146// is computed using the kind of that entity, not the kind of the
147// primary entity for which we are computing visibility. For example,
148// the visibility of a specialization of either of these templates:
149// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
150// template <class T, bool (&compare)(T, X)> class matcher;
151// is restricted according to the type visibility of the argument 'T',
152// the type visibility of 'bool(&)(T,X)', and the value visibility of
153// the argument function 'compare'. That 'has_match' is a value
154// and 'matcher' is a type only matters when looking for attributes
155// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +0000156
John McCalld041a9b2013-02-20 01:54:26 +0000157/// Does this computation kind permit us to consider additional
158/// visibility settings from attributes and the like?
159static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000160 return computation.IgnoreExplicitVisibility;
John McCalld041a9b2013-02-20 01:54:26 +0000161}
162
163/// Given an LVComputationKind, return one of the same type/value sort
164/// that records that it already has explicit visibility.
165static LVComputationKind
Richard Smithfbe7b462017-09-22 02:22:32 +0000166withExplicitVisibilityAlready(LVComputationKind Kind) {
167 Kind.IgnoreExplicitVisibility = true;
168 return Kind;
John McCalld041a9b2013-02-20 01:54:26 +0000169}
170
David Blaikie05785d12013-02-20 22:23:23 +0000171static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
172 LVComputationKind kind) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000173 assert(!kind.IgnoreExplicitVisibility &&
John McCalld041a9b2013-02-20 01:54:26 +0000174 "asking for explicit visibility when we shouldn't be");
Richard Smithfbe7b462017-09-22 02:22:32 +0000175 return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
John McCalld041a9b2013-02-20 01:54:26 +0000176}
177
John McCalldf25c432013-02-16 00:17:33 +0000178/// Is the given declaration a "type" or a "value" for the purposes of
179/// visibility computation?
180static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000181 return isa<TypeDecl>(D) ||
182 isa<ClassTemplateDecl>(D) ||
183 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000184}
185
John McCall5f46c482013-02-21 23:42:58 +0000186/// Does the given declaration have member specialization information,
187/// and if so, is it an explicit specialization?
188template <class T> static typename
Benjamin Kramered2f4762014-03-07 14:30:23 +0000189std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-02-21 23:42:58 +0000190isExplicitMemberSpecialization(const T *D) {
191 if (const MemberSpecializationInfo *member =
192 D->getMemberSpecializationInfo()) {
193 return member->isExplicitSpecialization();
194 }
195 return false;
196}
197
198/// For templates, this question is easier: a member template can't be
199/// explicitly instantiated, so there's a single bit indicating whether
200/// or not this is an explicit member specialization.
201static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
202 return D->isMemberSpecialization();
203}
204
John McCalld041a9b2013-02-20 01:54:26 +0000205/// Given a visibility attribute, return the explicit visibility
206/// associated with it.
207template <class T>
208static Visibility getVisibilityFromAttr(const T *attr) {
209 switch (attr->getVisibility()) {
210 case T::Default:
211 return DefaultVisibility;
212 case T::Hidden:
213 return HiddenVisibility;
214 case T::Protected:
215 return ProtectedVisibility;
216 }
217 llvm_unreachable("bad visibility kind");
218}
219
John McCalldf25c432013-02-16 00:17:33 +0000220/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000221static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000222 NamedDecl::ExplicitVisibilityKind kind) {
223 // If we're ultimately computing the visibility of a type, look for
224 // a 'type_visibility' attribute before looking for 'visibility'.
225 if (kind == NamedDecl::VisibilityForType) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000226 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000227 return getVisibilityFromAttr(A);
228 }
229 }
230
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000231 // If this declaration has an explicit visibility attribute, use it.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000232 if (const auto *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000233 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000234 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000235
David Blaikie7a30dc52013-02-21 01:47:18 +0000236 return None;
John McCall457a04e2010-10-22 21:05:15 +0000237}
238
George Burgess IV99db3ea2017-08-09 04:02:49 +0000239LinkageInfo LinkageComputer::getLVForType(const Type &T,
240 LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000241 if (computation.IgnoreAllVisibility)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000242 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
George Burgess IV35cb4f82017-08-09 04:12:17 +0000243 return getTypeLinkageAndVisibility(&T);
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000244}
245
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000246/// Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000247/// template parameter list. For visibility purposes, template
248/// parameters are part of the signature of a template.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000249LinkageInfo LinkageComputer::getLVForTemplateParameterList(
250 const TemplateParameterList *Params, LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000251 LinkageInfo LV;
David Majnemerc7b85c42014-04-23 05:16:48 +0000252 for (const NamedDecl *P : *Params) {
John McCalldf25c432013-02-16 00:17:33 +0000253 // Template type parameters are the most common and never
254 // contribute to visibility, pack or not.
David Majnemerc7b85c42014-04-23 05:16:48 +0000255 if (isa<TemplateTypeParmDecl>(P))
John McCalldf25c432013-02-16 00:17:33 +0000256 continue;
257
258 // Non-type template parameters can be restricted by the value type, e.g.
259 // template <enum X> class A { ... };
260 // We have to be careful here, though, because we can be dealing with
261 // dependent types.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000262 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
John McCalldf25c432013-02-16 00:17:33 +0000263 // Handle the non-pack case first.
264 if (!NTTP->isExpandedParameterPack()) {
265 if (!NTTP->getType()->isDependentType()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000266 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000267 }
268 continue;
269 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000270
John McCalldf25c432013-02-16 00:17:33 +0000271 // Look at all the types in an expanded pack.
272 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
273 QualType type = NTTP->getExpansionType(i);
274 if (!type->isDependentType())
George Burgess IV35cb4f82017-08-09 04:12:17 +0000275 LV.merge(getTypeLinkageAndVisibility(type));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000276 }
John McCalldf25c432013-02-16 00:17:33 +0000277 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000278 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000279
John McCalldf25c432013-02-16 00:17:33 +0000280 // Template template parameters can be restricted by their
281 // template parameters, recursively.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000282 const auto *TTP = cast<TemplateTemplateParmDecl>(P);
John McCalldf25c432013-02-16 00:17:33 +0000283
284 // Handle the non-pack case first.
285 if (!TTP->isExpandedParameterPack()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000286 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
287 computation));
John McCalldf25c432013-02-16 00:17:33 +0000288 continue;
289 }
290
291 // Look at all expansions in an expanded pack.
292 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
293 i != n; ++i) {
294 LV.merge(getLVForTemplateParameterList(
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000295 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000296 }
297 }
298
John McCall457a04e2010-10-22 21:05:15 +0000299 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000300}
301
Eli Friedman7e346a82013-07-01 20:22:57 +0000302static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
Craig Topper36250ad2014-05-12 05:36:57 +0000303 const Decl *Ret = nullptr;
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000304 const DeclContext *DC = D->getDeclContext();
305 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman7e346a82013-07-01 20:22:57 +0000306 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
307 Ret = cast<Decl>(DC);
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000308 DC = DC->getParent();
309 }
310 return Ret;
311}
312
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000313/// Get the most restrictive linkage for the types and
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000314/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000315///
316/// Note that we don't take an LVComputationKind because we always
317/// want to honor the visibility of template arguments in the same way.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000318LinkageInfo
319LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
320 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000321 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000322
David Majnemerc7b85c42014-04-23 05:16:48 +0000323 for (const TemplateArgument &Arg : Args) {
324 switch (Arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000325 case TemplateArgument::Null:
326 case TemplateArgument::Integral:
327 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000328 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000329
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000330 case TemplateArgument::Type:
David Majnemerc7b85c42014-04-23 05:16:48 +0000331 LV.merge(getLVForType(*Arg.getAsType(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000332 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000333
George Burgess IV00f70bd2018-03-01 05:43:23 +0000334 case TemplateArgument::Declaration: {
335 const NamedDecl *ND = Arg.getAsDecl();
336 assert(!usesTypeVisibility(ND));
337 LV.merge(getLVForDecl(ND, computation));
John McCalldf25c432013-02-16 00:17:33 +0000338 continue;
George Burgess IV00f70bd2018-03-01 05:43:23 +0000339 }
Eli Friedmanb826a002012-09-26 02:36:12 +0000340
341 case TemplateArgument::NullPtr:
George Burgess IV35cb4f82017-08-09 04:12:17 +0000342 LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
John McCalldf25c432013-02-16 00:17:33 +0000343 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000344
345 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000346 case TemplateArgument::TemplateExpansion:
David Majnemerc7b85c42014-04-23 05:16:48 +0000347 if (TemplateDecl *Template =
348 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000349 LV.merge(getLVForDecl(Template, computation));
John McCalldf25c432013-02-16 00:17:33 +0000350 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000351
352 case TemplateArgument::Pack:
David Majnemerc7b85c42014-04-23 05:16:48 +0000353 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000354 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000355 }
John McCalldf25c432013-02-16 00:17:33 +0000356 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000357 }
358
John McCall457a04e2010-10-22 21:05:15 +0000359 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000360}
361
George Burgess IV99db3ea2017-08-09 04:02:49 +0000362LinkageInfo
363LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
364 LVComputationKind computation) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000365 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall8823c652010-08-13 08:35:10 +0000366}
367
John McCall5f46c482013-02-21 23:42:58 +0000368static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
369 const FunctionTemplateSpecializationInfo *specInfo) {
370 // Include visibility from the template parameters and arguments
371 // only if this is not an explicit instantiation or specialization
372 // with direct explicit visibility. (Implicit instantiations won't
373 // have a direct attribute.)
374 if (!specInfo->isExplicitInstantiationOrSpecialization())
375 return true;
376
377 return !fn->hasAttr<VisibilityAttr>();
378}
379
John McCalldf25c432013-02-16 00:17:33 +0000380/// Merge in template-related linkage and visibility for the given
381/// function template specialization.
382///
383/// We don't need a computation kind here because we can assume
384/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000385///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000386/// \param[out] LV the computation to use for the parent
George Burgess IV99db3ea2017-08-09 04:02:49 +0000387void LinkageComputer::mergeTemplateLV(
388 LinkageInfo &LV, const FunctionDecl *fn,
389 const FunctionTemplateSpecializationInfo *specInfo,
390 LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000391 bool considerVisibility =
392 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000393
394 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000395 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000396 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000397 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000398 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
399
400 // Merge information from the template arguments.
401 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000402 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCalldf25c432013-02-16 00:17:33 +0000403 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000404}
405
John McCall5f46c482013-02-21 23:42:58 +0000406/// Does the given declaration have a direct visibility attribute
407/// that would match the given rules?
408static bool hasDirectVisibilityAttribute(const NamedDecl *D,
409 LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000410 if (computation.IgnoreAllVisibility)
John McCall5f46c482013-02-21 23:42:58 +0000411 return false;
Richard Smithfbe7b462017-09-22 02:22:32 +0000412
413 return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
414 D->hasAttr<VisibilityAttr>();
John McCall5f46c482013-02-21 23:42:58 +0000415}
416
John McCalld041a9b2013-02-20 01:54:26 +0000417/// Should we consider visibility associated with the template
418/// arguments and parameters of the given class template specialization?
419static bool shouldConsiderTemplateVisibility(
420 const ClassTemplateSpecializationDecl *spec,
421 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000422 // Include visibility from the template parameters and arguments
423 // only if this is not an explicit instantiation or specialization
424 // with direct explicit visibility (and note that implicit
425 // instantiations won't have a direct attribute).
426 //
427 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000428 // for an explicit specialization when computing the visibility of a
429 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000430 //
431 // This is a bit complex; let's unpack it.
432 //
433 // An explicit class specialization is an independent, top-level
434 // declaration. As such, if it or any of its members has an
435 // explicit visibility attribute, that must directly express the
436 // user's intent, and we should honor it. The same logic applies to
437 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000438
439 // Fast path: if this is not an explicit instantiation or
440 // specialization, we always want to consider template-related
441 // visibility restrictions.
442 if (!spec->isExplicitInstantiationOrSpecialization())
443 return true;
444
445 // This is the 'member thereof' check.
446 if (spec->isExplicitSpecialization() &&
447 hasExplicitVisibilityAlready(computation))
448 return false;
449
John McCall5f46c482013-02-21 23:42:58 +0000450 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000451}
452
453/// Merge in template-related linkage and visibility for the given
454/// class template specialization.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000455void LinkageComputer::mergeTemplateLV(
456 LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,
457 LVComputationKind computation) {
John McCalld041a9b2013-02-20 01:54:26 +0000458 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000459
460 // Merge information from the template parameters, but ignore
461 // visibility if we're only considering template arguments.
462
John McCalld041a9b2013-02-20 01:54:26 +0000463 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000464 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000465 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000466 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000467 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000468
469 // Merge information from the template arguments. We ignore
470 // template-argument visibility if we've got an explicit
471 // instantiation with a visibility attribute.
472 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000473 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000474 if (considerVisibility)
475 LV.mergeVisibility(argsLV);
476 LV.mergeExternalVisibility(argsLV);
John McCallb8c604a2011-06-27 23:06:04 +0000477}
478
Larisse Voufo5899e192014-07-02 23:08:34 +0000479/// Should we consider visibility associated with the template
480/// arguments and parameters of the given variable template
481/// specialization? As usual, follow class template specialization
482/// logic up to initialization.
483static bool shouldConsiderTemplateVisibility(
484 const VarTemplateSpecializationDecl *spec,
485 LVComputationKind computation) {
486 // Include visibility from the template parameters and arguments
487 // only if this is not an explicit instantiation or specialization
488 // with direct explicit visibility (and note that implicit
489 // instantiations won't have a direct attribute).
490 if (!spec->isExplicitInstantiationOrSpecialization())
491 return true;
492
493 // An explicit variable specialization is an independent, top-level
494 // declaration. As such, if it has an explicit visibility attribute,
495 // that must directly express the user's intent, and we should honor
496 // it.
497 if (spec->isExplicitSpecialization() &&
498 hasExplicitVisibilityAlready(computation))
499 return false;
500
501 return !hasDirectVisibilityAttribute(spec, computation);
502}
503
504/// Merge in template-related linkage and visibility for the given
505/// variable template specialization. As usual, follow class template
506/// specialization logic up to initialization.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000507void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
508 const VarTemplateSpecializationDecl *spec,
509 LVComputationKind computation) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000510 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
511
512 // Merge information from the template parameters, but ignore
513 // visibility if we're only considering template arguments.
514
515 VarTemplateDecl *temp = spec->getSpecializedTemplate();
516 LinkageInfo tempLV =
517 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
518 LV.mergeMaybeWithVisibility(tempLV,
519 considerVisibility && !hasExplicitVisibilityAlready(computation));
520
521 // Merge information from the template arguments. We ignore
522 // template-argument visibility if we've got an explicit
523 // instantiation with a visibility attribute.
524 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
525 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
526 if (considerVisibility)
527 LV.mergeVisibility(argsLV);
528 LV.mergeExternalVisibility(argsLV);
529}
530
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000531static bool useInlineVisibilityHidden(const NamedDecl *D) {
532 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000533 const LangOptions &Opts = D->getASTContext().getLangOpts();
534 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000535 return false;
536
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000537 const auto *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000538 if (!FD)
539 return false;
540
541 TemplateSpecializationKind TSK = TSK_Undeclared;
542 if (FunctionTemplateSpecializationInfo *spec
543 = FD->getTemplateSpecializationInfo()) {
544 TSK = spec->getTemplateSpecializationKind();
545 } else if (MemberSpecializationInfo *MSI =
546 FD->getMemberSpecializationInfo()) {
547 TSK = MSI->getTemplateSpecializationKind();
548 }
549
Craig Topper36250ad2014-05-12 05:36:57 +0000550 const FunctionDecl *Def = nullptr;
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000551 // InlineVisibilityHidden only applies to definitions, and
552 // isInlined() only gives meaningful answers on definitions
553 // anyway.
554 return TSK != TSK_ExplicitInstantiationDeclaration &&
555 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000556 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000557}
558
Rafael Espindola593537a2013-05-05 20:15:21 +0000559template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000560 const T *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +0000561 return First->isInExternCContext();
Rafael Espindolaf4187652013-02-14 01:18:37 +0000562}
563
Richard Smith03c05032014-02-17 23:34:47 +0000564static bool isSingleLineLanguageLinkage(const Decl &D) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000565 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Richard Smith03c05032014-02-17 23:34:47 +0000566 if (!SD->hasBraces())
Rafael Espindola327be3c2013-04-26 01:30:23 +0000567 return true;
568 return false;
569}
570
Richard Smitha5bbbfe2019-04-18 21:12:54 +0000571/// Determine whether D is declared in the purview of a named module.
572static bool isInModulePurview(const NamedDecl *D) {
573 if (auto *M = D->getOwningModule())
574 return M->isModulePurview();
575 return false;
576}
577
Ali Tamurb6a8a6c2019-04-19 02:15:57 +0000578static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D) {
Richard Smithbecb92d2017-10-10 22:33:17 +0000579 // FIXME: Handle isModulePrivate.
Richard Smith1283e982017-07-07 20:04:28 +0000580 switch (D->getModuleOwnershipKind()) {
581 case Decl::ModuleOwnershipKind::Unowned:
582 case Decl::ModuleOwnershipKind::ModulePrivate:
583 return false;
584 case Decl::ModuleOwnershipKind::Visible:
585 case Decl::ModuleOwnershipKind::VisibleWhenImported:
Richard Smitha5bbbfe2019-04-18 21:12:54 +0000586 return isInModulePurview(D);
Richard Smith1283e982017-07-07 20:04:28 +0000587 }
588 llvm_unreachable("unexpected module ownership kind");
589}
590
591static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
592 // Internal linkage declarations within a module interface unit are modeled
593 // as "module-internal linkage", which means that they have internal linkage
594 // formally but can be indirectly accessed from outside the module via inline
595 // functions and templates defined within the module.
Richard Smitha5bbbfe2019-04-18 21:12:54 +0000596 if (isInModulePurview(D))
597 return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false);
Richard Smith1283e982017-07-07 20:04:28 +0000598
599 return LinkageInfo::internal();
600}
601
602static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
603 // C++ Modules TS [basic.link]/6.8:
604 // - A name declared at namespace scope that does not have internal linkage
605 // by the previous rules and that is introduced by a non-exported
606 // declaration has module linkage.
Richard Smith96451e32019-04-19 02:46:50 +0000607 if (isInModulePurview(D) && !isExportedFromModuleInterfaceUnit(
608 cast<NamedDecl>(D->getCanonicalDecl())))
Richard Smitha5bbbfe2019-04-18 21:12:54 +0000609 return LinkageInfo(ModuleLinkage, DefaultVisibility, false);
Richard Smith1283e982017-07-07 20:04:28 +0000610
611 return LinkageInfo::external();
612}
613
Richard Smithbb750682019-04-26 01:51:08 +0000614static StorageClass getStorageClass(const Decl *D) {
615 if (auto *TD = dyn_cast<TemplateDecl>(D))
616 D = TD->getTemplatedDecl();
Hans Wennborgb0dbc9612019-05-14 10:11:33 +0000617 if (D) {
618 if (auto *VD = dyn_cast<VarDecl>(D))
619 return VD->getStorageClass();
620 if (auto *FD = dyn_cast<FunctionDecl>(D))
621 return FD->getStorageClass();
Richard Smithbb750682019-04-26 01:51:08 +0000622 }
623 return SC_None;
624}
625
George Burgess IV99db3ea2017-08-09 04:02:49 +0000626LinkageInfo
627LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +0000628 LVComputationKind computation,
629 bool IgnoreVarTypeLinkage) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000630 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000631 "Not a name having namespace scope");
632 ASTContext &Context = D->getASTContext();
633
634 // C++ [basic.link]p3:
635 // A name having namespace scope (3.3.6) has internal linkage if it
636 // is the name of
Ilya Biryukovb8292c92019-04-24 08:50:24 +0000637
Hans Wennborgb0dbc9612019-05-14 10:11:33 +0000638 if (getStorageClass(D->getCanonicalDecl()) == SC_Static) {
Richard Smithbb750682019-04-26 01:51:08 +0000639 // - a variable, variable template, function, or function template
640 // that is explicitly declared static; or
641 // (This bullet corresponds to C99 6.2.2p3.)
642 return getInternalLinkageFor(D);
643 }
644
645 if (const auto *Var = dyn_cast<VarDecl>(D)) {
646 // - a non-template variable of non-volatile const-qualified type, unless
647 // - it is explicitly declared extern, or
648 // - it is inline or exported, or
649 // - it was previously declared and the prior declaration did not have
650 // internal linkage
651 // (There is no equivalent in C99.)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000652 if (Context.getLangOpts().CPlusPlus &&
Fangrui Song6907ce22018-07-30 19:24:48 +0000653 Var->getType().isConstQualified() &&
Richard Smith62f19e72016-06-25 00:15:56 +0000654 !Var->getType().isVolatileQualified() &&
Richard Smith1283e982017-07-07 20:04:28 +0000655 !Var->isInline() &&
Richard Smithbb750682019-04-26 01:51:08 +0000656 !isExportedFromModuleInterfaceUnit(Var) &&
657 !isa<VarTemplateSpecializationDecl>(Var) &&
658 !Var->getDescribedVarTemplate()) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000659 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000660 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000661 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000662
663 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000664 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000665 !isSingleLineLanguageLinkage(*Var))
Richard Smith1283e982017-07-07 20:04:28 +0000666 return getInternalLinkageFor(Var);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000667 }
668
669 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
670 PrevVar = PrevVar->getPreviousDecl()) {
671 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
672 Var->getStorageClass() == SC_None)
George Burgess IV35cb4f82017-08-09 04:12:17 +0000673 return getDeclLinkageAndVisibility(PrevVar);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000674 // Explicitly declared static.
675 if (PrevVar->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000676 return getInternalLinkageFor(Var);
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000677 }
David Majnemer18fac3b2014-12-10 22:58:14 +0000678 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
679 // - a data member of an anonymous union.
680 const VarDecl *VD = IFD->getVarDecl();
681 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
Richard Smithc95d2c52017-09-22 04:25:05 +0000682 return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000683 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000684 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000685
Richard Smithbb750682019-04-26 01:51:08 +0000686 // FIXME: This gives internal linkage to names that should have no linkage
687 // (those not covered by [basic.link]p6).
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000688 if (D->isInAnonymousNamespace()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000689 const auto *Var = dyn_cast<VarDecl>(D);
690 const auto *Func = dyn_cast<FunctionDecl>(D);
Richard Smithdf963a32017-09-22 22:21:44 +0000691 // FIXME: The check for extern "C" here is not justified by the standard
692 // wording, but we retain it from the pre-DR1113 model to avoid breaking
693 // code.
Richard Smith1283e982017-07-07 20:04:28 +0000694 //
695 // C++11 [basic.link]p4:
696 // An unnamed namespace or a namespace declared directly or indirectly
697 // within an unnamed namespace has internal linkage.
Rafael Espindola593537a2013-05-05 20:15:21 +0000698 if ((!Var || !isFirstInExternCContext(Var)) &&
699 (!Func || !isFirstInExternCContext(Func)))
Richard Smithdf963a32017-09-22 22:21:44 +0000700 return getInternalLinkageFor(D);
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000701 }
John McCallb7139c42010-10-28 04:18:25 +0000702
John McCall457a04e2010-10-22 21:05:15 +0000703 // Set up the defaults.
704
705 // C99 6.2.2p5:
706 // If the declaration of an identifier for an object has file
707 // scope and no storage-class specifier, its linkage is
708 // external.
Richard Smithdd8b5332017-09-04 05:37:53 +0000709 LinkageInfo LV = getExternalLinkageFor(D);
John McCallc273f242010-10-30 11:50:40 +0000710
John McCalld041a9b2013-02-20 01:54:26 +0000711 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000712 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000713 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000714 } else {
715 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000716 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000717 for (const DeclContext *DC = D->getDeclContext();
718 !isa<TranslationUnitDecl>(DC);
719 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000720 const auto *ND = dyn_cast<NamespaceDecl>(DC);
Rafael Espindola78158af2012-04-16 18:46:26 +0000721 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000722 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000723 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000724 break;
725 }
726 }
727 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000728
John McCalldf25c432013-02-16 00:17:33 +0000729 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000730 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000731 // Use global type/value visibility as appropriate.
Richard Smithfbe7b462017-09-22 02:22:32 +0000732 Visibility globalVisibility =
733 computation.isValueVisibility()
734 ? Context.getLangOpts().getValueVisibilityMode()
735 : Context.getLangOpts().getTypeVisibilityMode();
John McCallb4a99d32013-02-19 01:57:35 +0000736 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000737
738 // If we're paying attention to global visibility, apply
739 // -finline-visibility-hidden if this is an inline method.
740 if (useInlineVisibilityHidden(D))
Reid Klecknera52d1512018-10-10 21:59:56 +0000741 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
John McCalldf25c432013-02-16 00:17:33 +0000742 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000743 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000744
Douglas Gregorf73b2822009-11-25 22:24:25 +0000745 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000746
Richard Smithbb750682019-04-26 01:51:08 +0000747 // A name having namespace scope that has not been given internal linkage
748 // above and that is the name of
749 // [...bullets...]
750 // has its linkage determined as follows:
751 // - if the enclosing namespace has internal linkage, the name has
752 // internal linkage; [handled above]
753 // - otherwise, if the declaration of the name is attached to a named
754 // module and is not exported, the name has module linkage;
755 // - otherwise, the name has external linkage.
756 // LV is currently set up to handle the last two bullets.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000757 //
Richard Smithbb750682019-04-26 01:51:08 +0000758 // The bullets are:
759
760 // - a variable; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000761 if (const auto *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000762 // GCC applies the following optimization to variables and static
763 // data members, but not to functions:
764 //
John McCall457a04e2010-10-22 21:05:15 +0000765 // Modify the variable's LV by the LV of its type unless this is
766 // C or extern "C". This follows from [basic.link]p9:
767 // A type without linkage shall not be used as the type of a
768 // variable or function with external linkage unless
769 // - the entity has C language linkage, or
770 // - the entity is declared within an unnamed namespace, or
771 // - the entity is not used or is defined in the same
772 // translation unit.
773 // and [basic.link]p10:
774 // ...the types specified by all declarations referring to a
775 // given variable or function shall be identical...
776 // C does not have an equivalent rule.
777 //
John McCall5fe84122010-10-26 04:59:26 +0000778 // Ignore this if we've got an explicit attribute; the user
779 // probably knows what they're doing.
780 //
John McCall457a04e2010-10-22 21:05:15 +0000781 // Note that we don't want to make the variable non-external
782 // because of this, but unique-external linkage suits us.
Richard Smithc95d2c52017-09-22 04:25:05 +0000783 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
784 !IgnoreVarTypeLinkage) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000785 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Richard Smith405e2db2017-09-20 07:22:00 +0000786 if (!isExternallyVisible(TypeLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000787 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000788 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000789 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000790 }
791
John McCall23032652010-11-02 18:38:13 +0000792 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000793 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000794
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000795 // Note that Sema::MergeVarDecl already takes care of implementing
796 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
797 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000798
Larisse Voufo5899e192014-07-02 23:08:34 +0000799 // As per function and class template specializations (below),
800 // consider LV for the template and template arguments. We're at file
801 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000802 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000803 mergeTemplateLV(LV, spec, computation);
804 }
805
Richard Smithbb750682019-04-26 01:51:08 +0000806 // - a function; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000807 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000808 // In theory, we can modify the function's LV by the LV of its
809 // type unless it has C linkage (see comment above about variables
810 // for justification). In practice, GCC doesn't do this, so it's
811 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000812
John McCall23032652010-11-02 18:38:13 +0000813 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000814 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000815
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000816 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
817 // merging storage classes and visibility attributes, so we don't have to
818 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000819
John McCallf768aa72011-02-10 06:50:24 +0000820 // In C++, then if the type of the function uses a type with
821 // unique-external linkage, it's not legally usable from outside
822 // this translation unit. However, we should use the C linkage
823 // rules instead for extern "C" declarations.
Richard Smith99f54792018-01-03 02:34:35 +0000824 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
Richard Smithc95d2c52017-09-22 04:25:05 +0000825 // Only look at the type-as-written. Otherwise, deducing the return type
826 // of a function could change its linkage.
Richard Smith50f4afc2013-05-12 23:17:59 +0000827 QualType TypeAsWritten = Function->getType();
828 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
829 TypeAsWritten = TSI->getType();
Richard Smith405e2db2017-09-20 07:22:00 +0000830 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
Richard Smith50f4afc2013-05-12 23:17:59 +0000831 return LinkageInfo::uniqueExternal();
832 }
John McCallf768aa72011-02-10 06:50:24 +0000833
John McCall5f46c482013-02-21 23:42:58 +0000834 // Consider LV from the template and the template arguments.
835 // We're at file scope, so we do not need to worry about nested
836 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000837 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000838 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000839 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000840 }
841
Douglas Gregorf73b2822009-11-25 22:24:25 +0000842 // - a named class (Clause 9), or an unnamed class defined in a
843 // typedef declaration in which the class has the typedef name
844 // for linkage purposes (7.1.3); or
845 // - a named enumeration (7.2), or an unnamed enumeration
846 // defined in a typedef declaration in which the enumeration
847 // has the typedef name for linkage purposes (7.1.3); or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000848 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000849 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000850 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000851 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000852
John McCall457a04e2010-10-22 21:05:15 +0000853 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000854 // linkage of the template and template arguments. We're at file
855 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000856 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000857 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000858 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000859
Richard Smithbb750682019-04-26 01:51:08 +0000860 // FIXME: This is not part of the C++ standard any more.
861 // - an enumerator belonging to an enumeration with external linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000862 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000863 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000864 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000865 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000866 return LinkageInfo::none();
867 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000868
Richard Smithbb750682019-04-26 01:51:08 +0000869 // - a template
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000870 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000871 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000872 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000873 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000874 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
875
Richard Smithbb750682019-04-26 01:51:08 +0000876 // An unnamed namespace or a namespace declared directly or indirectly
877 // within an unnamed namespace has internal linkage. All other namespaces
878 // have external linkage.
Richard Smith1283e982017-07-07 20:04:28 +0000879 //
880 // We handled names in anonymous namespaces above.
881 } else if (isa<NamespaceDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000882 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000883
John McCall457a04e2010-10-22 21:05:15 +0000884 // By extension, we assign external linkage to Objective-C
885 // interfaces.
886 } else if (isa<ObjCInterfaceDecl>(D)) {
887 // fallout
888
Richard Smith97135cc2015-11-12 22:19:45 +0000889 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
890 // A typedef declaration has linkage if it gives a type a name for
891 // linkage purposes.
892 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
893 return LinkageInfo::none();
894
John McCall457a04e2010-10-22 21:05:15 +0000895 // Everything not covered here has no linkage.
896 } else {
John McCallc273f242010-10-30 11:50:40 +0000897 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000898 }
899
Richard Smithc445d5d2017-10-03 01:58:15 +0000900 // If we ended up with non-externally-visible linkage, visibility should
John McCall457a04e2010-10-22 21:05:15 +0000901 // always be default.
Richard Smithc445d5d2017-10-03 01:58:15 +0000902 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola4a5da442013-02-27 02:56:45 +0000903 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000904
Alexey Bataevbbc328c2019-11-21 11:30:43 -0500905 // Mark the symbols as hidden when compiling for the device.
906 if (Context.getLangOpts().OpenMP && Context.getLangOpts().OpenMPIsDevice)
907 LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
908
John McCall457a04e2010-10-22 21:05:15 +0000909 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000910}
911
George Burgess IV99db3ea2017-08-09 04:02:49 +0000912LinkageInfo
913LinkageComputer::getLVForClassMember(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +0000914 LVComputationKind computation,
915 bool IgnoreVarTypeLinkage) {
John McCall457a04e2010-10-22 21:05:15 +0000916 // Only certain class members have linkage. Note that fields don't
917 // really have linkage, but it's convenient to say they do for the
918 // purposes of calculating linkage of pointer-to-data-member
919 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000920 //
921 // Templates also don't officially have linkage, but since we ignore
922 // the C++ standard and look at template arguments when determining
923 // linkage and visibility of a template specialization, we might hit
924 // a template template argument that way. If we do, we need to
925 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000926 if (!(isa<CXXMethodDecl>(D) ||
927 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000928 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000929 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000930 isa<TagDecl>(D) ||
931 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000932 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000933
John McCall07072662010-11-02 01:45:15 +0000934 LinkageInfo LV;
935
John McCall07072662010-11-02 01:45:15 +0000936 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000937 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000938 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000939 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000940 // If we're paying attention to global visibility, apply
941 // -finline-visibility-hidden if this is an inline method.
942 //
943 // Note that we do this before merging information about
944 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000945 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Reid Klecknera52d1512018-10-10 21:59:56 +0000946 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
John McCall07072662010-11-02 01:45:15 +0000947 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000948
949 // If this class member has an explicit visibility attribute, the only
950 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000951 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000952 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000953 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000954 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000955
John McCall5f46c482013-02-21 23:42:58 +0000956 LinkageInfo classLV =
957 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
Richard Smithcdb06f22017-09-23 04:02:17 +0000958 // The member has the same linkage as the class. If that's not externally
959 // visible, we don't need to compute anything about the linkage.
960 // FIXME: If we're only computing linkage, can we bail out here?
Rafael Espindolae6190db2013-05-28 02:22:10 +0000961 if (!isExternallyVisible(classLV.getLinkage()))
Richard Smithcdb06f22017-09-23 04:02:17 +0000962 return classLV;
Rafael Espindolae6190db2013-05-28 02:22:10 +0000963
964
John McCall5f46c482013-02-21 23:42:58 +0000965 // Otherwise, don't merge in classLV yet, because in certain cases
966 // we need to completely ignore the visibility from it.
967
968 // Specifically, if this decl exists and has an explicit attribute.
Craig Topper36250ad2014-05-12 05:36:57 +0000969 const NamedDecl *explicitSpecSuppressor = nullptr;
John McCall5f46c482013-02-21 23:42:58 +0000970
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000971 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc95d2c52017-09-22 04:25:05 +0000972 // Only look at the type-as-written. Otherwise, deducing the return type
973 // of a function could change its linkage.
974 QualType TypeAsWritten = MD->getType();
975 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
976 TypeAsWritten = TSI->getType();
977 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
978 return LinkageInfo::uniqueExternal();
979
John McCall457a04e2010-10-22 21:05:15 +0000980 // If this is a method template specialization, use the linkage for
981 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000982 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000983 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000984 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000985 if (spec->isExplicitSpecialization()) {
986 explicitSpecSuppressor = MD;
987 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
988 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
989 }
990 } else if (isExplicitMemberSpecialization(MD)) {
991 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000992 }
John McCall457a04e2010-10-22 21:05:15 +0000993
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000994 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
995 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000996 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000997 if (spec->isExplicitSpecialization()) {
998 explicitSpecSuppressor = spec;
999 } else {
1000 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
1001 if (isExplicitMemberSpecialization(temp)) {
1002 explicitSpecSuppressor = temp->getTemplatedDecl();
1003 }
1004 }
1005 } else if (isExplicitMemberSpecialization(RD)) {
1006 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +00001007 }
1008
John McCall37bb6c92010-10-29 22:22:43 +00001009 // Static data members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001010 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
1011 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
Larisse Voufo5899e192014-07-02 23:08:34 +00001012 mergeTemplateLV(LV, spec, computation);
1013
John McCall36cd5cc2010-10-30 09:18:49 +00001014 // Modify the variable's linkage by its type, but ignore the
1015 // type's visibility unless it's a definition.
Richard Smithc95d2c52017-09-22 04:25:05 +00001016 if (!IgnoreVarTypeLinkage) {
1017 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
1018 // FIXME: If the type's linkage is not externally visible, we can
1019 // give this static data member UniqueExternalLinkage.
1020 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
1021 LV.mergeVisibility(typeLV);
1022 LV.mergeExternalVisibility(typeLV);
1023 }
John McCall5f46c482013-02-21 23:42:58 +00001024
1025 if (isExplicitMemberSpecialization(VD)) {
1026 explicitSpecSuppressor = VD;
1027 }
John McCalldf25c432013-02-16 00:17:33 +00001028
1029 // Template members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001030 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001031 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +00001032 (!LV.isVisibilityExplicit() &&
1033 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +00001034 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +00001035 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +00001036 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +00001037 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +00001038
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001039 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
John McCall5f46c482013-02-21 23:42:58 +00001040 if (isExplicitMemberSpecialization(redeclTemp)) {
1041 explicitSpecSuppressor = temp->getTemplatedDecl();
1042 }
1043 }
John McCall37bb6c92010-10-29 22:22:43 +00001044 }
1045
John McCall5f46c482013-02-21 23:42:58 +00001046 // We should never be looking for an attribute directly on a template.
1047 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1048
1049 // If this member is an explicit member specialization, and it has
1050 // an explicit attribute, ignore visibility from the parent.
1051 bool considerClassVisibility = true;
1052 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +00001053 // optimization: hasDVA() is true only with explicit visibility.
1054 LV.isVisibilityExplicit() &&
1055 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +00001056 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
1057 considerClassVisibility = false;
1058 }
1059
1060 // Finally, merge in information from the class.
1061 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +00001062 return LV;
John McCall8823c652010-08-13 08:35:10 +00001063}
1064
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001065void NamedDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00001066
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001067bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001068 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001069 return true;
John McCalld396b972011-02-08 19:01:05 +00001070
Richard Smithfbe7b462017-09-22 02:22:32 +00001071 Linkage L = LinkageComputer{}
1072 .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
1073 .getLinkage();
George Burgess IV99db3ea2017-08-09 04:02:49 +00001074 return L == getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +00001075}
1076
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001077ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1078 StringRef name = getName();
1079 if (name.empty()) return SFF_None;
Fangrui Song6907ce22018-07-30 19:24:48 +00001080
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001081 if (name.front() == 'C')
1082 if (name == "CFStringCreateWithFormat" ||
1083 name == "CFStringCreateWithFormatAndArguments" ||
1084 name == "CFStringAppendFormat" ||
1085 name == "CFStringAppendFormatAndArguments")
1086 return SFF_CFString;
1087 return SFF_None;
1088}
1089
Rafael Espindola3ae00052013-05-13 00:12:11 +00001090Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +00001091 // We don't care about visibility here, so ask for the cheapest
1092 // possible visibility analysis.
Richard Smithfbe7b462017-09-22 02:22:32 +00001093 return LinkageComputer{}
1094 .getLVForDecl(this, LVComputationKind::forLinkageOnly())
1095 .getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001096}
1097
John McCallc273f242010-10-30 11:50:40 +00001098LinkageInfo NamedDecl::getLinkageAndVisibility() const {
George Burgess IV99db3ea2017-08-09 04:02:49 +00001099 return LinkageComputer{}.getDeclLinkageAndVisibility(this);
John McCall033caa52010-10-29 00:29:13 +00001100}
Ted Kremenek926d8602010-04-20 23:15:35 +00001101
Rafael Espindola9ad61122013-11-26 16:09:08 +00001102static Optional<Visibility>
1103getExplicitVisibilityAux(const NamedDecl *ND,
1104 NamedDecl::ExplicitVisibilityKind kind,
1105 bool IsMostRecent) {
1106 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1107
Rafael Espindola3a52c442013-02-26 19:33:14 +00001108 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001109 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001110 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001111
Rafael Espindola3a52c442013-02-26 19:33:14 +00001112 // If this is a member class of a specialization of a class template
1113 // and the corresponding decl has explicit visibility, use that.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001114 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +00001115 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1116 if (InstantiatedFrom)
1117 return getVisibilityOf(InstantiatedFrom, kind);
1118 }
1119
1120 // If there wasn't explicit visibility there, and this is a
1121 // specialization of a class template, check for visibility
1122 // on the pattern.
Steven Wu79cbd112018-04-19 15:46:43 +00001123 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
1124 // Walk all the template decl till this point to see if there are
1125 // explicit visibility attributes.
1126 const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();
1127 while (TD != nullptr) {
1128 auto Vis = getVisibilityOf(TD, kind);
1129 if (Vis != None)
1130 return Vis;
1131 TD = TD->getPreviousDecl();
1132 }
1133 return None;
1134 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001135
1136 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +00001137 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +00001138 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1139 if (MostRecent != ND)
1140 return getExplicitVisibilityAux(MostRecent, kind, true);
1141 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001142
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001143 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +00001144 if (Var->isStaticDataMember()) {
1145 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1146 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001147 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +00001148 }
1149
David Majnemer35b02bc2014-04-29 07:32:26 +00001150 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1151 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1152 kind);
1153
David Blaikie7a30dc52013-02-21 01:47:18 +00001154 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +00001155 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001156 // Also handle function template specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001157 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001158 // If the function is a specialization of a template with an
1159 // explicit visibility attribute, use that.
1160 if (FunctionTemplateSpecializationInfo *templateInfo
1161 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +00001162 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1163 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001164
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001165 // If the function is a member of a specialization of a class template
1166 // and the corresponding decl has explicit visibility, use that.
1167 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1168 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001169 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001170
David Blaikie7a30dc52013-02-21 01:47:18 +00001171 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001172 }
1173
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001174 // The visibility of a template is stored in the templated decl.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001175 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001176 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001177
David Blaikie7a30dc52013-02-21 01:47:18 +00001178 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001179}
1180
Rafael Espindola9ad61122013-11-26 16:09:08 +00001181Optional<Visibility>
1182NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1183 return getExplicitVisibilityAux(this, kind, false);
1184}
1185
George Burgess IV99db3ea2017-08-09 04:02:49 +00001186LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1187 Decl *ContextDecl,
1188 LVComputationKind computation) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001189 // This lambda has its linkage/visibility determined by its owner.
Richard Smithc95d2c52017-09-22 04:25:05 +00001190 const NamedDecl *Owner;
1191 if (!ContextDecl)
1192 Owner = dyn_cast<NamedDecl>(DC);
1193 else if (isa<ParmVarDecl>(ContextDecl))
1194 Owner =
1195 dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1196 else
1197 Owner = cast<NamedDecl>(ContextDecl);
1198
Richard Smithc95d2c52017-09-22 04:25:05 +00001199 if (!Owner)
Richard Smith7ff83042017-09-22 04:33:20 +00001200 return LinkageInfo::none();
Richard Smithc95d2c52017-09-22 04:25:05 +00001201
1202 // If the owner has a deduced type, we need to skip querying the linkage and
1203 // visibility of that type, because it might involve this closure type. The
1204 // only effect of this is that we might give a lambda VisibleNoLinkage rather
1205 // than NoLinkage when we don't strictly need to, which is benign.
1206 auto *VD = dyn_cast<VarDecl>(Owner);
Richard Smith7ff83042017-09-22 04:33:20 +00001207 LinkageInfo OwnerLV =
Richard Smithc95d2c52017-09-22 04:25:05 +00001208 VD && VD->getType()->getContainedDeducedType()
1209 ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1210 : getLVForDecl(Owner, computation);
1211
Richard Smith7ff83042017-09-22 04:33:20 +00001212 // A lambda never formally has linkage. But if the owner is externally
1213 // visible, then the lambda is too. We apply the same rules to blocks.
1214 if (!isExternallyVisible(OwnerLV.getLinkage()))
1215 return LinkageInfo::none();
1216 return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
1217 OwnerLV.isVisibilityExplicit());
Eli Friedman7e346a82013-07-01 20:22:57 +00001218}
1219
George Burgess IV99db3ea2017-08-09 04:02:49 +00001220LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1221 LVComputationKind computation) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001222 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001223 if (Function->isInAnonymousNamespace() &&
Richard Smith99f54792018-01-03 02:34:35 +00001224 !isFirstInExternCContext(Function))
Richard Smithdf963a32017-09-22 22:21:44 +00001225 return getInternalLinkageFor(Function);
John McCalldf25c432013-02-16 00:17:33 +00001226
1227 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001228 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +00001229 return getInternalLinkageFor(Function);
John McCalldf25c432013-02-16 00:17:33 +00001230
1231 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001232 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001233 if (Optional<Visibility> Vis =
1234 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001235 LV.mergeVisibility(*Vis, true);
1236 }
1237
1238 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1239 // merging storage classes and visibility attributes, so we don't have to
1240 // look at previous decls in here.
1241
1242 return LV;
1243 }
1244
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001245 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001246 if (Var->hasExternalStorage()) {
Richard Smith99f54792018-01-03 02:34:35 +00001247 if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
Richard Smithdf963a32017-09-22 22:21:44 +00001248 return getInternalLinkageFor(Var);
John McCalldf25c432013-02-16 00:17:33 +00001249
John McCalldf25c432013-02-16 00:17:33 +00001250 LinkageInfo LV;
1251 if (Var->getStorageClass() == SC_PrivateExtern)
1252 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001253 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001254 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001255 LV.mergeVisibility(*Vis, true);
1256 }
1257
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001258 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1259 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1260 if (PrevLV.getLinkage())
1261 LV.setLinkage(PrevLV.getLinkage());
1262 LV.mergeVisibility(PrevLV);
1263 }
1264
John McCalldf25c432013-02-16 00:17:33 +00001265 return LV;
1266 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001267
1268 if (!Var->isStaticLocal())
1269 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001270 }
1271
Rafael Espindolaa4184182013-06-17 20:04:51 +00001272 ASTContext &Context = D->getASTContext();
1273 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001274 return LinkageInfo::none();
1275
Eli Friedman7e346a82013-07-01 20:22:57 +00001276 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
Alexey Bataev0a47e652016-01-12 09:01:25 +00001277 if (!OuterD || OuterD->isInvalidDecl())
Rafael Espindola50df3a02013-05-25 17:16:20 +00001278 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001279
Eli Friedman7e346a82013-07-01 20:22:57 +00001280 LinkageInfo LV;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001281 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001282 if (!BD->getBlockManglingNumber())
1283 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001284
Eli Friedman7e346a82013-07-01 20:22:57 +00001285 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1286 BD->getBlockManglingContextDecl(), computation);
1287 } else {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001288 const auto *FD = cast<FunctionDecl>(OuterD);
Eli Friedman7e346a82013-07-01 20:22:57 +00001289 if (!FD->isInlined() &&
David Majnemer9963ade2014-12-16 04:52:14 +00001290 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
Eli Friedman7e346a82013-07-01 20:22:57 +00001291 return LinkageInfo::none();
1292
Hiroshi Inoue03ff37d2018-08-22 05:43:27 +00001293 // If a function is hidden by -fvisibility-inlines-hidden option and
1294 // is not explicitly attributed as a hidden function,
1295 // we should not make static local variables in the function hidden.
Eli Friedman7e346a82013-07-01 20:22:57 +00001296 LV = getLVForDecl(FD, computation);
Reid Klecknera52d1512018-10-10 21:59:56 +00001297 if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) &&
1298 !LV.isVisibilityExplicit()) {
1299 assert(cast<VarDecl>(D)->isStaticLocal());
1300 // If this was an implicitly hidden inline method, check again for
1301 // explicit visibility on the parent class, and use that for static locals
1302 // if present.
1303 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1304 LV = getLVForDecl(MD->getParent(), computation);
1305 if (!LV.isVisibilityExplicit()) {
1306 Visibility globalVisibility =
1307 computation.isValueVisibility()
1308 ? Context.getLangOpts().getValueVisibilityMode()
1309 : Context.getLangOpts().getTypeVisibilityMode();
1310 return LinkageInfo(VisibleNoLinkage, globalVisibility,
1311 /*visibilityExplicit=*/false);
1312 }
1313 }
Eli Friedman7e346a82013-07-01 20:22:57 +00001314 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001315 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001316 return LinkageInfo::none();
1317 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1318 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001319}
1320
George Burgess IV99db3ea2017-08-09 04:02:49 +00001321LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +00001322 LVComputationKind computation,
1323 bool IgnoreVarTypeLinkage) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001324 // Internal_linkage attribute overrides other considerations.
1325 if (D->hasAttr<InternalLinkageAttr>())
Richard Smith1283e982017-07-07 20:04:28 +00001326 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001327
Ted Kremenek926d8602010-04-20 23:15:35 +00001328 // Objective-C: treat all Objective-C declarations as having external
1329 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001330 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001331 default:
1332 break;
Richard Smith97135cc2015-11-12 22:19:45 +00001333
1334 // Per C++ [basic.link]p2, only the names of objects, references,
1335 // functions, types, templates, namespaces, and values ever have linkage.
1336 //
1337 // Note that the name of a typedef, namespace alias, using declaration,
1338 // and so on are not the name of the corresponding type, namespace, or
1339 // declaration, so they do *not* have linkage.
Richard Smith97135cc2015-11-12 22:19:45 +00001340 case Decl::ImplicitParam:
1341 case Decl::Label:
1342 case Decl::NamespaceAlias:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001343 case Decl::ParmVar:
Richard Smith97135cc2015-11-12 22:19:45 +00001344 case Decl::Using:
1345 case Decl::UsingShadow:
1346 case Decl::UsingDirective:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001347 return LinkageInfo::none();
Richard Smith97135cc2015-11-12 22:19:45 +00001348
Richard Smith26210db2015-11-13 03:52:13 +00001349 case Decl::EnumConstant:
1350 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
Bruno Cardoso Lopes057c82c2017-07-01 00:06:27 +00001351 if (D->getASTContext().getLangOpts().CPlusPlus)
1352 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1353 return LinkageInfo::visible_none();
Richard Smith26210db2015-11-13 03:52:13 +00001354
Richard Smith97135cc2015-11-12 22:19:45 +00001355 case Decl::Typedef:
1356 case Decl::TypeAlias:
1357 // A typedef declaration has linkage if it gives a type a name for
1358 // linkage purposes.
Vassil Vassilevb00ea082017-07-01 20:44:49 +00001359 if (!cast<TypedefNameDecl>(D)
Richard Smith97135cc2015-11-12 22:19:45 +00001360 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1361 return LinkageInfo::none();
1362 break;
1363
John McCall457a04e2010-10-22 21:05:15 +00001364 case Decl::TemplateTemplateParm: // count these as external
1365 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001366 case Decl::ObjCAtDefsField:
1367 case Decl::ObjCCategory:
1368 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001369 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001370 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001371 case Decl::ObjCMethod:
1372 case Decl::ObjCProperty:
1373 case Decl::ObjCPropertyImpl:
1374 case Decl::ObjCProtocol:
Richard Smith1283e982017-07-07 20:04:28 +00001375 return getExternalLinkageFor(D);
Fangrui Song6907ce22018-07-30 19:24:48 +00001376
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001377 case Decl::CXXRecord: {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001378 const auto *Record = cast<CXXRecordDecl>(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001379 if (Record->isLambda()) {
Michael Liao243ebfb2019-10-19 00:15:19 +00001380 if (Record->hasKnownLambdaInternalLinkage() ||
1381 !Record->getLambdaManglingNumber()) {
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001382 // This lambda has no mangling number, so it's internal.
Richard Smith1283e982017-07-07 20:04:28 +00001383 return getInternalLinkageFor(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001384 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001385
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001386 return getLVForClosure(
Michael Liao29269172020-02-07 12:58:17 -05001387 Record->getDeclContext()->getRedeclContext(),
1388 Record->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001389 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001390
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001391 break;
1392 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001393 }
1394
Douglas Gregorf73b2822009-11-25 22:24:25 +00001395 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001396 if (D->getDeclContext()->getRedeclContext()->isFileContext())
Richard Smithc95d2c52017-09-22 04:25:05 +00001397 return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
Fangrui Song6907ce22018-07-30 19:24:48 +00001398
Douglas Gregorf73b2822009-11-25 22:24:25 +00001399 // C++ [basic.link]p5:
1400 // In addition, a member function, static data member, a named
1401 // class or enumeration of class scope, or an unnamed class or
1402 // enumeration defined in a class-scope typedef declaration such
1403 // that the class or enumeration has the typedef name for linkage
1404 // purposes (7.1.3), has external linkage if the name of the class
1405 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001406 if (D->getDeclContext()->isRecord())
Richard Smithc95d2c52017-09-22 04:25:05 +00001407 return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001408
1409 // C++ [basic.link]p6:
1410 // The name of a function declared in block scope and the name of
1411 // an object declared by a block scope extern declaration have
1412 // linkage. If there is a visible declaration of an entity with
1413 // linkage having the same name and type, ignoring entities
1414 // declared outside the innermost enclosing namespace scope, the
1415 // block scope declaration declares that same entity and receives
1416 // the linkage of the previous declaration. If there is more than
1417 // one such matching entity, the program is ill-formed. Otherwise,
1418 // if no matching entity is found, the block scope entity receives
1419 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001420 if (D->getDeclContext()->isFunctionOrMethod())
1421 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001422
1423 // C++ [basic.link]p6:
1424 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001425 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001426}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001427
George Burgess IV99db3ea2017-08-09 04:02:49 +00001428/// getLVForDecl - Get the linkage and visibility for the given declaration.
1429LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1430 LVComputationKind computation) {
1431 // Internal_linkage attribute overrides other considerations.
1432 if (D->hasAttr<InternalLinkageAttr>())
1433 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001434
Richard Smithfbe7b462017-09-22 02:22:32 +00001435 if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
George Burgess IV99db3ea2017-08-09 04:02:49 +00001436 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001437
George Burgess IV35cb4f82017-08-09 04:12:17 +00001438 if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
1439 return *LI;
1440
George Burgess IV99db3ea2017-08-09 04:02:49 +00001441 LinkageInfo LV = computeLVForDecl(D, computation);
1442 if (D->hasCachedLinkage())
1443 assert(D->getCachedLinkage() == LV.getLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001444
George Burgess IV99db3ea2017-08-09 04:02:49 +00001445 D->setCachedLinkage(LV.getLinkage());
George Burgess IV35cb4f82017-08-09 04:12:17 +00001446 cache(D, computation, LV);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001447
1448#ifndef NDEBUG
George Burgess IV99db3ea2017-08-09 04:02:49 +00001449 // In C (because of gnu inline) and in c++ with microsoft extensions an
1450 // static can follow an extern, so we can have two decls with different
1451 // linkages.
1452 const LangOptions &Opts = D->getASTContext().getLangOpts();
1453 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1454 return LV;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001455
George Burgess IV99db3ea2017-08-09 04:02:49 +00001456 // We have just computed the linkage for this decl. By induction we know
1457 // that all other computed linkages match, check that the one we just
1458 // computed also does.
1459 NamedDecl *Old = nullptr;
1460 for (auto I : D->redecls()) {
1461 auto *T = cast<NamedDecl>(I);
1462 if (T == D)
1463 continue;
1464 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1465 Old = T;
1466 break;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001467 }
George Burgess IV99db3ea2017-08-09 04:02:49 +00001468 }
1469 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001470#endif
1471
George Burgess IV99db3ea2017-08-09 04:02:49 +00001472 return LV;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001473}
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001474
George Burgess IV99db3ea2017-08-09 04:02:49 +00001475LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
Richard Smithfbe7b462017-09-22 02:22:32 +00001476 return getLVForDecl(D,
1477 LVComputationKind(usesTypeVisibility(D)
1478 ? NamedDecl::VisibilityForType
1479 : NamedDecl::VisibilityForValue));
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001480}
1481
Richard Smithbecb92d2017-10-10 22:33:17 +00001482Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
Richard Smithdd8b5332017-09-04 05:37:53 +00001483 Module *M = getOwningModule();
1484 if (!M)
1485 return nullptr;
1486
1487 switch (M->Kind) {
1488 case Module::ModuleMapModule:
1489 // Module map modules have no special linkage semantics.
1490 return nullptr;
1491
1492 case Module::ModuleInterfaceUnit:
1493 return M;
1494
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001495 case Module::GlobalModuleFragment: {
Richard Smithdd8b5332017-09-04 05:37:53 +00001496 // External linkage declarations in the global module have no owning module
1497 // for linkage purposes. But internal linkage declarations in the global
1498 // module fragment of a particular module are owned by that module for
1499 // linkage purposes.
Richard Smithbecb92d2017-10-10 22:33:17 +00001500 if (IgnoreLinkage)
1501 return nullptr;
1502 bool InternalLinkage;
1503 if (auto *ND = dyn_cast<NamedDecl>(this))
1504 InternalLinkage = !ND->hasExternalFormalLinkage();
1505 else {
1506 auto *NSD = dyn_cast<NamespaceDecl>(this);
1507 InternalLinkage = (NSD && NSD->isAnonymousNamespace()) ||
1508 isInAnonymousNamespace();
1509 }
1510 return InternalLinkage ? M->Parent : nullptr;
Richard Smithdd8b5332017-09-04 05:37:53 +00001511 }
Richard Smitha5bbbfe2019-04-18 21:12:54 +00001512
1513 case Module::PrivateModuleFragment:
1514 // The private module fragment is part of its containing module for linkage
1515 // purposes.
1516 return M->Parent;
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001517 }
Richard Smithdd8b5332017-09-04 05:37:53 +00001518
1519 llvm_unreachable("unknown module kind");
1520}
1521
Richard Smith7873de02016-08-11 22:25:46 +00001522void NamedDecl::printName(raw_ostream &os) const {
1523 os << Name;
1524}
1525
Douglas Gregor2ada0482009-02-04 17:27:36 +00001526std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001527 std::string QualName;
1528 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001529 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001530 return OS.str();
1531}
1532
1533void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1534 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1535}
1536
1537void NamedDecl::printQualifiedName(raw_ostream &OS,
1538 const PrintingPolicy &P) const {
Ilya Biryukov66482232019-09-25 15:46:04 +00001539 if (getDeclContext()->isFunctionOrMethod()) {
1540 // We do not print '(anonymous)' for function parameters without name.
1541 printName(OS);
1542 return;
1543 }
1544 printNestedNameSpecifier(OS, P);
Richard Smith9bd6b772020-04-14 23:35:35 -07001545 if (getDeclName())
Ilya Biryukov66482232019-09-25 15:46:04 +00001546 OS << *this;
Richard Smith9bd6b772020-04-14 23:35:35 -07001547 else {
1548 // Give the printName override a chance to pick a different name before we
1549 // fall back to "(anonymous)".
1550 SmallString<64> NameBuffer;
1551 llvm::raw_svector_ostream NameOS(NameBuffer);
1552 printName(NameOS);
1553 if (NameBuffer.empty())
1554 OS << "(anonymous)";
1555 else
1556 OS << NameBuffer;
1557 }
Ilya Biryukov66482232019-09-25 15:46:04 +00001558}
1559
1560void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
1561 printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
1562}
1563
1564void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
1565 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001566 const DeclContext *Ctx = getDeclContext();
1567
David Goldman19d21852019-04-04 20:13:22 +00001568 // For ObjC methods and properties, look through categories and use the
1569 // interface as context.
Argyrios Kyrtzidisa166a2b2017-03-07 09:26:07 +00001570 if (auto *MD = dyn_cast<ObjCMethodDecl>(this))
1571 if (auto *ID = MD->getClassInterface())
1572 Ctx = ID;
David Goldman19d21852019-04-04 20:13:22 +00001573 if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
1574 if (auto *MD = PD->getGetterMethodDecl())
1575 if (auto *ID = MD->getClassInterface())
1576 Ctx = ID;
1577 }
Argyrios Kyrtzidisa166a2b2017-03-07 09:26:07 +00001578
Ilya Biryukov66482232019-09-25 15:46:04 +00001579 if (Ctx->isFunctionOrMethod())
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001580 return;
Douglas Gregor2ada0482009-02-04 17:27:36 +00001581
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001582 using ContextsTy = SmallVector<const DeclContext *, 8>;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001583 ContextsTy Contexts;
1584
Sam McCall34f9d3f2018-02-02 13:34:47 +00001585 // Collect named contexts.
1586 while (Ctx) {
1587 if (isa<NamedDecl>(Ctx))
1588 Contexts.push_back(Ctx);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001589 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001590 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001591
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001592 for (const DeclContext *DC : llvm::reverse(Contexts)) {
David Majnemerf7e36092016-06-23 00:15:04 +00001593 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001594 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001595 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Serge Pavlov03e672c2017-11-28 16:14:14 +00001596 printTemplateArgumentList(OS, TemplateArgs.asArray(), P);
David Majnemerf7e36092016-06-23 00:15:04 +00001597 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
Richard Smith46dd5bb2014-05-30 22:16:51 +00001598 if (P.SuppressUnwrittenScope &&
1599 (ND->isAnonymousNamespace() || ND->isInline()))
1600 continue;
Reid Kleckner60103382015-12-16 02:04:40 +00001601 if (ND->isAnonymousNamespace()) {
1602 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1603 : "(anonymous namespace)");
1604 }
Sam Weinig07d211e2009-12-24 23:15:03 +00001605 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001606 OS << *ND;
David Majnemerf7e36092016-06-23 00:15:04 +00001607 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001608 if (!RD->getIdentifier())
David Blaikieabe1a392014-04-02 05:58:29 +00001609 OS << "(anonymous " << RD->getKindName() << ')';
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001610 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001611 OS << *RD;
David Majnemerf7e36092016-06-23 00:15:04 +00001612 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
Craig Topper36250ad2014-05-12 05:36:57 +00001613 const FunctionProtoType *FT = nullptr;
Sam Weinigb999f682009-12-28 03:19:38 +00001614 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001615 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001616
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001617 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001618 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001619 unsigned NumParams = FD->getNumParams();
1620 for (unsigned i = 0; i < NumParams; ++i) {
1621 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001622 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001623 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001624 }
1625
1626 if (FT->isVariadic()) {
1627 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001628 OS << ", ";
1629 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001630 }
1631 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001632 OS << ')';
David Majnemerf7e36092016-06-23 00:15:04 +00001633 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
Alexander Kornienko4f355322015-11-09 16:45:17 +00001634 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1635 // enumerator is declared in the scope that immediately contains
1636 // the enum-specifier. Each scoped enumerator is declared in the
1637 // scope of the enumeration.
Paul Robinsonf1838482017-12-21 21:47:22 +00001638 // For the case of unscoped enumerator, do not include in the qualified
Paul Robinsond1c3dd82017-12-26 18:01:19 +00001639 // name any information about its enum enclosing scope, as its visibility
Paul Robinsonf1838482017-12-21 21:47:22 +00001640 // is global.
1641 if (ED->isScoped())
Alexander Kornienko4f355322015-11-09 16:45:17 +00001642 OS << *ED;
1643 else
1644 continue;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001645 } else {
David Majnemerf7e36092016-06-23 00:15:04 +00001646 OS << *cast<NamedDecl>(DC);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001647 }
1648 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001649 }
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001650}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001651
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001652void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1653 const PrintingPolicy &Policy,
1654 bool Qualified) const {
1655 if (Qualified)
1656 printQualifiedName(OS, Policy);
1657 else
1658 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001659}
1660
Richard Smithe8292b12015-02-10 03:28:10 +00001661template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1662 return true;
1663}
1664static bool isRedeclarableImpl(...) { return false; }
1665static bool isRedeclarable(Decl::Kind K) {
1666 switch (K) {
1667#define DECL(Type, Base) \
1668 case Decl::Type: \
1669 return isRedeclarableImpl((Type##Decl *)nullptr);
1670#define ABSTRACT_DECL(DECL)
1671#include "clang/AST/DeclNodes.inc"
1672 }
1673 llvm_unreachable("unknown decl kind");
1674}
1675
1676bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001677 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1678
Richard Smithfe620d22015-03-05 23:24:12 +00001679 // Never replace one imported declaration with another; we need both results
1680 // when re-exporting.
1681 if (OldD->isFromASTFile() && isFromASTFile())
1682 return false;
1683
Richard Smith5cd86f82015-11-03 03:13:11 +00001684 // A kind mismatch implies that the declaration is not replaced.
1685 if (OldD->getKind() != getKind())
Richard Smithe8292b12015-02-10 03:28:10 +00001686 return false;
1687
Richard Smith5cd86f82015-11-03 03:13:11 +00001688 // For method declarations, we never replace. (Why?)
1689 if (isa<ObjCMethodDecl>(this))
1690 return false;
1691
1692 // For parameters, pick the newer one. This is either an error or (in
1693 // Objective-C) permitted as an extension.
1694 if (isa<ParmVarDecl>(this))
1695 return true;
1696
Richard Smithe8292b12015-02-10 03:28:10 +00001697 // Inline namespaces can give us two declarations with the same
1698 // name and kind in the same scope but different contexts; we should
1699 // keep both declarations in this case.
1700 if (!this->getDeclContext()->getRedeclContext()->Equals(
1701 OldD->getDeclContext()->getRedeclContext()))
1702 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001703
Richard Smith5cd86f82015-11-03 03:13:11 +00001704 // Using declarations can be replaced if they import the same name from the
1705 // same context.
Richard Smithe8292b12015-02-10 03:28:10 +00001706 if (auto *UD = dyn_cast<UsingDecl>(this)) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001707 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001708 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001709 Context.getCanonicalNestedNameSpecifier(
Richard Smithe8292b12015-02-10 03:28:10 +00001710 cast<UsingDecl>(OldD)->getQualifier());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001711 }
Richard Smithe8292b12015-02-10 03:28:10 +00001712 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001713 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001714 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001715 Context.getCanonicalNestedNameSpecifier(
1716 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1717 }
1718
Richard Smith5cd86f82015-11-03 03:13:11 +00001719 if (isRedeclarable(getKind())) {
1720 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1721 return false;
1722
1723 if (IsKnownNewer)
1724 return true;
1725
Richard Smithe8292b12015-02-10 03:28:10 +00001726 // Check whether this is actually newer than OldD. We want to keep the
1727 // newer declaration. This loop will usually only iterate once, because
1728 // OldD is usually the previous declaration.
1729 for (auto D : redecls()) {
1730 if (D == OldD)
1731 break;
1732
1733 // If we reach the canonical declaration, then OldD is not actually older
1734 // than this one.
1735 //
1736 // FIXME: In this case, we should not add this decl to the lookup table.
1737 if (D->isCanonicalDecl())
1738 return false;
1739 }
Richard Smith5cd86f82015-11-03 03:13:11 +00001740
1741 // It's a newer declaration of the same kind of declaration in the same
1742 // scope: we want this decl instead of the existing one.
1743 return true;
Richard Smithe8292b12015-02-10 03:28:10 +00001744 }
1745
Richard Smith5cd86f82015-11-03 03:13:11 +00001746 // In all other cases, we need to keep both declarations in case they have
1747 // different visibility. Any attempt to use the name will result in an
1748 // ambiguity if more than one is visible.
1749 return false;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001750}
1751
Douglas Gregoreddf4332009-02-24 20:03:32 +00001752bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001753 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001754}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001755
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001756NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001757 NamedDecl *ND = this;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001758 while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001759 ND = UD->getTargetDecl();
1760
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001761 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001762 return AD->getClassInterface();
1763
Richard Smithf2005d32015-12-29 23:34:32 +00001764 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1765 return AD->getNamespace();
1766
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001767 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001768}
1769
John McCalla8ae2222010-04-06 21:38:20 +00001770bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001771 if (!isCXXClassMember())
1772 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001773
John McCalla8ae2222010-04-06 21:38:20 +00001774 const NamedDecl *D = this;
1775 if (isa<UsingShadowDecl>(D))
1776 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1777
John McCall5e77d762013-04-16 07:28:30 +00001778 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001779 return true;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001780 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
Alp Tokera2794f92014-01-22 07:29:52 +00001781 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001782 return false;
1783}
1784
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001785//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001786// DeclaratorDecl Implementation
1787//===----------------------------------------------------------------------===//
1788
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001789template <typename DeclT>
1790static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1791 if (decl->getNumTemplateParameterLists() > 0)
1792 return decl->getTemplateParameterList(0)->getTemplateLoc();
1793 else
1794 return decl->getInnerLocStart();
1795}
1796
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001797SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001798 TypeSourceInfo *TSI = getTypeSourceInfo();
1799 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001800 return SourceLocation();
1801}
1802
Mark de Weverf022a5a2020-01-01 17:23:19 +01001803SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const {
1804 TypeSourceInfo *TSI = getTypeSourceInfo();
1805 if (TSI) return TSI->getTypeLoc().getEndLoc();
1806 return SourceLocation();
1807}
1808
Douglas Gregor14454802011-02-25 02:25:35 +00001809void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1810 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001811 // Make sure the extended decl info is allocated.
1812 if (!hasExtInfo()) {
1813 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001814 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
John McCall3e11ebe2010-03-15 10:12:16 +00001815 // Allocate external info struct.
1816 DeclInfo = new (getASTContext()) ExtInfo;
1817 // Restore savedTInfo into (extended) decl info.
1818 getExtInfo()->TInfo = savedTInfo;
1819 }
1820 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001821 getExtInfo()->QualifierLoc = QualifierLoc;
Saar Razb65b1f32020-01-09 15:07:51 +02001822 } else if (hasExtInfo()) {
John McCall3e11ebe2010-03-15 10:12:16 +00001823 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
Saar Razb65b1f32020-01-09 15:07:51 +02001824 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001825 }
1826}
1827
Saar Razb65b1f32020-01-09 15:07:51 +02001828void DeclaratorDecl::setTrailingRequiresClause(Expr *TrailingRequiresClause) {
1829 assert(TrailingRequiresClause);
1830 // Make sure the extended decl info is allocated.
1831 if (!hasExtInfo()) {
1832 // Save (non-extended) type source info pointer.
1833 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1834 // Allocate external info struct.
1835 DeclInfo = new (getASTContext()) ExtInfo;
1836 // Restore savedTInfo into (extended) decl info.
1837 getExtInfo()->TInfo = savedTInfo;
1838 }
1839 // Set requires clause info.
1840 getExtInfo()->TrailingRequiresClause = TrailingRequiresClause;
1841}
1842
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001843void DeclaratorDecl::setTemplateParameterListsInfo(
1844 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1845 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00001846 // Make sure the extended decl info is allocated.
1847 if (!hasExtInfo()) {
1848 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001849 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
Abramo Bagnara60804e12011-03-18 15:16:37 +00001850 // Allocate external info struct.
1851 DeclInfo = new (getASTContext()) ExtInfo;
1852 // Restore savedTInfo into (extended) decl info.
1853 getExtInfo()->TInfo = savedTInfo;
1854 }
1855 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001856 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00001857}
1858
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001859SourceLocation DeclaratorDecl::getOuterLocStart() const {
1860 return getTemplateOrInnerLocStart(this);
1861}
1862
Abramo Bagnaraea947882011-03-08 16:41:52 +00001863// Helper function: returns true if QT is or contains a type
1864// having a postfix component.
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001865static bool typeIsPostfix(QualType QT) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00001866 while (true) {
1867 const Type* T = QT.getTypePtr();
1868 switch (T->getTypeClass()) {
1869 default:
1870 return false;
1871 case Type::Pointer:
1872 QT = cast<PointerType>(T)->getPointeeType();
1873 break;
1874 case Type::BlockPointer:
1875 QT = cast<BlockPointerType>(T)->getPointeeType();
1876 break;
1877 case Type::MemberPointer:
1878 QT = cast<MemberPointerType>(T)->getPointeeType();
1879 break;
1880 case Type::LValueReference:
1881 case Type::RValueReference:
1882 QT = cast<ReferenceType>(T)->getPointeeType();
1883 break;
1884 case Type::PackExpansion:
1885 QT = cast<PackExpansionType>(T)->getPattern();
1886 break;
1887 case Type::Paren:
1888 case Type::ConstantArray:
1889 case Type::DependentSizedArray:
1890 case Type::IncompleteArray:
1891 case Type::VariableArray:
1892 case Type::FunctionProto:
1893 case Type::FunctionNoProto:
1894 return true;
1895 }
1896 }
1897}
1898
Abramo Bagnaraea947882011-03-08 16:41:52 +00001899SourceRange DeclaratorDecl::getSourceRange() const {
1900 SourceLocation RangeEnd = getLocation();
1901 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001902 // If the declaration has no name or the type extends past the name take the
1903 // end location of the type.
1904 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001905 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1906 }
1907 return SourceRange(getOuterLocStart(), RangeEnd);
1908}
1909
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001910void QualifierInfo::setTemplateParameterListsInfo(
1911 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001912 // Free previous template parameters (if any).
1913 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001914 Context.Deallocate(TemplParamLists);
Craig Topper36250ad2014-05-12 05:36:57 +00001915 TemplParamLists = nullptr;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001916 NumTemplParamLists = 0;
1917 }
1918 // Set info on matched template parameter lists (if any).
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001919 if (!TPLists.empty()) {
1920 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1921 NumTemplParamLists = TPLists.size();
1922 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001923 }
1924}
1925
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001926//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001927// VarDecl Implementation
1928//===----------------------------------------------------------------------===//
1929
Sebastian Redl833ef452010-01-26 22:01:41 +00001930const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1931 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001932 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001933 case SC_Auto: return "auto";
1934 case SC_Extern: return "extern";
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001935 case SC_PrivateExtern: return "__private_extern__";
1936 case SC_Register: return "register";
1937 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001938 }
1939
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001940 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001941}
1942
Richard Smith053f6c62014-05-16 23:01:30 +00001943VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1944 SourceLocation StartLoc, SourceLocation IdLoc,
1945 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1946 StorageClass SC)
1947 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001948 redeclarable_base(C) {
Benjamin Kramera939c232014-03-15 18:54:13 +00001949 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1950 "VarDeclBitfields too large!");
1951 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1952 "ParmVarDeclBitfields too large!");
David Majnemerfa7bc782015-05-19 00:57:16 +00001953 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1954 "NonParmVarDeclBitfields too large!");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001955 AllBits = 0;
1956 VarDeclBits.SClass = SC;
1957 // Everything else is implicitly initialized to false.
1958}
1959
Abramo Bagnaradff19302011-03-08 08:55:46 +00001960VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1961 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001962 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001963 StorageClass S) {
Richard Smith053f6c62014-05-16 23:01:30 +00001964 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001965}
1966
Douglas Gregor72172e92012-01-05 21:55:30 +00001967VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00001968 return new (C, ID)
1969 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1970 QualType(), nullptr, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001971}
1972
Douglas Gregorbf62d642010-12-06 18:36:25 +00001973void VarDecl::setStorageClass(StorageClass SC) {
1974 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001975 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001976}
1977
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001978VarDecl::TLSKind VarDecl::getTLSKind() const {
1979 switch (VarDeclBits.TSCSpec) {
1980 case TSCS_unspecified:
Samuel Antaof8b50122015-07-13 22:54:53 +00001981 if (!hasAttr<ThreadAttr>() &&
1982 !(getASTContext().getLangOpts().OpenMPUseTLS &&
1983 getASTContext().getTargetInfo().isTLSSupported() &&
1984 hasAttr<OMPThreadPrivateDeclAttr>()))
David Majnemer1b5baff2015-05-14 05:19:23 +00001985 return TLS_None;
Samuel Antaof8b50122015-07-13 22:54:53 +00001986 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1987 LangOptions::MSVC2015)) ||
1988 hasAttr<OMPThreadPrivateDeclAttr>())
David Majnemer1b5baff2015-05-14 05:19:23 +00001989 ? TLS_Dynamic
1990 : TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001991 case TSCS___thread: // Fall through.
1992 case TSCS__Thread_local:
Samuel Antaof8b50122015-07-13 22:54:53 +00001993 return TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001994 case TSCS_thread_local:
1995 return TLS_Dynamic;
1996 }
1997 llvm_unreachable("Unknown thread storage class specifier!");
1998}
1999
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002000SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00002001 if (const Expr *Init = getInit()) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002002 SourceLocation InitEnd = Init->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002003 // If Init is implicit, ignore its source range and fallback on
Nico Weberbbe13942013-01-22 17:00:09 +00002004 // DeclaratorDecl::getSourceRange() to handle postfix elements.
2005 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00002006 return SourceRange(getOuterLocStart(), InitEnd);
2007 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00002008 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002009}
2010
Rafael Espindola88510672013-01-04 21:18:45 +00002011template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00002012static LanguageLinkage getDeclLanguageLinkage(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00002013 // C++ [dcl.link]p1: All function types, function names with external linkage,
2014 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00002015 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00002016 return NoLanguageLinkage;
2017
2018 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00002019 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00002020 ASTContext &Context = D.getASTContext();
2021 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00002022 return CLanguageLinkage;
2023
Rafael Espindola5bda63f2013-02-14 01:47:04 +00002024 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
2025 // language linkage of the names of class members and the function type of
2026 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00002027 const DeclContext *DC = D.getDeclContext();
2028 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002029 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00002030
2031 // If the first decl is in an extern "C" context, any other redeclaration
2032 // will have C language linkage. If the first one is not in an extern "C"
2033 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00002034 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00002035 return CLanguageLinkage;
2036 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00002037}
2038
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002039template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00002040static bool isDeclExternC(const T &D) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002041 // Since the context is ignored for class members, they can only have C++
2042 // language linkage or no language linkage.
2043 const DeclContext *DC = D.getDeclContext();
2044 if (DC->isRecord()) {
2045 assert(D.getASTContext().getLangOpts().CPlusPlus);
2046 return false;
2047 }
2048
2049 return D.getLanguageLinkage() == CLanguageLinkage;
2050}
2051
Rafael Espindolaf4187652013-02-14 01:18:37 +00002052LanguageLinkage VarDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00002053 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002054}
2055
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002056bool VarDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00002057 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002058}
2059
Rafael Espindola593537a2013-05-05 20:15:21 +00002060bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002061 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002062}
2063
2064bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002065 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002066}
2067
Rafael Espindola8db352d2013-10-17 15:37:26 +00002068VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002069
Nico Weber7f5015a2015-04-15 21:53:00 +00002070VarDecl::DefinitionKind
2071VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
Richard Smitha22d9a52017-12-02 00:55:48 +00002072 if (isThisDeclarationADemotedDefinition())
2073 return DeclarationOnly;
2074
Sebastian Redl35351a92010-01-31 22:27:38 +00002075 // C++ [basic.def]p2:
2076 // A declaration is a definition unless [...] it contains the 'extern'
2077 // specifier or a linkage-specification and neither an initializer [...],
Richard Smith62f19e72016-06-25 00:15:56 +00002078 // it declares a non-inline static data member in a class declaration [...],
2079 // it declares a static data member outside a class definition and the variable
2080 // was defined within the class with the constexpr specifier [...],
Richard Smith8809a0c2013-09-27 20:14:12 +00002081 // C++1y [temp.expl.spec]p15:
2082 // An explicit specialization of a static data member or an explicit
2083 // specialization of a static data member template is a definition if the
2084 // declaration includes an initializer; otherwise, it is a declaration.
2085 //
2086 // FIXME: How do you declare (but not define) a partial specialization of
2087 // a static data member template outside the containing class?
Sebastian Redl35351a92010-01-31 22:27:38 +00002088 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002089 if (isOutOfLine() &&
Richard Smith62f19e72016-06-25 00:15:56 +00002090 !(getCanonicalDecl()->isInline() &&
2091 getCanonicalDecl()->isConstexpr()) &&
Richard Smith8809a0c2013-09-27 20:14:12 +00002092 (hasInit() ||
2093 // If the first declaration is out-of-line, this may be an
2094 // instantiation of an out-of-line partial specialization of a variable
2095 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00002096 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00002097 ? getTemplateSpecializationKind() == TSK_Undeclared
2098 : getTemplateSpecializationKind() !=
2099 TSK_ExplicitSpecialization) ||
2100 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00002101 return Definition;
Richard Smith62f19e72016-06-25 00:15:56 +00002102 else if (!isOutOfLine() && isInline())
2103 return Definition;
Sebastian Redl35351a92010-01-31 22:27:38 +00002104 else
2105 return DeclarationOnly;
2106 }
2107 // C99 6.7p5:
2108 // A definition of an identifier is a declaration for that identifier that
2109 // [...] causes storage to be reserved for that object.
2110 // Note: that applies for all non-file-scope objects.
2111 // C99 6.9.2p1:
2112 // If the declaration of an identifier for an object has file scope and an
2113 // initializer, the declaration is an external definition for the identifier
2114 if (hasInit())
2115 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00002116
Dmitry Polukhin85eda122016-04-11 07:48:59 +00002117 if (hasDefiningAttr())
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002118 return Definition;
2119
David Majnemerdd0bed12015-05-14 05:19:20 +00002120 if (const auto *SAA = getAttr<SelectAnyAttr>())
2121 if (!SAA->isInherited())
2122 return Definition;
2123
Richard Smith8809a0c2013-09-27 20:14:12 +00002124 // A variable template specialization (other than a static data member
2125 // template or an explicit specialization) is a declaration until we
2126 // instantiate its initializer.
Richard Smith435e6472017-12-02 02:48:42 +00002127 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2128 if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2129 !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2130 !VTSD->IsCompleteDefinition)
2131 return DeclarationOnly;
2132 }
Richard Smith8809a0c2013-09-27 20:14:12 +00002133
Nico Weber608e7682015-04-15 23:04:24 +00002134 if (hasExternalStorage())
Sebastian Redl35351a92010-01-31 22:27:38 +00002135 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00002136
Rafael Espindolabff59562013-04-25 12:11:36 +00002137 // [dcl.link] p7:
2138 // A declaration directly contained in a linkage-specification is treated
2139 // as if it contains the extern specifier for the purpose of determining
2140 // the linkage of the declared name and whether it is a definition.
Nico Weber608e7682015-04-15 23:04:24 +00002141 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00002142 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00002143
Sebastian Redl35351a92010-01-31 22:27:38 +00002144 // C99 6.9.2p2:
2145 // A declaration of an object that has file scope without an initializer,
2146 // and without a storage class specifier or the scs 'static', constitutes
2147 // a tentative definition.
2148 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002149 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00002150 return TentativeDefinition;
2151
2152 // What's left is (in C, block-scope) declarations without initializers or
2153 // external storage. These are definitions.
2154 return Definition;
2155}
2156
Sebastian Redl35351a92010-01-31 22:27:38 +00002157VarDecl *VarDecl::getActingDefinition() {
2158 DefinitionKind Kind = isThisDeclarationADefinition();
2159 if (Kind != TentativeDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00002160 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002161
Craig Topper36250ad2014-05-12 05:36:57 +00002162 VarDecl *LastTentative = nullptr;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002163 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002164 for (auto I : First->redecls()) {
2165 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00002166 if (Kind == Definition)
Craig Topper36250ad2014-05-12 05:36:57 +00002167 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002168 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00002169 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00002170 }
2171 return LastTentative;
2172}
2173
Daniel Dunbar9d355812012-03-09 01:51:51 +00002174VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002175 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002176 for (auto I : First->redecls()) {
2177 if (I->isThisDeclarationADefinition(C) == Definition)
2178 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002179 }
Craig Topper36250ad2014-05-12 05:36:57 +00002180 return nullptr;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002181}
2182
Daniel Dunbar9d355812012-03-09 01:51:51 +00002183VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00002184 DefinitionKind Kind = DeclarationOnly;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002185
Rafael Espindola8db352d2013-10-17 15:37:26 +00002186 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002187 for (auto I : First->redecls()) {
2188 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00002189 if (Kind == Definition)
2190 break;
2191 }
John McCall37bb6c92010-10-29 22:22:43 +00002192
2193 return Kind;
2194}
2195
Sebastian Redl5ca79842010-02-01 20:16:42 +00002196const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002197 for (auto I : redecls()) {
2198 if (auto Expr = I->getInit()) {
2199 D = I;
2200 return Expr;
2201 }
Sebastian Redl833ef452010-01-26 22:01:41 +00002202 }
Craig Topper36250ad2014-05-12 05:36:57 +00002203 return nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002204}
2205
Chandler Carruth813faed2015-12-30 02:51:00 +00002206bool VarDecl::hasInit() const {
2207 if (auto *P = dyn_cast<ParmVarDecl>(this))
2208 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2209 return false;
2210
2211 return !Init.isNull();
2212}
2213
2214Expr *VarDecl::getInit() {
2215 if (!hasInit())
2216 return nullptr;
2217
2218 if (auto *S = Init.dyn_cast<Stmt *>())
2219 return cast<Expr>(S);
2220
2221 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2222}
2223
2224Stmt **VarDecl::getInitAddress() {
2225 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2226 return &ES->Value;
2227
2228 return Init.getAddrOfPtr1();
2229}
2230
Richard Smitha6e8b682019-09-04 20:30:37 +00002231VarDecl *VarDecl::getInitializingDeclaration() {
2232 VarDecl *Def = nullptr;
2233 for (auto I : redecls()) {
2234 if (I->hasInit())
2235 return I;
2236
2237 if (I->isThisDeclarationADefinition()) {
2238 if (isStaticDataMember())
2239 return I;
2240 else
2241 Def = I;
2242 }
2243 }
2244 return Def;
2245}
2246
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002247bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002248 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002249 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00002250
2251 if (!isStaticDataMember())
2252 return false;
2253
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002254 // If this static data member was instantiated from a static data member of
Fangrui Song6907ce22018-07-30 19:24:48 +00002255 // a class template, check whether that static data member was defined
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002256 // out-of-line.
2257 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2258 return VD->isOutOfLine();
Fangrui Song6907ce22018-07-30 19:24:48 +00002259
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002260 return false;
2261}
2262
Douglas Gregord5058122010-02-11 01:19:42 +00002263void VarDecl::setInit(Expr *I) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002264 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
Sebastian Redl833ef452010-01-26 22:01:41 +00002265 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00002266 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00002267 }
2268
2269 Init = I;
2270}
2271
Richard Smith715f7a12019-06-11 17:50:32 +00002272bool VarDecl::mightBeUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002273 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00002274
Richard Smith35ecb362012-03-02 04:14:40 +00002275 if (!Lang.CPlusPlus)
2276 return false;
2277
Richard Smith715f7a12019-06-11 17:50:32 +00002278 // Function parameters are never usable in constant expressions.
2279 if (isa<ParmVarDecl>(this))
2280 return false;
2281
Richard Smith35ecb362012-03-02 04:14:40 +00002282 // In C++11, any variable of reference type can be used in a constant
2283 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002284 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00002285 return true;
2286
2287 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00002288 // not require the variable to be non-volatile, but we consider this to be a
2289 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00002290 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00002291 return false;
2292
2293 // In C++, const, non-volatile variables of integral or enumeration types
2294 // can be used in constant expressions.
2295 if (getType()->isIntegralOrEnumerationType())
2296 return true;
2297
Richard Smith35ecb362012-03-02 04:14:40 +00002298 // Additionally, in C++11, non-volatile constexpr variables can be used in
2299 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002300 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00002301}
2302
Richard Smith715f7a12019-06-11 17:50:32 +00002303bool VarDecl::isUsableInConstantExpressions(ASTContext &Context) const {
2304 // C++2a [expr.const]p3:
2305 // A variable is usable in constant expressions after its initializing
2306 // declaration is encountered...
2307 const VarDecl *DefVD = nullptr;
2308 const Expr *Init = getAnyInitializer(DefVD);
Richard Smith94bc88e2019-06-17 21:46:17 +00002309 if (!Init || Init->isValueDependent() || getType()->isDependentType())
Richard Smith715f7a12019-06-11 17:50:32 +00002310 return false;
2311 // ... if it is a constexpr variable, or it is of reference type or of
2312 // const-qualified integral or enumeration type, ...
2313 if (!DefVD->mightBeUsableInConstantExpressions(Context))
2314 return false;
2315 // ... and its initializer is a constant initializer.
2316 return DefVD->checkInitIsICE();
2317}
2318
Richard Smithd0b4dd62011-12-19 06:19:21 +00002319/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2320/// form, which contains extra information on the evaluated value of the
2321/// initializer.
2322EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002323 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002324 if (!Eval) {
Manuel Klimeka7328992013-06-03 13:51:33 +00002325 // Note: EvaluatedStmt contains an APValue, which usually holds
2326 // resources not allocated from the ASTContext. We need to do some
2327 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2328 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002329 Eval = new (getASTContext()) EvaluatedStmt;
Chandler Carruth813faed2015-12-30 02:51:00 +00002330 Eval->Value = Init.get<Stmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002331 Init = Eval;
2332 }
2333 return Eval;
2334}
2335
Richard Smithdafff942012-01-14 04:30:29 +00002336APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002337 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00002338 return evaluateValue(Notes);
2339}
2340
2341APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002342 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002343 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2344
2345 // We only produce notes indicating why an initializer is non-constant the
2346 // first time it is evaluated. FIXME: The notes won't always be emitted the
2347 // first time we try evaluation, so might not be produced at all.
2348 if (Eval->WasEvaluated)
Richard Smithe637cbe2019-05-21 23:15:18 +00002349 return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002350
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002351 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002352 assert(!Init->isValueDependent());
2353
2354 if (Eval->IsEvaluating) {
2355 // FIXME: Produce a diagnostic for self-initialization.
2356 Eval->CheckedICE = true;
2357 Eval->IsICE = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002358 return nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002359 }
2360
2361 Eval->IsEvaluating = true;
2362
2363 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2364 this, Notes);
2365
Manuel Klimeka7328992013-06-03 13:51:33 +00002366 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2367 // or that it's empty (so that there's nothing to clean up) if evaluation
2368 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002369 if (!Result)
2370 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00002371 else if (Eval->Evaluated.needsCleanup())
George Burgess IVb61bfbd2017-02-14 05:37:36 +00002372 getASTContext().addDestruction(&Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002373
2374 Eval->IsEvaluating = false;
2375 Eval->WasEvaluated = true;
2376
2377 // In C++11, we have determined whether the initializer was a constant
2378 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002379 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002380 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00002381 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002382 }
2383
Craig Topper36250ad2014-05-12 05:36:57 +00002384 return Result ? &Eval->Evaluated : nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002385}
2386
Chandler Carruth813faed2015-12-30 02:51:00 +00002387APValue *VarDecl::getEvaluatedValue() const {
2388 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2389 if (Eval->WasEvaluated)
2390 return &Eval->Evaluated;
2391
2392 return nullptr;
2393}
2394
2395bool VarDecl::isInitKnownICE() const {
2396 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2397 return Eval->CheckedICE;
2398
2399 return false;
2400}
2401
2402bool VarDecl::isInitICE() const {
2403 assert(isInitKnownICE() &&
2404 "Check whether we already know that the initializer is an ICE");
2405 return Init.get<EvaluatedStmt *>()->IsICE;
2406}
2407
Richard Smithd0b4dd62011-12-19 06:19:21 +00002408bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00002409 // Initializers of weak variables are never ICEs.
2410 if (isWeak())
2411 return false;
2412
Richard Smithd0b4dd62011-12-19 06:19:21 +00002413 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2414 if (Eval->CheckedICE)
2415 // We have already checked whether this subexpression is an
2416 // integral constant expression.
2417 return Eval->IsICE;
2418
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002419 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002420 assert(!Init->isValueDependent());
2421
2422 // In C++11, evaluate the initializer to check whether it's a constant
2423 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002424 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002425 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002426 evaluateValue(Notes);
2427 return Eval->IsICE;
2428 }
2429
2430 // It's an ICE whether or not the definition we found is
2431 // out-of-line. See DR 721 and the discussion in Clang PR
2432 // 6206 for details.
2433
2434 if (Eval->CheckingICE)
2435 return false;
2436 Eval->CheckingICE = true;
2437
2438 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2439 Eval->CheckingICE = false;
2440 Eval->CheckedICE = true;
2441 return Eval->IsICE;
2442}
2443
Richard Smithb2997f52019-05-21 20:10:50 +00002444bool VarDecl::isParameterPack() const {
2445 return isa<PackExpansionType>(getType());
2446}
2447
Richard Smith2195ec92017-04-21 01:15:13 +00002448template<typename DeclT>
2449static DeclT *getDefinitionOrSelf(DeclT *D) {
2450 assert(D);
2451 if (auto *Def = D->getDefinition())
2452 return Def;
2453 return D;
2454}
2455
Akira Hatanaka8e57b072018-10-01 21:51:28 +00002456bool VarDecl::isEscapingByref() const {
2457 return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
2458}
2459
2460bool VarDecl::isNonEscapingByref() const {
2461 return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
2462}
2463
Richard Smithedbc6e92016-10-14 21:41:24 +00002464VarDecl *VarDecl::getTemplateInstantiationPattern() const {
Richard Smitha6b41d72019-05-03 23:51:38 +00002465 const VarDecl *VD = this;
Richard Smithedbc6e92016-10-14 21:41:24 +00002466
Richard Smitha6b41d72019-05-03 23:51:38 +00002467 // If this is an instantiated member, walk back to the template from which
2468 // it was instantiated.
2469 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) {
Richard Smithedbc6e92016-10-14 21:41:24 +00002470 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
Richard Smitha6b41d72019-05-03 23:51:38 +00002471 VD = VD->getInstantiatedFromStaticDataMember();
Richard Smithedbc6e92016-10-14 21:41:24 +00002472 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2473 VD = NewVD;
Richard Smithedbc6e92016-10-14 21:41:24 +00002474 }
2475 }
2476
Richard Smitha6b41d72019-05-03 23:51:38 +00002477 // If it's an instantiated variable template specialization, find the
2478 // template or partial specialization from which it was instantiated.
2479 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2480 if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
2481 auto From = VDTemplSpec->getInstantiatedFrom();
2482 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2483 while (!VTD->isMemberSpecialization()) {
2484 auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
2485 if (!NewVTD)
2486 break;
2487 VTD = NewVTD;
2488 }
2489 return getDefinitionOrSelf(VTD->getTemplatedDecl());
2490 }
2491 if (auto *VTPSD =
2492 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2493 while (!VTPSD->isMemberSpecialization()) {
2494 auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
2495 if (!NewVTPSD)
2496 break;
2497 VTPSD = NewVTPSD;
2498 }
2499 return getDefinitionOrSelf<VarDecl>(VTPSD);
2500 }
2501 }
2502 }
2503
2504 // If this is the pattern of a variable template, find where it was
2505 // instantiated from. FIXME: Is this necessary?
2506 if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {
2507 while (!VarTemplate->isMemberSpecialization()) {
2508 auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
2509 if (!NewVT)
Richard Smithedbc6e92016-10-14 21:41:24 +00002510 break;
Richard Smitha6b41d72019-05-03 23:51:38 +00002511 VarTemplate = NewVT;
Richard Smithedbc6e92016-10-14 21:41:24 +00002512 }
2513
Richard Smith2195ec92017-04-21 01:15:13 +00002514 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
Richard Smithedbc6e92016-10-14 21:41:24 +00002515 }
Richard Smitha6b41d72019-05-03 23:51:38 +00002516
2517 if (VD == this)
2518 return nullptr;
2519 return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
Richard Smithedbc6e92016-10-14 21:41:24 +00002520}
2521
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002522VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002523 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002524 return cast<VarDecl>(MSI->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002525
2526 return nullptr;
Douglas Gregor86d142a2009-10-08 07:24:58 +00002527}
2528
Douglas Gregor3c74d412009-10-14 20:14:33 +00002529TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002530 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002531 return Spec->getSpecializationKind();
2532
Sebastian Redl35351a92010-01-31 22:27:38 +00002533 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002534 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002535
Douglas Gregor86d142a2009-10-08 07:24:58 +00002536 return TSK_Undeclared;
2537}
2538
Richard Smitha6b41d72019-05-03 23:51:38 +00002539TemplateSpecializationKind
2540VarDecl::getTemplateSpecializationKindForInstantiation() const {
2541 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2542 return MSI->getTemplateSpecializationKind();
2543
2544 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2545 return Spec->getSpecializationKind();
2546
2547 return TSK_Undeclared;
2548}
2549
Richard Smith8809a0c2013-09-27 20:14:12 +00002550SourceLocation VarDecl::getPointOfInstantiation() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002551 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Richard Smith8809a0c2013-09-27 20:14:12 +00002552 return Spec->getPointOfInstantiation();
2553
2554 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2555 return MSI->getPointOfInstantiation();
2556
2557 return SourceLocation();
2558}
2559
Larisse Voufo39a1e502013-08-06 01:03:05 +00002560VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2561 return getASTContext().getTemplateOrSpecializationInfo(this)
2562 .dyn_cast<VarTemplateDecl *>();
2563}
2564
2565void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2566 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2567}
2568
Justin Lebar5489f852018-05-17 16:15:07 +00002569bool VarDecl::isKnownToBeDefined() const {
2570 const auto &LangOpts = getASTContext().getLangOpts();
2571 // In CUDA mode without relocatable device code, variables of form 'extern
2572 // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2573 // memory pool. These are never undefined variables, even if they appear
2574 // inside of an anon namespace or static function.
2575 //
2576 // With CUDA relocatable device code enabled, these variables don't get
2577 // special handling; they're treated like regular extern variables.
Yaxun Liu97670892018-10-02 17:48:54 +00002578 if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
Justin Lebar5489f852018-05-17 16:15:07 +00002579 hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
2580 isa<IncompleteArrayType>(getType()))
2581 return true;
2582
2583 return hasDefinition();
2584}
2585
Erik Pilkington5a559e62018-08-21 17:24:06 +00002586bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
2587 return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||
2588 (!Ctx.getLangOpts().RegisterStaticDestructors &&
2589 !hasAttr<AlwaysDestroyAttr>()));
2590}
2591
Richard Smith2b4fa532019-09-29 05:08:46 +00002592QualType::DestructionKind
2593VarDecl::needsDestruction(const ASTContext &Ctx) const {
2594 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2595 if (Eval->HasConstantDestruction)
2596 return QualType::DK_none;
2597
2598 if (isNoDestroy(Ctx))
2599 return QualType::DK_none;
2600
2601 return getType().isDestructedType();
2602}
2603
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002604MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002605 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002606 // FIXME: Remove ?
2607 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2608 return getASTContext().getTemplateOrSpecializationInfo(this)
2609 .dyn_cast<MemberSpecializationInfo *>();
Craig Topper36250ad2014-05-12 05:36:57 +00002610 return nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002611}
2612
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002613void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2614 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002615 assert((isa<VarTemplateSpecializationDecl>(this) ||
2616 getMemberSpecializationInfo()) &&
2617 "not a variable or static data member template specialization");
2618
Larisse Voufo39a1e502013-08-06 01:03:05 +00002619 if (VarTemplateSpecializationDecl *Spec =
2620 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2621 Spec->setSpecializationKind(TSK);
Richard Smitha6b41d72019-05-03 23:51:38 +00002622 if (TSK != TSK_ExplicitSpecialization &&
2623 PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00002624 Spec->getPointOfInstantiation().isInvalid()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002625 Spec->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00002626 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2627 L->InstantiationRequested(this);
2628 }
Richard Smitha6b41d72019-05-03 23:51:38 +00002629 } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002630 MSI->setTemplateSpecializationKind(TSK);
2631 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00002632 MSI->getPointOfInstantiation().isInvalid()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002633 MSI->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00002634 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2635 L->InstantiationRequested(this);
2636 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002637 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002638}
2639
2640void
2641VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2642 TemplateSpecializationKind TSK) {
2643 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2644 "Previous template or instantiation?");
2645 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002646}
2647
Sebastian Redl833ef452010-01-26 22:01:41 +00002648//===----------------------------------------------------------------------===//
2649// ParmVarDecl Implementation
2650//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002651
Sebastian Redl833ef452010-01-26 22:01:41 +00002652ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002653 SourceLocation StartLoc,
2654 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002655 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002656 StorageClass S, Expr *DefArg) {
Richard Smith053f6c62014-05-16 23:01:30 +00002657 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smithf7981722013-11-22 09:01:48 +00002658 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002659}
2660
Reid Kleckner8a365022013-06-24 17:51:48 +00002661QualType ParmVarDecl::getOriginalType() const {
2662 TypeSourceInfo *TSI = getTypeSourceInfo();
2663 QualType T = TSI ? TSI->getType() : getType();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002664 if (const auto *DT = dyn_cast<DecayedType>(T))
Reid Kleckner8a365022013-06-24 17:51:48 +00002665 return DT->getOriginalType();
2666 return T;
2667}
2668
Douglas Gregor72172e92012-01-05 21:55:30 +00002669ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00002670 return new (C, ID)
2671 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2672 nullptr, QualType(), nullptr, SC_None, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00002673}
2674
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002675SourceRange ParmVarDecl::getSourceRange() const {
2676 if (!hasInheritedDefaultArg()) {
2677 SourceRange ArgRange = getDefaultArgRange();
2678 if (ArgRange.isValid())
2679 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2680 }
2681
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002682 // DeclaratorDecl considers the range of postfix types as overlapping with the
2683 // declaration name, but this is not the case with parameters in ObjC methods.
2684 if (isa<ObjCMethodDecl>(getDeclContext()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002685 return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002686
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002687 return DeclaratorDecl::getSourceRange();
2688}
2689
Sebastian Redl833ef452010-01-26 22:01:41 +00002690Expr *ParmVarDecl::getDefaultArg() {
2691 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2692 assert(!hasUninstantiatedDefaultArg() &&
2693 "Default argument is not yet instantiated!");
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002694
Sebastian Redl833ef452010-01-26 22:01:41 +00002695 Expr *Arg = getInit();
Bill Wendling7c44da22018-10-31 03:48:47 +00002696 if (auto *E = dyn_cast_or_null<FullExpr>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002697 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002698
Sebastian Redl833ef452010-01-26 22:01:41 +00002699 return Arg;
2700}
2701
Chandler Carruth813faed2015-12-30 02:51:00 +00002702void ParmVarDecl::setDefaultArg(Expr *defarg) {
2703 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2704 Init = defarg;
2705}
Sebastian Redl833ef452010-01-26 22:01:41 +00002706
Chandler Carruth813faed2015-12-30 02:51:00 +00002707SourceRange ParmVarDecl::getDefaultArgRange() const {
2708 switch (ParmVarDeclBits.DefaultArgKind) {
2709 case DAK_None:
2710 case DAK_Unparsed:
2711 // Nothing we can do here.
2712 return SourceRange();
2713
2714 case DAK_Uninstantiated:
Sebastian Redl833ef452010-01-26 22:01:41 +00002715 return getUninstantiatedDefaultArg()->getSourceRange();
2716
Chandler Carruth813faed2015-12-30 02:51:00 +00002717 case DAK_Normal:
2718 if (const Expr *E = getInit())
2719 return E->getSourceRange();
2720
2721 // Missing an actual expression, may be invalid.
2722 return SourceRange();
2723 }
2724 llvm_unreachable("Invalid default argument kind.");
2725}
2726
2727void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2728 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2729 Init = arg;
2730}
2731
2732Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2733 assert(hasUninstantiatedDefaultArg() &&
2734 "Wrong kind of initialization expression!");
2735 return cast_or_null<Expr>(Init.get<Stmt *>());
2736}
2737
2738bool ParmVarDecl::hasDefaultArg() const {
2739 // FIXME: We should just return false for DAK_None here once callers are
2740 // prepared for the case that we encountered an invalid default argument and
2741 // were unable to even build an invalid expression.
2742 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2743 !Init.isNull();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002744}
2745
Ted Kremenek540017e2011-10-06 05:00:56 +00002746void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2747 getASTContext().setParameterIndex(this, parameterIndex);
2748 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2749}
2750
2751unsigned ParmVarDecl::getParameterIndexLarge() const {
2752 return getASTContext().getParameterIndex(this);
2753}
2754
Nuno Lopes394ec982008-12-17 23:39:55 +00002755//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002756// FunctionDecl Implementation
2757//===----------------------------------------------------------------------===//
2758
Erich Keane9c665062018-08-01 21:02:40 +00002759FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,
2760 SourceLocation StartLoc,
2761 const DeclarationNameInfo &NameInfo, QualType T,
2762 TypeSourceInfo *TInfo, StorageClass S,
Gauthier Harnisch796ed032019-06-14 08:56:20 +00002763 bool isInlineSpecified,
Saar Razb65b1f32020-01-09 15:07:51 +02002764 ConstexprSpecKind ConstexprKind,
2765 Expr *TrailingRequiresClause)
Erich Keane9c665062018-08-01 21:02:40 +00002766 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
2767 StartLoc),
Richard Smith848934c2019-12-05 13:37:35 -08002768 DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),
Erich Keane9c665062018-08-01 21:02:40 +00002769 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002770 assert(T.isNull() || T->isFunctionType());
Bruno Ricci0b639da2018-12-03 13:04:10 +00002771 FunctionDeclBits.SClass = S;
2772 FunctionDeclBits.IsInline = isInlineSpecified;
2773 FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
Bruno Ricci0b639da2018-12-03 13:04:10 +00002774 FunctionDeclBits.IsVirtualAsWritten = false;
2775 FunctionDeclBits.IsPure = false;
2776 FunctionDeclBits.HasInheritedPrototype = false;
2777 FunctionDeclBits.HasWrittenPrototype = true;
2778 FunctionDeclBits.IsDeleted = false;
2779 FunctionDeclBits.IsTrivial = false;
2780 FunctionDeclBits.IsTrivialForCall = false;
2781 FunctionDeclBits.IsDefaulted = false;
2782 FunctionDeclBits.IsExplicitlyDefaulted = false;
Richard Smith848934c2019-12-05 13:37:35 -08002783 FunctionDeclBits.HasDefaultedFunctionInfo = false;
Bruno Ricci0b639da2018-12-03 13:04:10 +00002784 FunctionDeclBits.HasImplicitReturnZero = false;
2785 FunctionDeclBits.IsLateTemplateParsed = false;
Gauthier Harnisch796ed032019-06-14 08:56:20 +00002786 FunctionDeclBits.ConstexprKind = ConstexprKind;
Bruno Ricci0b639da2018-12-03 13:04:10 +00002787 FunctionDeclBits.InstantiationIsPending = false;
2788 FunctionDeclBits.UsesSEHTry = false;
Melanie Blower7f9b5132019-12-04 12:23:46 -08002789 FunctionDeclBits.UsesFPIntrin = false;
Bruno Ricci0b639da2018-12-03 13:04:10 +00002790 FunctionDeclBits.HasSkippedBody = false;
2791 FunctionDeclBits.WillHaveBody = false;
2792 FunctionDeclBits.IsMultiVersion = false;
2793 FunctionDeclBits.IsCopyDeductionCandidate = false;
2794 FunctionDeclBits.HasODRHash = false;
Saar Razb65b1f32020-01-09 15:07:51 +02002795 if (TrailingRequiresClause)
2796 setTrailingRequiresClause(TrailingRequiresClause);
Erich Keane9c665062018-08-01 21:02:40 +00002797}
2798
Benjamin Kramer9170e912013-02-22 15:46:01 +00002799void FunctionDecl::getNameForDiagnostic(
2800 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2801 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002802 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2803 if (TemplateArgs)
Serge Pavlov03e672c2017-11-28 16:14:14 +00002804 printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002805}
2806
Ted Kremenek186a0742010-04-29 16:49:01 +00002807bool FunctionDecl::isVariadic() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002808 if (const auto *FT = getType()->getAs<FunctionProtoType>())
Ted Kremenek186a0742010-04-29 16:49:01 +00002809 return FT->isVariadic();
2810 return false;
2811}
2812
Richard Smith848934c2019-12-05 13:37:35 -08002813FunctionDecl::DefaultedFunctionInfo *
2814FunctionDecl::DefaultedFunctionInfo::Create(ASTContext &Context,
2815 ArrayRef<DeclAccessPair> Lookups) {
2816 DefaultedFunctionInfo *Info = new (Context.Allocate(
2817 totalSizeToAlloc<DeclAccessPair>(Lookups.size()),
2818 std::max(alignof(DefaultedFunctionInfo), alignof(DeclAccessPair))))
2819 DefaultedFunctionInfo;
2820 Info->NumLookups = Lookups.size();
2821 std::uninitialized_copy(Lookups.begin(), Lookups.end(),
2822 Info->getTrailingObjects<DeclAccessPair>());
2823 return Info;
2824}
2825
2826void FunctionDecl::setDefaultedFunctionInfo(DefaultedFunctionInfo *Info) {
2827 assert(!FunctionDeclBits.HasDefaultedFunctionInfo && "already have this");
2828 assert(!Body && "can't replace function body with defaulted function info");
2829
2830 FunctionDeclBits.HasDefaultedFunctionInfo = true;
2831 DefaultedInfo = Info;
2832}
2833
2834FunctionDecl::DefaultedFunctionInfo *
2835FunctionDecl::getDefaultedFunctionInfo() const {
2836 return FunctionDeclBits.HasDefaultedFunctionInfo ? DefaultedInfo : nullptr;
2837}
2838
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002839bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002840 for (auto I : redecls()) {
Serge Pavlov9a618e12017-02-15 12:30:35 +00002841 if (I->doesThisDeclarationHaveABody()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002842 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002843 return true;
2844 }
2845 }
2846
2847 return false;
2848}
2849
Richard Smith848934c2019-12-05 13:37:35 -08002850bool FunctionDecl::hasTrivialBody() const {
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002851 Stmt *S = getBody();
2852 if (!S) {
2853 // Since we don't have a body for this function, we don't know if it's
2854 // trivial or not.
2855 return false;
2856 }
2857
2858 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2859 return true;
2860 return false;
2861}
2862
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002863bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002864 for (auto I : redecls()) {
Serge Pavlov10673c92017-06-04 12:53:12 +00002865 if (I->isThisDeclarationADefinition()) {
2866 Definition = I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002867 return true;
2868 }
2869 }
2870
2871 return false;
2872}
2873
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002874Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002875 if (!hasBody(Definition))
Craig Topper36250ad2014-05-12 05:36:57 +00002876 return nullptr;
Rafael Espindola44503012013-10-19 01:37:17 +00002877
Richard Smith848934c2019-12-05 13:37:35 -08002878 assert(!Definition->FunctionDeclBits.HasDefaultedFunctionInfo &&
2879 "definition should not have a body");
Rafael Espindola44503012013-10-19 01:37:17 +00002880 if (Definition->Body)
2881 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002882
Craig Topper36250ad2014-05-12 05:36:57 +00002883 return nullptr;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002884}
2885
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002886void FunctionDecl::setBody(Stmt *B) {
Richard Smith848934c2019-12-05 13:37:35 -08002887 FunctionDeclBits.HasDefaultedFunctionInfo = false;
2888 Body = LazyDeclStmtPtr(B);
Douglas Gregor027ba502010-12-06 17:49:01 +00002889 if (B)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002890 EndRangeLoc = B->getEndLoc();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002891}
2892
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002893void FunctionDecl::setPure(bool P) {
Erich Keane9c665062018-08-01 21:02:40 +00002894 FunctionDeclBits.IsPure = P;
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002895 if (P)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002896 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002897 Parent->markedVirtualFunctionPure();
2898}
2899
Richard Smith8d0dc312013-07-21 23:12:18 +00002900template<std::size_t Len>
2901static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2902 IdentifierInfo *II = ND->getIdentifier();
2903 return II && II->isStr(Str);
2904}
2905
Douglas Gregor16618f22009-09-12 00:17:51 +00002906bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002907 const TranslationUnitDecl *tunit =
2908 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2909 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002910 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002911 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002912}
2913
David Majnemerc729b0b2013-09-16 22:44:20 +00002914bool FunctionDecl::isMSVCRTEntryPoint() const {
2915 const TranslationUnitDecl *TUnit =
2916 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2917 if (!TUnit)
2918 return false;
2919
2920 // Even though we aren't really targeting MSVCRT if we are freestanding,
2921 // semantic analysis for these functions remains the same.
2922
2923 // MSVCRT entry points only exist on MSVCRT targets.
2924 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2925 return false;
2926
2927 // Nameless functions like constructors cannot be entry points.
2928 if (!getIdentifier())
2929 return false;
2930
2931 return llvm::StringSwitch<bool>(getName())
2932 .Cases("main", // an ANSI console app
2933 "wmain", // a Unicode console App
2934 "WinMain", // an ANSI GUI app
2935 "wWinMain", // a Unicode GUI app
2936 "DllMain", // a DLL
2937 true)
2938 .Default(false);
2939}
2940
John McCall53ffd372011-05-15 17:49:20 +00002941bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2942 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2943 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2944 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2945 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2946 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2947
Richard Smithf6004412014-01-19 23:25:37 +00002948 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2949 return false;
John McCall53ffd372011-05-15 17:49:20 +00002950
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002951 const auto *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002952 if (proto->getNumParams() != 2 || proto->isVariadic())
2953 return false;
John McCall53ffd372011-05-15 17:49:20 +00002954
2955 ASTContext &Context =
2956 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2957 ->getASTContext();
2958
2959 // The result type and first argument type are constant across all
2960 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002961 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002962}
2963
Roman Lebedev3dd5a292020-02-26 01:37:17 +03002964bool FunctionDecl::isReplaceableGlobalAllocationFunction(
2965 Optional<unsigned> *AlignmentParam, bool *IsNothrow) const {
Richard Smith8d0dc312013-07-21 23:12:18 +00002966 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2967 return false;
2968 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2969 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2970 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2971 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2972 return false;
2973
2974 if (isa<CXXRecordDecl>(getDeclContext()))
2975 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002976
2977 // This can only fail for an invalid 'operator new' declaration.
2978 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2979 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002980
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002981 const auto *FPT = getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00002982 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002983 return false;
2984
2985 // If this is a single-parameter function, it must be a replaceable global
2986 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002987 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002988 return true;
2989
Richard Smithb2f0f052016-10-10 18:54:32 +00002990 unsigned Params = 1;
2991 QualType Ty = FPT->getParamType(Params);
Richard Smith1cdec012013-09-29 04:40:38 +00002992 ASTContext &Ctx = getASTContext();
Richard Smithb2f0f052016-10-10 18:54:32 +00002993
2994 auto Consume = [&] {
2995 ++Params;
2996 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
2997 };
2998
2999 // In C++14, the next parameter can be a 'std::size_t' for sized delete.
3000 bool IsSizedDelete = false;
Richard Smithb47c36f2013-11-05 09:12:18 +00003001 if (Ctx.getLangOpts().SizedDeallocation &&
Richard Smithb2f0f052016-10-10 18:54:32 +00003002 (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
3003 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
3004 Ctx.hasSameType(Ty, Ctx.getSizeType())) {
3005 IsSizedDelete = true;
3006 Consume();
3007 }
3008
3009 // In C++17, the next parameter can be a 'std::align_val_t' for aligned
3010 // new/delete.
Akira Hatanakacae83f72017-06-29 18:48:40 +00003011 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
Richard Smithb2f0f052016-10-10 18:54:32 +00003012 Consume();
Roman Lebedev3dd5a292020-02-26 01:37:17 +03003013 if (AlignmentParam)
3014 *AlignmentParam = Params;
Akira Hatanakacae83f72017-06-29 18:48:40 +00003015 }
Richard Smithb2f0f052016-10-10 18:54:32 +00003016
3017 // Finally, if this is not a sized delete, the final parameter can
3018 // be a 'const std::nothrow_t&'.
3019 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
3020 Ty = Ty->getPointeeType();
3021 if (Ty.getCVRQualifiers() != Qualifiers::Const)
3022 return false;
Roman Lebedev3dd5a292020-02-26 01:37:17 +03003023 if (Ty->isNothrowT()) {
3024 if (IsNothrow)
3025 *IsNothrow = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00003026 Consume();
Roman Lebedev3dd5a292020-02-26 01:37:17 +03003027 }
Richard Smithb2f0f052016-10-10 18:54:32 +00003028 }
3029
3030 return Params == FPT->getNumParams();
Richard Smith8d0dc312013-07-21 23:12:18 +00003031}
3032
serge-sans-pailled437fba2020-01-16 19:54:38 +01003033bool FunctionDecl::isInlineBuiltinDeclaration() const {
3034 if (!getBuiltinID())
3035 return false;
3036
3037 const FunctionDecl *Definition;
3038 return hasBody(Definition) && Definition->isInlineSpecified();
3039}
3040
Richard Smith5b349582017-10-13 01:55:36 +00003041bool FunctionDecl::isDestroyingOperatorDelete() const {
3042 // C++ P0722:
3043 // Within a class C, a single object deallocation function with signature
3044 // (T, std::destroying_delete_t, <more params>)
3045 // is a destroying operator delete.
3046 if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
3047 getNumParams() < 2)
3048 return false;
3049
3050 auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
3051 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
3052 RD->getIdentifier()->isStr("destroying_delete_t");
3053}
3054
Rafael Espindolaf4187652013-02-14 01:18:37 +00003055LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00003056 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00003057}
3058
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003059bool FunctionDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00003060 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003061}
3062
Rafael Espindola593537a2013-05-05 20:15:21 +00003063bool FunctionDecl::isInExternCContext() const {
Anastasia Stulovad6865b72019-05-07 14:22:34 +00003064 if (hasAttr<OpenCLKernelAttr>())
3065 return true;
Serge Pavlov3cb80222013-11-14 02:13:03 +00003066 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00003067}
3068
3069bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00003070 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00003071}
3072
Douglas Gregorf1b876d2009-03-31 16:35:03 +00003073bool FunctionDecl::isGlobal() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003074 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
Douglas Gregorf1b876d2009-03-31 16:35:03 +00003075 return Method->isStatic();
3076
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003077 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00003078 return false;
3079
Mike Stump11289f42009-09-09 15:08:12 +00003080 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00003081 DC->isNamespace();
3082 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003083 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
Douglas Gregorf1b876d2009-03-31 16:35:03 +00003084 if (!Namespace->getDeclName())
3085 return false;
3086 break;
3087 }
3088 }
3089
3090 return true;
3091}
3092
Richard Smith10876ef2013-01-17 01:30:42 +00003093bool FunctionDecl::isNoReturn() const {
Adrian Prantl721c7cb2016-08-17 16:42:15 +00003094 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
3095 hasAttr<C11NoReturnAttr>())
3096 return true;
3097
3098 if (auto *FnTy = getType()->getAs<FunctionType>())
3099 return FnTy->getNoReturnAttr();
3100
3101 return false;
Richard Smith10876ef2013-01-17 01:30:42 +00003102}
3103
Erich Keane5c0d1922018-11-28 18:34:14 +00003104
3105MultiVersionKind FunctionDecl::getMultiVersionKind() const {
3106 if (hasAttr<TargetAttr>())
3107 return MultiVersionKind::Target;
3108 if (hasAttr<CPUDispatchAttr>())
3109 return MultiVersionKind::CPUDispatch;
3110 if (hasAttr<CPUSpecificAttr>())
3111 return MultiVersionKind::CPUSpecific;
3112 return MultiVersionKind::None;
3113}
3114
Erich Keane3efe0022018-07-20 14:13:28 +00003115bool FunctionDecl::isCPUDispatchMultiVersion() const {
3116 return isMultiVersion() && hasAttr<CPUDispatchAttr>();
3117}
3118
3119bool FunctionDecl::isCPUSpecificMultiVersion() const {
3120 return isMultiVersion() && hasAttr<CPUSpecificAttr>();
3121}
3122
Erich Keane19a8adc2018-10-25 18:57:19 +00003123bool FunctionDecl::isTargetMultiVersion() const {
3124 return isMultiVersion() && hasAttr<TargetAttr>();
3125}
3126
Sebastian Redl833ef452010-01-26 22:01:41 +00003127void
3128FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00003129 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00003130
3131 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
3132 FunctionTemplateDecl *PrevFunTmpl
Craig Topper36250ad2014-05-12 05:36:57 +00003133 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00003134 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00003135 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00003136 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003137
Erich Keane9c665062018-08-01 21:02:40 +00003138 if (PrevDecl && PrevDecl->isInlined())
3139 setImplicitlyInline(true);
Sebastian Redl833ef452010-01-26 22:01:41 +00003140}
3141
Rafael Espindola8db352d2013-10-17 15:37:26 +00003142FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00003143
Erik Pilkingtonb6e16ea2019-03-18 19:23:45 +00003144/// Returns a value indicating whether this function corresponds to a builtin
3145/// function.
Douglas Gregorb9063fc2009-02-13 23:20:09 +00003146///
Erik Pilkingtonb6e16ea2019-03-18 19:23:45 +00003147/// The function corresponds to a built-in function if it is declared at
3148/// translation scope or within an extern "C" block and its name matches with
3149/// the name of a builtin. The returned value will be 0 for functions that do
3150/// not correspond to a builtin, a value of type \c Builtin::ID if in the
3151/// target-independent range \c [1,Builtin::First), or a target-specific builtin
3152/// value.
3153///
3154/// \param ConsiderWrapperFunctions If true, we should consider wrapper
3155/// functions as their wrapped builtins. This shouldn't be done in general, but
3156/// it's useful in Sema to diagnose calls to wrappers based on their semantics.
3157unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
Simon Tatham7c11da02019-09-02 15:35:09 +01003158 unsigned BuiltinID;
Douglas Gregore711f702009-02-14 18:57:46 +00003159
Mikhail Maltsev47edf5ba2020-03-10 14:01:42 +00003160 if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) {
3161 BuiltinID = ABAA->getBuiltinName()->getBuiltinID();
Simon Tatham7c11da02019-09-02 15:35:09 +01003162 } else {
3163 if (!getIdentifier())
3164 return 0;
3165
3166 BuiltinID = getIdentifier()->getBuiltinID();
3167 }
3168
Daniel Dunbar304314d2012-03-06 23:52:37 +00003169 if (!BuiltinID)
3170 return 0;
3171
3172 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00003173 if (Context.getLangOpts().CPlusPlus) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003174 const auto *LinkageDecl =
3175 dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
Warren Hunt445d83e2013-11-01 23:46:51 +00003176 // In C++, the first declaration of a builtin is always inside an implicit
3177 // extern "C".
3178 // FIXME: A recognised library function may not be directly in an extern "C"
3179 // declaration, for instance "extern "C" { namespace std { decl } }".
David Majnemerba3e5ec2015-03-13 18:26:17 +00003180 if (!LinkageDecl) {
3181 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
David Majnemer145abde2016-01-26 01:12:17 +00003182 Context.getTargetInfo().getCXXABI().isMicrosoft())
David Majnemerba3e5ec2015-03-13 18:26:17 +00003183 return Builtin::BI__GetExceptionInfo;
3184 return 0;
3185 }
3186 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
Warren Hunt445d83e2013-11-01 23:46:51 +00003187 return 0;
3188 }
3189
3190 // If the function is marked "overloadable", it has a different mangled name
3191 // and is not the C library function.
Simon Tatham7c11da02019-09-02 15:35:09 +01003192 if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&
Mikhail Maltsev47edf5ba2020-03-10 14:01:42 +00003193 !hasAttr<ArmBuiltinAliasAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00003194 return 0;
3195
Douglas Gregore711f702009-02-14 18:57:46 +00003196 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3197 return BuiltinID;
3198
3199 // This function has the name of a known C library
3200 // function. Determine whether it actually refers to the C library
3201 // function or whether it just has the same name.
3202
Douglas Gregora908e7f2009-02-17 03:23:10 +00003203 // If this is a static function, it's not a builtin.
Erik Pilkingtonb6e16ea2019-03-18 19:23:45 +00003204 if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00003205 return 0;
3206
Anastasia Stulova1202de32016-02-12 12:07:04 +00003207 // OpenCL v1.2 s6.9.f - The library functions defined in
3208 // the C99 standard headers are not available.
3209 if (Context.getLangOpts().OpenCL &&
3210 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3211 return 0;
3212
Artem Belevich5ecdb942018-01-23 19:08:18 +00003213 // CUDA does not have device-side standard library. printf and malloc are the
3214 // only special cases that are supported by device-side runtime.
3215 if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
3216 !hasAttr<CUDAHostAttr>() &&
3217 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3218 return 0;
3219
Warren Hunt445d83e2013-11-01 23:46:51 +00003220 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00003221}
3222
Chris Lattner47c0d002009-04-25 06:03:53 +00003223/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00003224/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00003225/// after it has been created.
3226unsigned FunctionDecl::getNumParams() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003227 const auto *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003228 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00003229}
3230
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003231void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003232 ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00003233 assert(!ParamInfo && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00003234 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00003235
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00003236 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003237 if (!NewParamInfo.empty()) {
3238 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
3239 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00003240 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00003241}
Chris Lattner41943152007-01-25 04:52:46 +00003242
Chris Lattner58258242008-04-10 02:22:51 +00003243/// getMinRequiredArguments - Returns the minimum number of arguments
3244/// needed to call this function. This may be fewer than the number of
3245/// function parameters, if some of the parameters have default
Richard Smith91151782014-04-01 19:18:16 +00003246/// arguments (in C++) or are parameter packs (C++11).
Chris Lattner58258242008-04-10 02:22:51 +00003247unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003248 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003249 return getNumParams();
Chris Lattner58258242008-04-10 02:22:51 +00003250
Richard Smith91151782014-04-01 19:18:16 +00003251 unsigned NumRequiredArgs = 0;
David Majnemer59f77922016-06-24 04:05:48 +00003252 for (auto *Param : parameters())
Richard Smith91151782014-04-01 19:18:16 +00003253 if (!Param->isParameterPack() && !Param->hasDefaultArg())
3254 ++NumRequiredArgs;
Chris Lattner58258242008-04-10 02:22:51 +00003255 return NumRequiredArgs;
3256}
3257
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003258/// The combination of the extern and inline keywords under MSVC forces
David Majnemer54e3ba52014-04-02 23:17:29 +00003259/// the function to be required.
3260///
3261/// Note: This function assumes that we will only get called when isInlined()
3262/// would return true for this FunctionDecl.
3263bool FunctionDecl::isMSExternInline() const {
3264 assert(isInlined() && "expected to get called on an inlined function!");
3265
3266 const ASTContext &Context = getASTContext();
David Majnemer3f021502015-10-08 04:53:31 +00003267 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3268 !hasAttr<DLLExportAttr>())
David Majnemer54e3ba52014-04-02 23:17:29 +00003269 return false;
3270
David Majnemer73768702015-03-20 00:02:27 +00003271 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
3272 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00003273 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00003274 return true;
3275
3276 return false;
3277}
3278
3279static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3280 if (Redecl->getStorageClass() != SC_Extern)
3281 return false;
3282
3283 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
3284 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00003285 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00003286 return false;
3287
3288 return true;
3289}
3290
Eli Friedman1b125c32012-02-07 03:50:18 +00003291static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3292 // Only consider file-scope declarations in this test.
3293 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3294 return false;
3295
3296 // Only consider explicit declarations; the presence of a builtin for a
3297 // libcall shouldn't affect whether a definition is externally visible.
3298 if (Redecl->isImplicit())
3299 return false;
3300
Fangrui Song6907ce22018-07-30 19:24:48 +00003301 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00003302 return true; // Not an inline definition
3303
3304 return false;
3305}
3306
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003307/// For a function declaration in C or C++, determine whether this
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003308/// declaration causes the definition to be externally visible.
3309///
David Majnemer54e3ba52014-04-02 23:17:29 +00003310/// For instance, this determines if adding the current declaration to the set
Eli Friedman1b125c32012-02-07 03:50:18 +00003311/// of redeclarations of the given functions causes
3312/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003313bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
Justin Lebar0241c962016-10-28 16:46:39 +00003314 assert(!doesThisDeclarationHaveABody() &&
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003315 "Must have a declaration without a body.");
3316
3317 ASTContext &Context = getASTContext();
3318
David Majnemer54e3ba52014-04-02 23:17:29 +00003319 if (Context.getLangOpts().MSVCCompat) {
3320 const FunctionDecl *Definition;
3321 if (hasBody(Definition) && Definition->isInlined() &&
3322 redeclForcesDefMSVC(this))
3323 return true;
3324 }
3325
Martin Storsjo71decf82019-09-27 12:25:19 +00003326 if (Context.getLangOpts().CPlusPlus)
3327 return false;
3328
David Blaikiebbafb8a2012-03-11 07:00:24 +00003329 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003330 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3331 // an externally visible definition.
3332 //
3333 // FIXME: What happens if gnu_inline gets added on after the first
3334 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003335 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00003336 return false;
3337
3338 const FunctionDecl *Prev = this;
3339 bool FoundBody = false;
3340 while ((Prev = Prev->getPreviousDecl())) {
Richard Smith848934c2019-12-05 13:37:35 -08003341 FoundBody |= Prev->doesThisDeclarationHaveABody();
Eli Friedman1b125c32012-02-07 03:50:18 +00003342
Richard Smith848934c2019-12-05 13:37:35 -08003343 if (Prev->doesThisDeclarationHaveABody()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003344 // If it's not the case that both 'inline' and 'extern' are
3345 // specified on the definition, then it is always externally visible.
3346 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003347 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00003348 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003349 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003350 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003351 return false;
3352 }
3353 }
3354 return FoundBody;
3355 }
3356
Eli Friedman1b125c32012-02-07 03:50:18 +00003357 // C99 6.7.4p6:
Fangrui Song6907ce22018-07-30 19:24:48 +00003358 // [...] If all of the file scope declarations for a function in a
3359 // translation unit include the inline function specifier without extern,
Eli Friedman1b125c32012-02-07 03:50:18 +00003360 // then the definition in that translation unit is an inline definition.
3361 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003362 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00003363 const FunctionDecl *Prev = this;
3364 bool FoundBody = false;
3365 while ((Prev = Prev->getPreviousDecl())) {
Richard Smith848934c2019-12-05 13:37:35 -08003366 FoundBody |= Prev->doesThisDeclarationHaveABody();
Eli Friedman1b125c32012-02-07 03:50:18 +00003367 if (RedeclForcesDefC99(Prev))
3368 return false;
3369 }
3370 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003371}
3372
Richard Smithd052a5782019-10-22 17:44:08 -07003373FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const {
Alp Tokerd0787eb2014-07-02 01:47:15 +00003374 const TypeSourceInfo *TSI = getTypeSourceInfo();
Richard Smithd052a5782019-10-22 17:44:08 -07003375 return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>()
3376 : FunctionTypeLoc();
3377}
3378
3379SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3380 FunctionTypeLoc FTL = getFunctionTypeLoc();
Alp Tokerf5b10792014-07-02 12:55:58 +00003381 if (!FTL)
Alp Tokerd0787eb2014-07-02 01:47:15 +00003382 return SourceRange();
3383
Alp Tokerf5b10792014-07-02 12:55:58 +00003384 // Skip self-referential return types.
3385 const SourceManager &SM = getASTContext().getSourceManager();
3386 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003387 SourceLocation Boundary = getNameInfo().getBeginLoc();
Alp Tokerf5b10792014-07-02 12:55:58 +00003388 if (RTRange.isInvalid() || Boundary.isInvalid() ||
3389 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3390 return SourceRange();
Alp Tokerd0787eb2014-07-02 01:47:15 +00003391
Alp Tokerf5b10792014-07-02 12:55:58 +00003392 return RTRange;
Alp Tokerd0787eb2014-07-02 01:47:15 +00003393}
3394
Nicolas Manichoncc3c9352019-12-03 08:21:55 -05003395SourceRange FunctionDecl::getParametersSourceRange() const {
3396 unsigned NP = getNumParams();
3397 SourceLocation EllipsisLoc = getEllipsisLoc();
3398
3399 if (NP == 0 && EllipsisLoc.isInvalid())
3400 return SourceRange();
3401
3402 SourceLocation Begin =
3403 NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;
3404 SourceLocation End = EllipsisLoc.isValid()
3405 ? EllipsisLoc
3406 : ParamInfo[NP - 1]->getSourceRange().getEnd();
3407
3408 return SourceRange(Begin, End);
3409}
3410
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003411SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
Richard Smithd052a5782019-10-22 17:44:08 -07003412 FunctionTypeLoc FTL = getFunctionTypeLoc();
3413 return FTL ? FTL.getExceptionSpecRange() : SourceRange();
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003414}
3415
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003416/// For an inline function definition in C, or for a gnu_inline function
Richard Smithf3814ad2013-01-25 00:08:28 +00003417/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00003418///
3419/// Inline function definitions are always available for inlining optimizations.
3420/// However, depending on the language dialect, declaration specifiers, and
3421/// attributes, the definition of an inline function may or may not be
3422/// "externally" visible to other translation units in the program.
3423///
3424/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00003425/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00003426/// inline definition becomes externally visible (C99 6.7.4p6).
3427///
3428/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
Fangrui Song6907ce22018-07-30 19:24:48 +00003429/// definition, we use the GNU semantics for inline, which are nearly the
3430/// opposite of C99 semantics. In particular, "inline" by itself will create
3431/// an externally visible symbol, but "extern inline" will not create an
Douglas Gregor299d76e2009-09-13 07:46:26 +00003432/// externally visible symbol.
3433bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Nick Desaulniers58060222019-09-12 19:53:35 +00003434 assert((doesThisDeclarationHaveABody() || willHaveBody() ||
3435 hasAttr<AliasAttr>()) &&
Manuel Klimekda7456a2016-11-01 10:30:50 +00003436 "Must be a function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003437 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00003438 ASTContext &Context = getASTContext();
Fangrui Song6907ce22018-07-30 19:24:48 +00003439
David Blaikiebbafb8a2012-03-11 07:00:24 +00003440 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003441 // Note: If you change the logic here, please change
3442 // doesDeclarationForceExternallyVisibleDefinition as well.
3443 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00003444 // If it's not the case that both 'inline' and 'extern' are
3445 // specified on the definition, then this inline definition is
3446 // externally visible.
Martin Storsjo71decf82019-09-27 12:25:19 +00003447 if (Context.getLangOpts().CPlusPlus)
3448 return false;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003449 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00003450 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003451
Douglas Gregorff76cb92010-12-09 16:59:22 +00003452 // If any declaration is 'inline' but not 'extern', then this definition
3453 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00003454 for (auto Redecl : redecls()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003455 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003456 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00003457 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003458 }
3459
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003460 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003461 }
Eli Friedman1b125c32012-02-07 03:50:18 +00003462
Richard Smithf3814ad2013-01-25 00:08:28 +00003463 // The rest of this function is C-only.
3464 assert(!Context.getLangOpts().CPlusPlus &&
3465 "should not use C inline rules in C++");
3466
Douglas Gregor299d76e2009-09-13 07:46:26 +00003467 // C99 6.7.4p6:
Fangrui Song6907ce22018-07-30 19:24:48 +00003468 // [...] If all of the file scope declarations for a function in a
3469 // translation unit include the inline function specifier without extern,
Douglas Gregor299d76e2009-09-13 07:46:26 +00003470 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00003471 for (auto Redecl : redecls()) {
3472 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00003473 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003474 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003475
Douglas Gregor299d76e2009-09-13 07:46:26 +00003476 // C99 6.7.4p6:
Fangrui Song6907ce22018-07-30 19:24:48 +00003477 // An inline definition does not provide an external definition for the
3478 // function, and does not forbid an external definition in another
Douglas Gregor299d76e2009-09-13 07:46:26 +00003479 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003480 return false;
3481}
3482
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003483/// getOverloadedOperator - Which C++ overloaded operator this
3484/// function represents, if any.
3485OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00003486 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3487 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003488 else
3489 return OO_None;
3490}
3491
Alexis Huntc88db062010-01-13 09:01:02 +00003492/// getLiteralIdentifier - The literal suffix identifier this function
3493/// represents, if any.
3494const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3495 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3496 return getDeclName().getCXXLiteralIdentifier();
3497 else
Craig Topper36250ad2014-05-12 05:36:57 +00003498 return nullptr;
Alexis Huntc88db062010-01-13 09:01:02 +00003499}
3500
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003501FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3502 if (TemplateOrSpecialization.isNull())
3503 return TK_NonTemplate;
3504 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3505 return TK_FunctionTemplate;
3506 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3507 return TK_MemberSpecialization;
3508 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3509 return TK_FunctionTemplateSpecialization;
3510 if (TemplateOrSpecialization.is
3511 <DependentFunctionTemplateSpecializationInfo*>())
3512 return TK_DependentFunctionTemplateSpecialization;
3513
David Blaikie83d382b2011-09-23 05:06:16 +00003514 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003515}
3516
Douglas Gregord801b062009-10-07 23:56:10 +00003517FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00003518 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00003519 return cast<FunctionDecl>(Info->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00003520
3521 return nullptr;
Douglas Gregord801b062009-10-07 23:56:10 +00003522}
3523
Chandler Carruth21c90602015-12-30 03:24:14 +00003524MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
Richard Smithf19a8b02019-05-02 00:49:14 +00003525 if (auto *MSI =
3526 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3527 return MSI;
3528 if (auto *FTSI = TemplateOrSpecialization
3529 .dyn_cast<FunctionTemplateSpecializationInfo *>())
3530 return FTSI->getMemberSpecializationInfo();
3531 return nullptr;
Chandler Carruth21c90602015-12-30 03:24:14 +00003532}
3533
Fangrui Song6907ce22018-07-30 19:24:48 +00003534void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003535FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3536 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00003537 TemplateSpecializationKind TSK) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003538 assert(TemplateOrSpecialization.isNull() &&
Douglas Gregord801b062009-10-07 23:56:10 +00003539 "Member function is already a specialization");
Fangrui Song6907ce22018-07-30 19:24:48 +00003540 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003541 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00003542 TemplateOrSpecialization = Info;
3543}
3544
Chandler Carruth21c90602015-12-30 03:24:14 +00003545FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3546 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3547}
3548
3549void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
Richard Smithf19a8b02019-05-02 00:49:14 +00003550 assert(TemplateOrSpecialization.isNull() &&
3551 "Member function is already a specialization");
Chandler Carruth21c90602015-12-30 03:24:14 +00003552 TemplateOrSpecialization = Template;
3553}
3554
Douglas Gregorafca3b42009-10-27 20:53:28 +00003555bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00003556 // If the function is invalid, it can't be implicitly instantiated.
3557 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00003558 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003559
Richard Smithf19a8b02019-05-02 00:49:14 +00003560 switch (getTemplateSpecializationKindForInstantiation()) {
Douglas Gregorafca3b42009-10-27 20:53:28 +00003561 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00003562 case TSK_ExplicitInstantiationDefinition:
Richard Smithf19a8b02019-05-02 00:49:14 +00003563 case TSK_ExplicitSpecialization:
Douglas Gregorafca3b42009-10-27 20:53:28 +00003564 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003565
Douglas Gregorafca3b42009-10-27 20:53:28 +00003566 case TSK_ImplicitInstantiation:
3567 return true;
3568
3569 case TSK_ExplicitInstantiationDeclaration:
3570 // Handled below.
3571 break;
3572 }
3573
3574 // Find the actual template from which we will instantiate.
3575 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003576 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003577 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003578 HasPattern = PatternDecl->hasBody(PatternDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00003579
Douglas Gregorafca3b42009-10-27 20:53:28 +00003580 // C++0x [temp.explicit]p9:
3581 // Except for inline functions, other explicit instantiation declarations
3582 // have the effect of suppressing the implicit instantiation of the entity
Fangrui Song6907ce22018-07-30 19:24:48 +00003583 // to which they refer.
3584 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00003585 return true;
3586
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003587 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00003588}
3589
3590bool FunctionDecl::isTemplateInstantiation() const {
Richard Smithf19a8b02019-05-02 00:49:14 +00003591 // FIXME: Remove this, it's not clear what it means. (Which template
3592 // specialization kind?)
3593 return clang::isTemplateInstantiation(getTemplateSpecializationKind());
Ted Kremenek85825ae2011-12-01 00:59:17 +00003594}
Fangrui Song6907ce22018-07-30 19:24:48 +00003595
Douglas Gregorafca3b42009-10-27 20:53:28 +00003596FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003597 // If this is a generic lambda call operator specialization, its
Faisal Valib90b2112014-04-03 16:32:21 +00003598 // instantiation pattern is always its primary template's pattern
Fangrui Song6907ce22018-07-30 19:24:48 +00003599 // even if its primary template was instantiated from another
Faisal Valib90b2112014-04-03 16:32:21 +00003600 // member template (which happens with nested generic lambdas).
Fangrui Song6907ce22018-07-30 19:24:48 +00003601 // Since a lambda's call operator's body is transformed eagerly,
3602 // we don't have to go hunting for a prototype definition template
3603 // (i.e. instantiated-from-member-template) to use as an instantiation
Faisal Valib90b2112014-04-03 16:32:21 +00003604 // pattern.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003605
Faisal Valib90b2112014-04-03 16:32:21 +00003606 if (isGenericLambdaCallOperatorSpecialization(
3607 dyn_cast<CXXMethodDecl>(this))) {
Richard Smith2195ec92017-04-21 01:15:13 +00003608 assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3609 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
Faisal Valib90b2112014-04-03 16:32:21 +00003610 }
Richard Smith2195ec92017-04-21 01:15:13 +00003611
Richard Smithf19a8b02019-05-02 00:49:14 +00003612 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) {
3613 if (!clang::isTemplateInstantiation(Info->getTemplateSpecializationKind()))
3614 return nullptr;
3615 return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
3616 }
3617
3618 if (!clang::isTemplateInstantiation(getTemplateSpecializationKind()))
3619 return nullptr;
3620
Douglas Gregorafca3b42009-10-27 20:53:28 +00003621 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
Richard Smitha6b41d72019-05-03 23:51:38 +00003622 // If we hit a point where the user provided a specialization of this
3623 // template, we're done looking.
3624 while (!Primary->isMemberSpecialization()) {
3625 auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
3626 if (!NewPrimary)
Douglas Gregorafca3b42009-10-27 20:53:28 +00003627 break;
Richard Smitha6b41d72019-05-03 23:51:38 +00003628 Primary = NewPrimary;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003629 }
Richard Smith2195ec92017-04-21 01:15:13 +00003630
3631 return getDefinitionOrSelf(Primary->getTemplatedDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00003632 }
Richard Smith2195ec92017-04-21 01:15:13 +00003633
Richard Smith2195ec92017-04-21 01:15:13 +00003634 return nullptr;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003635}
3636
Douglas Gregor70d83e22009-06-29 17:30:29 +00003637FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00003638 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003639 = TemplateOrSpecialization
3640 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Richard Smithf19a8b02019-05-02 00:49:14 +00003641 return Info->getTemplate();
Douglas Gregor70d83e22009-06-29 17:30:29 +00003642 }
Craig Topper36250ad2014-05-12 05:36:57 +00003643 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003644}
3645
Chandler Carruth21c90602015-12-30 03:24:14 +00003646FunctionTemplateSpecializationInfo *
3647FunctionDecl::getTemplateSpecializationInfo() const {
3648 return TemplateOrSpecialization
3649 .dyn_cast<FunctionTemplateSpecializationInfo *>();
3650}
3651
Douglas Gregor70d83e22009-06-29 17:30:29 +00003652const TemplateArgumentList *
3653FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00003654 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00003655 = TemplateOrSpecialization
3656 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003657 return Info->TemplateArguments;
3658 }
Craig Topper36250ad2014-05-12 05:36:57 +00003659 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003660}
3661
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00003662const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003663FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3664 if (FunctionTemplateSpecializationInfo *Info
3665 = TemplateOrSpecialization
3666 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3667 return Info->TemplateArgumentsAsWritten;
3668 }
Craig Topper36250ad2014-05-12 05:36:57 +00003669 return nullptr;
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003670}
3671
Mike Stump11289f42009-09-09 15:08:12 +00003672void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003673FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3674 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003675 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003676 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003677 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00003678 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3679 SourceLocation PointOfInstantiation) {
Richard Smithf19a8b02019-05-02 00:49:14 +00003680 assert((TemplateOrSpecialization.isNull() ||
3681 TemplateOrSpecialization.is<MemberSpecializationInfo *>()) &&
3682 "Member function is already a specialization");
Fangrui Song6907ce22018-07-30 19:24:48 +00003683 assert(TSK != TSK_Undeclared &&
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003684 "Must specify the type of function template specialization");
Richard Smithf19a8b02019-05-02 00:49:14 +00003685 assert((TemplateOrSpecialization.isNull() ||
3686 TSK == TSK_ExplicitSpecialization) &&
3687 "Member specialization must be an explicit specialization");
3688 FunctionTemplateSpecializationInfo *Info =
3689 FunctionTemplateSpecializationInfo::Create(
3690 C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
3691 PointOfInstantiation,
3692 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>());
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003693 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00003694 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003695}
3696
John McCallb9c78482010-04-08 09:05:18 +00003697void
3698FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3699 const UnresolvedSetImpl &Templates,
3700 const TemplateArgumentListInfo &TemplateArgs) {
3701 assert(TemplateOrSpecialization.isNull());
John McCallb9c78482010-04-08 09:05:18 +00003702 DependentFunctionTemplateSpecializationInfo *Info =
James Y Knight7a22b242015-08-06 20:26:32 +00003703 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3704 TemplateArgs);
John McCallb9c78482010-04-08 09:05:18 +00003705 TemplateOrSpecialization = Info;
3706}
3707
James Y Knight7a22b242015-08-06 20:26:32 +00003708DependentFunctionTemplateSpecializationInfo *
Chandler Carruth21c90602015-12-30 03:24:14 +00003709FunctionDecl::getDependentSpecializationInfo() const {
3710 return TemplateOrSpecialization
3711 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3712}
3713
3714DependentFunctionTemplateSpecializationInfo *
James Y Knight7a22b242015-08-06 20:26:32 +00003715DependentFunctionTemplateSpecializationInfo::Create(
3716 ASTContext &Context, const UnresolvedSetImpl &Ts,
3717 const TemplateArgumentListInfo &TArgs) {
3718 void *Buffer = Context.Allocate(
3719 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3720 TArgs.size(), Ts.size()));
3721 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3722}
3723
John McCallb9c78482010-04-08 09:05:18 +00003724DependentFunctionTemplateSpecializationInfo::
3725DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3726 const TemplateArgumentListInfo &TArgs)
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003727 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
James Y Knight53c76162015-07-17 18:21:37 +00003728 NumTemplates = Ts.size();
3729 NumArgs = TArgs.size();
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003730
James Y Knight7a22b242015-08-06 20:26:32 +00003731 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
John McCallb9c78482010-04-08 09:05:18 +00003732 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3733 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3734
James Y Knight7a22b242015-08-06 20:26:32 +00003735 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
John McCallb9c78482010-04-08 09:05:18 +00003736 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3737 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3738}
3739
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003740TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00003741 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003742 // information object.
Richard Smithf19a8b02019-05-02 00:49:14 +00003743 if (FunctionTemplateSpecializationInfo *FTSInfo =
3744 TemplateOrSpecialization
3745 .dyn_cast<FunctionTemplateSpecializationInfo *>())
Douglas Gregord801b062009-10-07 23:56:10 +00003746 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00003747
Richard Smithf19a8b02019-05-02 00:49:14 +00003748 if (MemberSpecializationInfo *MSInfo =
3749 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3750 return MSInfo->getTemplateSpecializationKind();
3751
3752 return TSK_Undeclared;
3753}
3754
3755TemplateSpecializationKind
3756FunctionDecl::getTemplateSpecializationKindForInstantiation() const {
3757 // This is the same as getTemplateSpecializationKind(), except that for a
3758 // function that is both a function template specialization and a member
3759 // specialization, we prefer the member specialization information. Eg:
3760 //
3761 // template<typename T> struct A {
3762 // template<typename U> void f() {}
3763 // template<> void f<int>() {}
3764 // };
3765 //
3766 // For A<int>::f<int>():
3767 // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
3768 // * getTemplateSpecializationKindForInstantiation() will return
3769 // TSK_ImplicitInstantiation
3770 //
3771 // This reflects the facts that A<int>::f<int> is an explicit specialization
3772 // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
3773 // from A::f<int> if a definition is needed.
3774 if (FunctionTemplateSpecializationInfo *FTSInfo =
3775 TemplateOrSpecialization
3776 .dyn_cast<FunctionTemplateSpecializationInfo *>()) {
3777 if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
3778 return MSInfo->getTemplateSpecializationKind();
3779 return FTSInfo->getTemplateSpecializationKind();
3780 }
3781
3782 if (MemberSpecializationInfo *MSInfo =
3783 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
Douglas Gregord801b062009-10-07 23:56:10 +00003784 return MSInfo->getTemplateSpecializationKind();
Fangrui Song6907ce22018-07-30 19:24:48 +00003785
Douglas Gregord801b062009-10-07 23:56:10 +00003786 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003787}
3788
Mike Stump11289f42009-09-09 15:08:12 +00003789void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003790FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3791 SourceLocation PointOfInstantiation) {
3792 if (FunctionTemplateSpecializationInfo *FTSInfo
3793 = TemplateOrSpecialization.dyn_cast<
3794 FunctionTemplateSpecializationInfo*>()) {
3795 FTSInfo->setTemplateSpecializationKind(TSK);
3796 if (TSK != TSK_ExplicitSpecialization &&
3797 PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00003798 FTSInfo->getPointOfInstantiation().isInvalid()) {
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003799 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00003800 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3801 L->InstantiationRequested(this);
3802 }
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003803 } else if (MemberSpecializationInfo *MSInfo
3804 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3805 MSInfo->setTemplateSpecializationKind(TSK);
3806 if (TSK != TSK_ExplicitSpecialization &&
3807 PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00003808 MSInfo->getPointOfInstantiation().isInvalid()) {
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003809 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00003810 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3811 L->InstantiationRequested(this);
3812 }
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003813 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003814 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003815}
3816
3817SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00003818 if (FunctionTemplateSpecializationInfo *FTSInfo
3819 = TemplateOrSpecialization.dyn_cast<
3820 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003821 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00003822 else if (MemberSpecializationInfo *MSInfo
3823 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003824 return MSInfo->getPointOfInstantiation();
Fangrui Song6907ce22018-07-30 19:24:48 +00003825
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003826 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00003827}
3828
Douglas Gregor6411b922009-09-11 20:15:17 +00003829bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00003830 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00003831 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003832
3833 // If this function was instantiated from a member function of a
Douglas Gregor6411b922009-09-11 20:15:17 +00003834 // class template, check whether that member function was defined out-of-line.
3835 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3836 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003837 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003838 return Definition->isOutOfLine();
3839 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003840
Douglas Gregor6411b922009-09-11 20:15:17 +00003841 // If this function was instantiated from a function template,
3842 // check whether that function template was defined out-of-line.
3843 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3844 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003845 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003846 return Definition->isOutOfLine();
3847 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003848
Douglas Gregor6411b922009-09-11 20:15:17 +00003849 return false;
3850}
3851
Abramo Bagnaraea947882011-03-08 16:41:52 +00003852SourceRange FunctionDecl::getSourceRange() const {
3853 return SourceRange(getOuterLocStart(), EndRangeLoc);
3854}
3855
Anna Zaks28db7ce2012-01-18 02:45:01 +00003856unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00003857 IdentifierInfo *FnInfo = getIdentifier();
3858
3859 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00003860 return 0;
Fangrui Song6907ce22018-07-30 19:24:48 +00003861
Anna Zaks201d4892012-01-13 21:52:01 +00003862 // Builtin handling.
3863 switch (getBuiltinID()) {
3864 case Builtin::BI__builtin_memset:
3865 case Builtin::BI__builtin___memset_chk:
3866 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003867 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003868
3869 case Builtin::BI__builtin_memcpy:
3870 case Builtin::BI__builtin___memcpy_chk:
3871 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003872 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003873
serge-sans-paillecee4a1c2019-12-11 21:30:10 +01003874 case Builtin::BI__builtin_mempcpy:
3875 case Builtin::BI__builtin___mempcpy_chk:
3876 case Builtin::BImempcpy:
3877 return Builtin::BImempcpy;
3878
Anna Zaks201d4892012-01-13 21:52:01 +00003879 case Builtin::BI__builtin_memmove:
3880 case Builtin::BI__builtin___memmove_chk:
3881 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003882 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003883
3884 case Builtin::BIstrlcpy:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003885 case Builtin::BI__builtin___strlcpy_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003886 return Builtin::BIstrlcpy;
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003887
Anna Zaks201d4892012-01-13 21:52:01 +00003888 case Builtin::BIstrlcat:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003889 case Builtin::BI__builtin___strlcat_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003890 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003891
3892 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003893 case Builtin::BImemcmp:
3894 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003895
Clement Courbet8c3343d2019-02-14 12:00:34 +00003896 case Builtin::BI__builtin_bcmp:
3897 case Builtin::BIbcmp:
3898 return Builtin::BIbcmp;
3899
Anna Zaks201d4892012-01-13 21:52:01 +00003900 case Builtin::BI__builtin_strncpy:
3901 case Builtin::BI__builtin___strncpy_chk:
3902 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003903 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003904
3905 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003906 case Builtin::BIstrncmp:
3907 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003908
3909 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003910 case Builtin::BIstrncasecmp:
3911 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003912
3913 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003914 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003915 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003916 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003917
3918 case Builtin::BI__builtin_strndup:
3919 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003920 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003921
Anna Zaks314cd092012-02-01 19:08:57 +00003922 case Builtin::BI__builtin_strlen:
3923 case Builtin::BIstrlen:
3924 return Builtin::BIstrlen;
3925
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003926 case Builtin::BI__builtin_bzero:
3927 case Builtin::BIbzero:
3928 return Builtin::BIbzero;
3929
Anna Zaks201d4892012-01-13 21:52:01 +00003930 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003931 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003932 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003933 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003934 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003935 return Builtin::BImemcpy;
serge-sans-paillecee4a1c2019-12-11 21:30:10 +01003936 else if (FnInfo->isStr("mempcpy"))
3937 return Builtin::BImempcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003938 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003939 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003940 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003941 return Builtin::BImemcmp;
Clement Courbet8c3343d2019-02-14 12:00:34 +00003942 else if (FnInfo->isStr("bcmp"))
3943 return Builtin::BIbcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003944 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003945 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003946 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003947 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003948 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003949 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003950 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003951 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003952 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003953 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003954 else if (FnInfo->isStr("strlen"))
3955 return Builtin::BIstrlen;
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003956 else if (FnInfo->isStr("bzero"))
3957 return Builtin::BIbzero;
Anna Zaks201d4892012-01-13 21:52:01 +00003958 }
3959 break;
3960 }
Anna Zaks22122702012-01-17 00:37:07 +00003961 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003962}
3963
Richard Trieu27c1b1a2018-07-10 01:40:50 +00003964unsigned FunctionDecl::getODRHash() const {
Erich Keane9c665062018-08-01 21:02:40 +00003965 assert(hasODRHash());
Richard Trieu27c1b1a2018-07-10 01:40:50 +00003966 return ODRHash;
3967}
3968
Richard Trieue6caa262017-12-23 00:41:01 +00003969unsigned FunctionDecl::getODRHash() {
Erich Keane9c665062018-08-01 21:02:40 +00003970 if (hasODRHash())
Richard Trieue6caa262017-12-23 00:41:01 +00003971 return ODRHash;
3972
Richard Trieu0ac2eb72018-02-22 05:50:29 +00003973 if (auto *FT = getInstantiatedFromMemberFunction()) {
Erich Keane9c665062018-08-01 21:02:40 +00003974 setHasODRHash(true);
Richard Trieu0ac2eb72018-02-22 05:50:29 +00003975 ODRHash = FT->getODRHash();
3976 return ODRHash;
3977 }
3978
Richard Trieue6caa262017-12-23 00:41:01 +00003979 class ODRHash Hash;
3980 Hash.AddFunctionDecl(this);
Erich Keane9c665062018-08-01 21:02:40 +00003981 setHasODRHash(true);
Richard Trieue6caa262017-12-23 00:41:01 +00003982 ODRHash = Hash.CalculateHash();
3983 return ODRHash;
3984}
3985
Chris Lattner59a25942008-03-31 00:36:02 +00003986//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003987// FieldDecl Implementation
3988//===----------------------------------------------------------------------===//
3989
Jay Foad39c79802011-01-12 09:06:06 +00003990FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003991 SourceLocation StartLoc, SourceLocation IdLoc,
3992 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003993 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003994 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003995 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3996 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003997}
3998
Douglas Gregor72172e92012-01-05 21:55:30 +00003999FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004000 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
4001 SourceLocation(), nullptr, QualType(), nullptr,
4002 nullptr, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00004003}
4004
Sebastian Redl833ef452010-01-26 22:01:41 +00004005bool FieldDecl::isAnonymousStructOrUnion() const {
4006 if (!isImplicit() || getDeclName())
4007 return false;
4008
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004009 if (const auto *Record = getType()->getAs<RecordType>())
Sebastian Redl833ef452010-01-26 22:01:41 +00004010 return Record->getDecl()->isAnonymousStructOrUnion();
4011
4012 return false;
4013}
4014
Richard Smithcaf33902011-10-10 18:28:20 +00004015unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
4016 assert(isBitField() && "not a bitfield");
Richard Smith6b8e3c02017-08-28 00:28:14 +00004017 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
Richard Smithcaf33902011-10-10 18:28:20 +00004018}
4019
Richard Smith866dee42018-04-02 18:29:43 +00004020bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const {
4021 return isUnnamedBitfield() && !getBitWidth()->isValueDependent() &&
4022 getBitWidthValue(Ctx) == 0;
4023}
4024
Richard Smith78b239e2019-06-20 20:44:45 +00004025bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
4026 if (isZeroLengthBitField(Ctx))
4027 return true;
4028
4029 // C++2a [intro.object]p7:
4030 // An object has nonzero size if it
4031 // -- is not a potentially-overlapping subobject, or
4032 if (!hasAttr<NoUniqueAddressAttr>())
4033 return false;
4034
4035 // -- is not of class type, or
4036 const auto *RT = getType()->getAs<RecordType>();
4037 if (!RT)
4038 return false;
4039 const RecordDecl *RD = RT->getDecl()->getDefinition();
4040 if (!RD) {
4041 assert(isInvalidDecl() && "valid field has incomplete type");
4042 return false;
4043 }
4044
4045 // -- [has] virtual member functions or virtual base classes, or
4046 // -- has subobjects of nonzero size or bit-fields of nonzero length
4047 const auto *CXXRD = cast<CXXRecordDecl>(RD);
4048 if (!CXXRD->isEmpty())
4049 return false;
4050
4051 // Otherwise, [...] the circumstances under which the object has zero size
4052 // are implementation-defined.
4053 // FIXME: This might be Itanium ABI specific; we don't yet know what the MS
4054 // ABI will do.
4055 return true;
4056}
4057
John McCall4e819612011-01-20 07:57:12 +00004058unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00004059 const FieldDecl *Canonical = getCanonicalDecl();
4060 if (Canonical != this)
4061 return Canonical->getFieldIndex();
4062
John McCall4e819612011-01-20 07:57:12 +00004063 if (CachedFieldIndex) return CachedFieldIndex - 1;
4064
Richard Smithd62306a2011-11-10 06:34:14 +00004065 unsigned Index = 0;
Richard Smith85567dd2017-11-15 01:33:46 +00004066 const RecordDecl *RD = getParent()->getDefinition();
4067 assert(RD && "requested index for field of struct with no definition");
Richard Smithd62306a2011-11-10 06:34:14 +00004068
Hans Wennborga302cd92014-08-21 16:06:57 +00004069 for (auto *Field : RD->fields()) {
4070 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
4071 ++Index;
4072 }
John McCall4e819612011-01-20 07:57:12 +00004073
Richard Smithd62306a2011-11-10 06:34:14 +00004074 assert(CachedFieldIndex && "failed to find field in parent");
4075 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00004076}
4077
Abramo Bagnara20c9e242011-03-08 11:07:11 +00004078SourceRange FieldDecl::getSourceRange() const {
Richard Smith6b8e3c02017-08-28 00:28:14 +00004079 const Expr *FinalExpr = getInClassInitializer();
4080 if (!FinalExpr)
4081 FinalExpr = getBitWidth();
4082 if (FinalExpr)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004083 return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
Richard Smith6b8e3c02017-08-28 00:28:14 +00004084 return DeclaratorDecl::getSourceRange();
Alexey Bataev39c81e22014-08-28 04:28:19 +00004085}
4086
4087void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
David Blaikie11ab0782014-10-31 17:18:09 +00004088 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
Alexey Bataev330de032014-10-29 12:21:55 +00004089 "capturing type in non-lambda or captured record.");
Richard Smith6b8e3c02017-08-28 00:28:14 +00004090 assert(InitStorage.getInt() == ISK_NoInit &&
John McCallc90c1492014-10-10 18:44:34 +00004091 InitStorage.getPointer() == nullptr &&
Alexey Bataev39c81e22014-08-28 04:28:19 +00004092 "bit width, initializer or captured type already set");
John McCallc90c1492014-10-10 18:44:34 +00004093 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
4094 ISK_CapturedVLAType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00004095}
4096
Sebastian Redl833ef452010-01-26 22:01:41 +00004097//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00004098// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00004099//===----------------------------------------------------------------------===//
4100
Erich Keanef92f31c2018-08-01 20:48:16 +00004101TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
4102 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
4103 SourceLocation StartL)
4104 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
4105 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
4106 assert((DK != Enum || TK == TTK_Enum) &&
4107 "EnumDecl not matched with TTK_Enum");
4108 setPreviousDecl(PrevDecl);
4109 setTagKind(TK);
4110 setCompleteDefinition(false);
4111 setBeingDefined(false);
4112 setEmbeddedInDeclarator(false);
4113 setFreeStanding(false);
4114 setCompleteDefinitionRequired(false);
4115}
4116
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00004117SourceLocation TagDecl::getOuterLocStart() const {
4118 return getTemplateOrInnerLocStart(this);
4119}
4120
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00004121SourceRange TagDecl::getSourceRange() const {
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004122 SourceLocation RBraceLoc = BraceRange.getEnd();
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00004123 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00004124 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00004125}
4126
Rafael Espindola8db352d2013-10-17 15:37:26 +00004127TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00004128
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00004129void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer00350522015-08-31 18:48:39 +00004130 TypedefNameDeclOrQualifier = TDD;
Reid Klecknercae82a22014-04-23 22:03:04 +00004131 if (const Type *T = getTypeForDecl()) {
4132 (void)T;
Richard Smith5b21db82014-04-23 18:20:42 +00004133 assert(T->isLinkageValid());
Reid Klecknercae82a22014-04-23 22:03:04 +00004134 }
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004135 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00004136}
4137
Douglas Gregordee1be82009-01-17 00:42:38 +00004138void TagDecl::startDefinition() {
Erich Keanef92f31c2018-08-01 20:48:16 +00004139 setBeingDefined(true);
John McCall67da35c2010-02-04 22:26:26 +00004140
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004141 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
Richard Smith053f6c62014-05-16 23:01:30 +00004142 struct CXXRecordDecl::DefinitionData *Data =
John McCall67da35c2010-02-04 22:26:26 +00004143 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00004144 for (auto I : redecls())
Richard Smith64c06302014-05-22 23:19:02 +00004145 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00004146 }
Douglas Gregordee1be82009-01-17 00:42:38 +00004147}
4148
4149void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00004150 assert((!isa<CXXRecordDecl>(this) ||
4151 cast<CXXRecordDecl>(this)->hasDefinition()) &&
4152 "definition completed but not started");
4153
Erich Keanef92f31c2018-08-01 20:48:16 +00004154 setCompleteDefinition(true);
4155 setBeingDefined(false);
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00004156
4157 if (ASTMutationListener *L = getASTMutationListener())
4158 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00004159}
4160
John McCallf937c022011-10-07 06:10:15 +00004161TagDecl *TagDecl::getDefinition() const {
4162 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00004163 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00004164
4165 // If it's possible for us to have an out-of-date definition, check now.
Erich Keanef92f31c2018-08-01 20:48:16 +00004166 if (mayHaveOutOfDateDef()) {
Douglas Gregor7dab26b2013-02-09 01:35:03 +00004167 if (IdentifierInfo *II = getIdentifier()) {
4168 if (II->isOutOfDate()) {
4169 updateOutOfDate(*II);
4170 }
4171 }
4172 }
4173
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004174 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
Andrew Trickba266ee2010-10-19 21:54:32 +00004175 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00004176
Aaron Ballman86c93902014-03-06 23:45:36 +00004177 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00004178 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00004179 return R;
Mike Stump11289f42009-09-09 15:08:12 +00004180
Craig Topper36250ad2014-05-12 05:36:57 +00004181 return nullptr;
Ted Kremenek21475702008-09-05 17:16:31 +00004182}
4183
Douglas Gregor14454802011-02-25 02:25:35 +00004184void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
4185 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00004186 // Make sure the extended qualifier info is allocated.
4187 if (!hasExtInfo())
David Majnemer00350522015-08-31 18:48:39 +00004188 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00004189 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00004190 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004191 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00004192 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00004193 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00004194 if (getExtInfo()->NumTemplParamLists == 0) {
4195 getASTContext().Deallocate(getExtInfo());
David Majnemer00350522015-08-31 18:48:39 +00004196 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
Abramo Bagnara60804e12011-03-18 15:16:37 +00004197 }
4198 else
4199 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00004200 }
4201 }
4202}
4203
Benjamin Kramer9cc210652015-08-05 09:40:49 +00004204void TagDecl::setTemplateParameterListsInfo(
4205 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
4206 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00004207 // Make sure the extended decl info is allocated.
4208 if (!hasExtInfo())
4209 // Allocate external info struct.
David Majnemer00350522015-08-31 18:48:39 +00004210 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00004211 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00004212 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00004213}
4214
Ted Kremenek21475702008-09-05 17:16:31 +00004215//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00004216// EnumDecl Implementation
4217//===----------------------------------------------------------------------===//
4218
Erich Keanef92f31c2018-08-01 20:48:16 +00004219EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4220 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
4221 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
4222 : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4223 assert(Scoped || !ScopedUsingClassTag);
4224 IntegerType = nullptr;
4225 setNumPositiveBits(0);
4226 setNumNegativeBits(0);
4227 setScoped(Scoped);
4228 setScopedUsingClassTag(ScopedUsingClassTag);
4229 setFixed(Fixed);
4230 setHasODRHash(false);
4231 ODRHash = 0;
4232}
4233
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004234void EnumDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004235
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004236EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
4237 SourceLocation StartLoc, SourceLocation IdLoc,
4238 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00004239 EnumDecl *PrevDecl, bool IsScoped,
4240 bool IsScopedUsingClassTag, bool IsFixed) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004241 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
4242 IsScoped, IsScopedUsingClassTag, IsFixed);
Erich Keanef92f31c2018-08-01 20:48:16 +00004243 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
Sebastian Redl833ef452010-01-26 22:01:41 +00004244 C.getTypeDeclType(Enum, PrevDecl);
4245 return Enum;
4246}
4247
Douglas Gregor72172e92012-01-05 21:55:30 +00004248EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004249 EnumDecl *Enum =
4250 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
4251 nullptr, nullptr, false, false, false);
Erich Keanef92f31c2018-08-01 20:48:16 +00004252 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00004253 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00004254}
4255
Alp Tokerb9fa5122014-01-06 11:31:18 +00004256SourceRange EnumDecl::getIntegerTypeRange() const {
4257 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
4258 return TI->getTypeLoc().getSourceRange();
4259 return SourceRange();
4260}
4261
Douglas Gregord5058122010-02-11 01:19:42 +00004262void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00004263 QualType NewPromotionType,
4264 unsigned NumPositiveBits,
4265 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00004266 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00004267 if (!IntegerType)
4268 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00004269 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00004270 setNumPositiveBits(NumPositiveBits);
4271 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00004272 TagDecl::completeDefinition();
4273}
4274
Akira Hatanaka3c268af2017-03-21 02:23:00 +00004275bool EnumDecl::isClosed() const {
4276 if (const auto *A = getAttr<EnumExtensibilityAttr>())
4277 return A->getExtensibility() == EnumExtensibilityAttr::Closed;
4278 return true;
4279}
4280
4281bool EnumDecl::isClosedFlag() const {
4282 return isClosed() && hasAttr<FlagEnumAttr>();
4283}
4284
4285bool EnumDecl::isClosedNonFlag() const {
4286 return isClosed() && !hasAttr<FlagEnumAttr>();
4287}
4288
Richard Smith7d137e32012-03-23 03:33:32 +00004289TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
4290 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
4291 return MSI->getTemplateSpecializationKind();
4292
4293 return TSK_Undeclared;
4294}
4295
4296void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4297 SourceLocation PointOfInstantiation) {
4298 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
4299 assert(MSI && "Not an instantiated member enumeration?");
4300 MSI->setTemplateSpecializationKind(TSK);
4301 if (TSK != TSK_ExplicitSpecialization &&
4302 PointOfInstantiation.isValid() &&
4303 MSI->getPointOfInstantiation().isInvalid())
4304 MSI->setPointOfInstantiation(PointOfInstantiation);
4305}
4306
Richard Smith6739a102016-05-05 00:56:12 +00004307EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
4308 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
4309 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
4310 EnumDecl *ED = getInstantiatedFromMemberEnum();
4311 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
4312 ED = NewED;
Richard Smith2195ec92017-04-21 01:15:13 +00004313 return getDefinitionOrSelf(ED);
Richard Smith6739a102016-05-05 00:56:12 +00004314 }
4315 }
4316
4317 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
4318 "couldn't find pattern for enum instantiation");
4319 return nullptr;
4320}
4321
Richard Smith4b38ded2012-03-14 23:13:10 +00004322EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
4323 if (SpecializationInfo)
4324 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
4325
Craig Topper36250ad2014-05-12 05:36:57 +00004326 return nullptr;
Richard Smith4b38ded2012-03-14 23:13:10 +00004327}
4328
4329void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
4330 TemplateSpecializationKind TSK) {
4331 assert(!SpecializationInfo && "Member enum is already a specialization");
4332 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
4333}
4334
Richard Trieuab4d7302018-07-25 22:52:05 +00004335unsigned EnumDecl::getODRHash() {
Erich Keanef92f31c2018-08-01 20:48:16 +00004336 if (hasODRHash())
Richard Trieuab4d7302018-07-25 22:52:05 +00004337 return ODRHash;
4338
4339 class ODRHash Hash;
4340 Hash.AddEnumDecl(this);
Erich Keanef92f31c2018-08-01 20:48:16 +00004341 setHasODRHash(true);
Richard Trieuab4d7302018-07-25 22:52:05 +00004342 ODRHash = Hash.CalculateHash();
4343 return ODRHash;
4344}
4345
Sebastian Redl833ef452010-01-26 22:01:41 +00004346//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00004347// RecordDecl Implementation
4348//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00004349
Richard Smith053f6c62014-05-16 23:01:30 +00004350RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
4351 DeclContext *DC, SourceLocation StartLoc,
4352 SourceLocation IdLoc, IdentifierInfo *Id,
4353 RecordDecl *PrevDecl)
Erich Keanef92f31c2018-08-01 20:48:16 +00004354 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4355 assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
4356 setHasFlexibleArrayMember(false);
4357 setAnonymousStructOrUnion(false);
4358 setHasObjectMember(false);
4359 setHasVolatileMember(false);
4360 setHasLoadedFieldsFromExternalStorage(false);
4361 setNonTrivialToPrimitiveDefaultInitialize(false);
4362 setNonTrivialToPrimitiveCopy(false);
4363 setNonTrivialToPrimitiveDestroy(false);
Akira Hatanaka09051062019-09-07 00:34:43 +00004364 setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false);
4365 setHasNonTrivialToPrimitiveDestructCUnion(false);
4366 setHasNonTrivialToPrimitiveCopyCUnion(false);
Erich Keanef92f31c2018-08-01 20:48:16 +00004367 setParamDestroyedInCallee(false);
4368 setArgPassingRestrictions(APK_CanPassInRegs);
Ted Kremenek52baf502008-09-02 21:12:32 +00004369}
4370
Jay Foad39c79802011-01-12 09:06:06 +00004371RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004372 SourceLocation StartLoc, SourceLocation IdLoc,
4373 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smith053f6c62014-05-16 23:01:30 +00004374 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
4375 StartLoc, IdLoc, Id, PrevDecl);
Erich Keanef92f31c2018-08-01 20:48:16 +00004376 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00004377
Ted Kremenek21475702008-09-05 17:16:31 +00004378 C.getTypeDeclType(R, PrevDecl);
4379 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00004380}
4381
Douglas Gregor72172e92012-01-05 21:55:30 +00004382RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004383 RecordDecl *R =
4384 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
4385 SourceLocation(), nullptr, nullptr);
Erich Keanef92f31c2018-08-01 20:48:16 +00004386 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00004387 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00004388}
4389
Douglas Gregordfcad112009-03-25 15:59:44 +00004390bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00004391 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00004392 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
4393}
4394
Alexey Bataev39c81e22014-08-28 04:28:19 +00004395bool RecordDecl::isLambda() const {
4396 if (auto RD = dyn_cast<CXXRecordDecl>(this))
4397 return RD->isLambda();
4398 return false;
4399}
4400
Alexey Bataev330de032014-10-29 12:21:55 +00004401bool RecordDecl::isCapturedRecord() const {
4402 return hasAttr<CapturedRecordAttr>();
4403}
4404
4405void RecordDecl::setCapturedRecord() {
4406 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
4407}
4408
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004409RecordDecl::field_iterator RecordDecl::field_begin() const {
Erich Keanef92f31c2018-08-01 20:48:16 +00004410 if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004411 LoadFieldsFromExternalStorage();
4412
4413 return field_iterator(decl_iterator(FirstDecl));
4414}
4415
Douglas Gregorb11aad82011-02-19 18:51:44 +00004416/// completeDefinition - Notes that the definition of this type is now
4417/// complete.
4418void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00004419 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00004420 TagDecl::completeDefinition();
4421}
4422
Eli Friedman9ee2d0472012-10-12 23:29:20 +00004423/// isMsStruct - Get whether or not this record uses ms_struct layout.
4424/// This which can be turned on with an attribute, pragma, or the
4425/// -mms-bitfields command-line option.
4426bool RecordDecl::isMsStruct(const ASTContext &C) const {
David Majnemer8ab003a2015-02-02 19:30:52 +00004427 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00004428}
4429
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004430void RecordDecl::LoadFieldsFromExternalStorage() const {
4431 ExternalASTSource *Source = getASTContext().getExternalSource();
4432 assert(hasExternalLexicalStorage() && Source && "No external storage?");
4433
4434 // Notify that we have a RecordDecl doing some initialization.
4435 ExternalASTSource::Deserializing TheFields(Source);
4436
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004437 SmallVector<Decl*, 64> Decls;
Erich Keanef92f31c2018-08-01 20:48:16 +00004438 setHasLoadedFieldsFromExternalStorage(true);
Richard Smith3cb15722015-08-05 22:41:45 +00004439 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
4440 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
4441 }, Decls);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004442
4443#ifndef NDEBUG
4444 // Check that all decls we got were FieldDecls.
4445 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00004446 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004447#endif
4448
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004449 if (Decls.empty())
4450 return;
4451
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00004452 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00004453 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004454}
4455
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004456bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
4457 ASTContext &Context = getASTContext();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004458 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
4459 (SanitizerKind::Address | SanitizerKind::KernelAddress);
4460 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004461 return false;
Alexey Samsonov33e00e22014-10-16 23:50:26 +00004462 const auto &Blacklist = Context.getSanitizerBlacklist();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004463 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004464 // We may be able to relax some of these requirements.
4465 int ReasonToReject = -1;
4466 if (!CXXRD || CXXRD->isExternCContext())
4467 ReasonToReject = 0; // is not C++.
4468 else if (CXXRD->hasAttr<PackedAttr>())
4469 ReasonToReject = 1; // is packed.
4470 else if (CXXRD->isUnion())
4471 ReasonToReject = 2; // is a union.
4472 else if (CXXRD->isTriviallyCopyable())
4473 ReasonToReject = 3; // is trivially copyable.
4474 else if (CXXRD->hasTrivialDestructor())
4475 ReasonToReject = 4; // has trivial destructor.
4476 else if (CXXRD->isStandardLayout())
4477 ReasonToReject = 5; // is standard layout.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004478 else if (Blacklist.isBlacklistedLocation(EnabledAsanMask, getLocation(),
4479 "field-padding"))
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004480 ReasonToReject = 6; // is in a blacklisted file.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004481 else if (Blacklist.isBlacklistedType(EnabledAsanMask,
4482 getQualifiedNameAsString(),
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004483 "field-padding"))
4484 ReasonToReject = 7; // is blacklisted.
4485
4486 if (EmitRemark) {
4487 if (ReasonToReject >= 0)
4488 Context.getDiagnostics().Report(
4489 getLocation(),
4490 diag::remark_sanitize_address_insert_extra_padding_rejected)
4491 << getQualifiedNameAsString() << ReasonToReject;
4492 else
4493 Context.getDiagnostics().Report(
4494 getLocation(),
4495 diag::remark_sanitize_address_insert_extra_padding_accepted)
4496 << getQualifiedNameAsString();
4497 }
4498 return ReasonToReject < 0;
4499}
4500
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004501const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
4502 for (const auto *I : fields()) {
4503 if (I->getIdentifier())
4504 return I;
4505
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004506 if (const auto *RT = I->getType()->getAs<RecordType>())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004507 if (const FieldDecl *NamedDataMember =
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004508 RT->getDecl()->findFirstNamedDataMember())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004509 return NamedDataMember;
4510 }
4511
4512 // We didn't find a named data member.
4513 return nullptr;
4514}
4515
Steve Naroff415d3d52008-10-08 17:01:13 +00004516//===----------------------------------------------------------------------===//
4517// BlockDecl Implementation
4518//===----------------------------------------------------------------------===//
4519
Erich Keanec9d29902018-08-01 21:16:54 +00004520BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
4521 : Decl(Block, DC, CaretLoc), DeclContext(Block) {
4522 setIsVariadic(false);
4523 setCapturesCXXThis(false);
4524 setBlockMissingReturnType(true);
4525 setIsConversionFromLambda(false);
4526 setDoesNotEscape(false);
Akira Hatanakac5792aa2019-02-27 18:17:16 +00004527 setCanAvoidCopyToHeap(false);
Erich Keanec9d29902018-08-01 21:16:54 +00004528}
4529
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004530void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00004531 assert(!ParamInfo && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00004532
Steve Naroffc4b30e52009-03-13 16:56:44 +00004533 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00004534 if (!NewParamInfo.empty()) {
4535 NumParams = NewParamInfo.size();
4536 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
4537 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00004538 }
4539}
4540
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004541void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4542 bool CapturesCXXThis) {
Erich Keanec9d29902018-08-01 21:16:54 +00004543 this->setCapturesCXXThis(CapturesCXXThis);
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004544 this->NumCaptures = Captures.size();
John McCallc63de662011-02-02 13:00:07 +00004545
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004546 if (Captures.empty()) {
4547 this->Captures = nullptr;
John McCallc63de662011-02-02 13:00:07 +00004548 return;
4549 }
4550
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004551 this->Captures = Captures.copy(Context).data();
Steve Naroffc4b30e52009-03-13 16:56:44 +00004552}
Sebastian Redl833ef452010-01-26 22:01:41 +00004553
John McCallce45f882011-06-15 22:51:16 +00004554bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00004555 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00004556 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00004557 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00004558 return true;
4559
4560 return false;
4561}
4562
Douglas Gregor70226da2010-12-21 16:27:07 +00004563SourceRange BlockDecl::getSourceRange() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004564 return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
Douglas Gregor70226da2010-12-21 16:27:07 +00004565}
Sebastian Redl833ef452010-01-26 22:01:41 +00004566
4567//===----------------------------------------------------------------------===//
4568// Other Decl Allocation/Deallocation Method Implementations
4569//===----------------------------------------------------------------------===//
4570
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004571void TranslationUnitDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004572
Sebastian Redl833ef452010-01-26 22:01:41 +00004573TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Craig Topper36250ad2014-05-12 05:36:57 +00004574 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00004575}
4576
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004577void PragmaCommentDecl::anchor() {}
Nico Weber66220292016-03-02 17:28:48 +00004578
4579PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4580 TranslationUnitDecl *DC,
4581 SourceLocation CommentLoc,
4582 PragmaMSCommentKind CommentKind,
4583 StringRef Arg) {
4584 PragmaCommentDecl *PCD =
4585 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4586 PragmaCommentDecl(DC, CommentLoc, CommentKind);
4587 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4588 PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4589 return PCD;
4590}
4591
4592PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4593 unsigned ID,
4594 unsigned ArgSize) {
4595 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
4596 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
4597}
4598
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004599void PragmaDetectMismatchDecl::anchor() {}
Nico Webercbbaeb12016-03-02 19:28:54 +00004600
4601PragmaDetectMismatchDecl *
4602PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4603 SourceLocation Loc, StringRef Name,
4604 StringRef Value) {
4605 size_t ValueStart = Name.size() + 1;
4606 PragmaDetectMismatchDecl *PDMD =
4607 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4608 PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4609 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4610 PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4611 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4612 Value.size());
4613 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4614 return PDMD;
4615}
4616
4617PragmaDetectMismatchDecl *
4618PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4619 unsigned NameValueSize) {
4620 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4621 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4622}
Nico Weber66220292016-03-02 17:28:48 +00004623
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004624void ExternCContextDecl::anchor() {}
Richard Smithf19e1272015-03-07 00:04:49 +00004625
4626ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4627 TranslationUnitDecl *DC) {
4628 return new (C, DC) ExternCContextDecl(DC);
4629}
4630
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004631void LabelDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004632
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004633LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004634 SourceLocation IdentL, IdentifierInfo *II) {
Craig Topper36250ad2014-05-12 05:36:57 +00004635 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004636}
4637
4638LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4639 SourceLocation IdentL, IdentifierInfo *II,
4640 SourceLocation GnuLabelL) {
4641 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Craig Topper36250ad2014-05-12 05:36:57 +00004642 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004643}
4644
Douglas Gregor72172e92012-01-05 21:55:30 +00004645LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004646 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
4647 SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00004648}
4649
Ehsan Akhgari31097582014-09-22 02:21:54 +00004650void LabelDecl::setMSAsmLabel(StringRef Name) {
Saar Razfdf80e82019-12-06 01:30:21 +02004651char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
Ehsan Akhgari31097582014-09-22 02:21:54 +00004652 memcpy(Buffer, Name.data(), Name.size());
4653 Buffer[Name.size()] = '\0';
4654 MSAsmName = Buffer;
4655}
4656
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004657void ValueDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004658
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004659bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00004660 for (const auto *I : attrs())
4661 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004662 return true;
4663
4664 return isWeakImported();
4665}
4666
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004667void ImplicitParamDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004668
Sebastian Redl833ef452010-01-26 22:01:41 +00004669ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004670 SourceLocation IdLoc,
Alexey Bataev56223232017-06-09 13:40:18 +00004671 IdentifierInfo *Id, QualType Type,
4672 ImplicitParamKind ParamKind) {
4673 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
4674}
4675
4676ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
4677 ImplicitParamKind ParamKind) {
4678 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
Sebastian Redl833ef452010-01-26 22:01:41 +00004679}
4680
Richard Smithf7981722013-11-22 09:01:48 +00004681ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004682 unsigned ID) {
Alexey Bataev56223232017-06-09 13:40:18 +00004683 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
Douglas Gregor72172e92012-01-05 21:55:30 +00004684}
4685
Sebastian Redl833ef452010-01-26 22:01:41 +00004686FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004687 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004688 const DeclarationNameInfo &NameInfo,
4689 QualType T, TypeSourceInfo *TInfo,
Gauthier Harnisch796ed032019-06-14 08:56:20 +00004690 StorageClass SC, bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00004691 bool hasWrittenPrototype,
Saar Razb65b1f32020-01-09 15:07:51 +02004692 ConstexprSpecKind ConstexprKind,
4693 Expr *TrailingRequiresClause) {
Richard Smithf7981722013-11-22 09:01:48 +00004694 FunctionDecl *New =
Richard Smith053f6c62014-05-16 23:01:30 +00004695 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
Saar Razb65b1f32020-01-09 15:07:51 +02004696 SC, isInlineSpecified, ConstexprKind,
4697 TrailingRequiresClause);
Erich Keane9c665062018-08-01 21:02:40 +00004698 New->setHasWrittenPrototype(hasWrittenPrototype);
Sebastian Redl833ef452010-01-26 22:01:41 +00004699 return New;
4700}
4701
Douglas Gregor72172e92012-01-05 21:55:30 +00004702FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004703 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004704 DeclarationNameInfo(), QualType(), nullptr,
Saar Razb65b1f32020-01-09 15:07:51 +02004705 SC_None, false, CSK_unspecified, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004706}
4707
Sebastian Redl833ef452010-01-26 22:01:41 +00004708BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004709 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00004710}
4711
Douglas Gregor72172e92012-01-05 21:55:30 +00004712BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004713 return new (C, ID) BlockDecl(nullptr, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00004714}
4715
Chandler Carruth21c90602015-12-30 03:24:14 +00004716CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
4717 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4718 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
4719
Ben Langmuir37943a72013-05-03 19:00:33 +00004720CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
4721 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004722 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Richard Smithf7981722013-11-22 09:01:48 +00004723 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004724}
4725
Ben Langmuirce914fc2013-05-03 19:20:19 +00004726CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00004727 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004728 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Craig Topper36250ad2014-05-12 05:36:57 +00004729 CapturedDecl(nullptr, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00004730}
4731
Chandler Carruth21c90602015-12-30 03:24:14 +00004732Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4733void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4734
4735bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4736void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4737
Sebastian Redl833ef452010-01-26 22:01:41 +00004738EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4739 SourceLocation L,
4740 IdentifierInfo *Id, QualType T,
4741 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00004742 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00004743}
4744
Douglas Gregor72172e92012-01-05 21:55:30 +00004745EnumConstantDecl *
4746EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004747 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4748 QualType(), nullptr, llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00004749}
4750
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004751void IndirectFieldDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004752
Richard Smith9f951822016-01-06 22:49:11 +00004753IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4754 SourceLocation L, DeclarationName N,
David Majnemer59f77922016-06-24 04:05:48 +00004755 QualType T,
4756 MutableArrayRef<NamedDecl *> CH)
4757 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4758 ChainingSize(CH.size()) {
Richard Smith9f951822016-01-06 22:49:11 +00004759 // In C++, indirect field declarations conflict with tag declarations in the
4760 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4761 if (C.getLangOpts().CPlusPlus)
4762 IdentifierNamespace |= IDNS_Tag;
4763}
4764
Benjamin Kramer39593702010-11-21 14:11:41 +00004765IndirectFieldDecl *
4766IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
David Majnemer59f77922016-06-24 04:05:48 +00004767 IdentifierInfo *Id, QualType T,
4768 llvm::MutableArrayRef<NamedDecl *> CH) {
4769 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
Francois Pichet783dd6e2010-11-21 06:08:52 +00004770}
4771
Douglas Gregor72172e92012-01-05 21:55:30 +00004772IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4773 unsigned ID) {
Richard Smith9f951822016-01-06 22:49:11 +00004774 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
David Majnemer59f77922016-06-24 04:05:48 +00004775 DeclarationName(), QualType(), None);
Douglas Gregor72172e92012-01-05 21:55:30 +00004776}
4777
Douglas Gregorbe996932010-09-01 20:41:53 +00004778SourceRange EnumConstantDecl::getSourceRange() const {
4779 SourceLocation End = getLocation();
4780 if (Init)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004781 End = Init->getEndLoc();
Douglas Gregorbe996932010-09-01 20:41:53 +00004782 return SourceRange(getLocation(), End);
4783}
4784
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004785void TypeDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004786
Sebastian Redl833ef452010-01-26 22:01:41 +00004787TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00004788 SourceLocation StartLoc, SourceLocation IdLoc,
4789 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004790 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00004791}
4792
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004793void TypedefNameDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004794
Richard Smith42413142015-05-15 20:05:43 +00004795TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4796 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4797 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4798 auto *ThisTypedef = this;
4799 if (AnyRedecl && OwningTypedef) {
4800 OwningTypedef = OwningTypedef->getCanonicalDecl();
4801 ThisTypedef = ThisTypedef->getCanonicalDecl();
4802 }
4803 if (OwningTypedef == ThisTypedef)
Richard Smitha5230222015-03-27 01:37:43 +00004804 return TT->getDecl();
Richard Smith42413142015-05-15 20:05:43 +00004805 }
Richard Smitha5230222015-03-27 01:37:43 +00004806
4807 return nullptr;
4808}
4809
Argyrios Kyrtzidis3b25c912017-03-21 16:56:02 +00004810bool TypedefNameDecl::isTransparentTagSlow() const {
4811 auto determineIsTransparent = [&]() {
4812 if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
4813 if (auto *TD = TT->getDecl()) {
4814 if (TD->getName() != getName())
4815 return false;
4816 SourceLocation TTLoc = getLocation();
4817 SourceLocation TDLoc = TD->getLocation();
4818 if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
4819 return false;
4820 SourceManager &SM = getASTContext().getSourceManager();
4821 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
4822 }
4823 }
4824 return false;
4825 };
4826
4827 bool isTransparent = determineIsTransparent();
Benjamin Kramerdfb730a2018-01-26 14:14:11 +00004828 MaybeModedTInfo.setInt((isTransparent << 1) | 1);
Argyrios Kyrtzidis3b25c912017-03-21 16:56:02 +00004829 return isTransparent;
4830}
4831
Douglas Gregor72172e92012-01-05 21:55:30 +00004832TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004833 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004834 nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004835}
4836
Richard Smithdda56e42011-04-15 14:24:37 +00004837TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4838 SourceLocation StartLoc,
4839 SourceLocation IdLoc, IdentifierInfo *Id,
4840 TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004841 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00004842}
4843
Douglas Gregor72172e92012-01-05 21:55:30 +00004844TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004845 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
4846 SourceLocation(), nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004847}
4848
Abramo Bagnaraea947882011-03-08 16:41:52 +00004849SourceRange TypedefDecl::getSourceRange() const {
4850 SourceLocation RangeEnd = getLocation();
4851 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4852 if (typeIsPostfix(TInfo->getType()))
4853 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4854 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004855 return SourceRange(getBeginLoc(), RangeEnd);
Abramo Bagnaraea947882011-03-08 16:41:52 +00004856}
4857
Richard Smithdda56e42011-04-15 14:24:37 +00004858SourceRange TypeAliasDecl::getSourceRange() const {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004859 SourceLocation RangeEnd = getBeginLoc();
Richard Smithdda56e42011-04-15 14:24:37 +00004860 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4861 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004862 return SourceRange(getBeginLoc(), RangeEnd);
Richard Smithdda56e42011-04-15 14:24:37 +00004863}
4864
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004865void FileScopeAsmDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004866
Sebastian Redl833ef452010-01-26 22:01:41 +00004867FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00004868 StringLiteral *Str,
4869 SourceLocation AsmLoc,
4870 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00004871 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00004872}
Douglas Gregorba345522011-12-02 23:23:56 +00004873
Richard Smithf7981722013-11-22 09:01:48 +00004874FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004875 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004876 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4877 SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00004878}
4879
Michael Han84324352013-02-22 17:15:32 +00004880void EmptyDecl::anchor() {}
4881
4882EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004883 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00004884}
4885
4886EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004887 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00004888}
4889
Douglas Gregorba345522011-12-02 23:23:56 +00004890//===----------------------------------------------------------------------===//
4891// ImportDecl Implementation
4892//===----------------------------------------------------------------------===//
4893
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004894/// Retrieve the number of module identifiers needed to name the given
Douglas Gregorba345522011-12-02 23:23:56 +00004895/// module.
4896static unsigned getNumModuleIdentifiers(Module *Mod) {
4897 unsigned Result = 1;
4898 while (Mod->Parent) {
4899 Mod = Mod->Parent;
4900 ++Result;
4901 }
4902 return Result;
4903}
4904
Fangrui Song6907ce22018-07-30 19:24:48 +00004905ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004906 Module *Imported,
4907 ArrayRef<SourceLocation> IdentifierLocs)
Reid Klecknerc915cb92020-02-27 18:13:54 -08004908 : Decl(Import, DC, StartLoc), ImportedModule(Imported),
4909 NextLocalImportAndComplete(nullptr, true) {
Douglas Gregorba345522011-12-02 23:23:56 +00004910 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004911 auto *StoredLocs = getTrailingObjects<SourceLocation>();
James Y Knight7a22b242015-08-06 20:26:32 +00004912 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4913 StoredLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004914}
4915
Fangrui Song6907ce22018-07-30 19:24:48 +00004916ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004917 Module *Imported, SourceLocation EndLoc)
Reid Klecknerc915cb92020-02-27 18:13:54 -08004918 : Decl(Import, DC, StartLoc), ImportedModule(Imported),
4919 NextLocalImportAndComplete(nullptr, false) {
James Y Knight7a22b242015-08-06 20:26:32 +00004920 *getTrailingObjects<SourceLocation>() = EndLoc;
Douglas Gregorba345522011-12-02 23:23:56 +00004921}
4922
Richard Smithf7981722013-11-22 09:01:48 +00004923ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004924 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004925 ArrayRef<SourceLocation> IdentifierLocs) {
James Y Knight7a22b242015-08-06 20:26:32 +00004926 return new (C, DC,
4927 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
Richard Smithf7981722013-11-22 09:01:48 +00004928 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004929}
4930
Richard Smithf7981722013-11-22 09:01:48 +00004931ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004932 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00004933 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004934 SourceLocation EndLoc) {
James Y Knight7a22b242015-08-06 20:26:32 +00004935 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
4936 ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00004937 Import->setImplicit();
4938 return Import;
4939}
4940
Douglas Gregor72172e92012-01-05 21:55:30 +00004941ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4942 unsigned NumLocations) {
James Y Knight7a22b242015-08-06 20:26:32 +00004943 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
Richard Smithf7981722013-11-22 09:01:48 +00004944 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00004945}
4946
4947ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
Reid Klecknerc915cb92020-02-27 18:13:54 -08004948 if (!isImportComplete())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004949 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00004950
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004951 const auto *StoredLocs = getTrailingObjects<SourceLocation>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00004952 return llvm::makeArrayRef(StoredLocs,
4953 getNumModuleIdentifiers(getImportedModule()));
Douglas Gregorba345522011-12-02 23:23:56 +00004954}
4955
4956SourceRange ImportDecl::getSourceRange() const {
Reid Klecknerc915cb92020-02-27 18:13:54 -08004957 if (!isImportComplete())
James Y Knight7a22b242015-08-06 20:26:32 +00004958 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
4959
Douglas Gregorba345522011-12-02 23:23:56 +00004960 return SourceRange(getLocation(), getIdentifierLocs().back());
4961}
Richard Smith8df390f2016-09-08 23:14:54 +00004962
4963//===----------------------------------------------------------------------===//
4964// ExportDecl Implementation
4965//===----------------------------------------------------------------------===//
4966
4967void ExportDecl::anchor() {}
4968
4969ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
4970 SourceLocation ExportLoc) {
4971 return new (C, DC) ExportDecl(DC, ExportLoc);
4972}
4973
4974ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4975 return new (C, ID) ExportDecl(nullptr, SourceLocation());
4976}