blob: 3723c868004fe3c10223bd8be7b13436e590dd03 [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"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000019#include "clang/AST/CanonicalType.h"
20#include "clang/AST/DeclBase.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000023#include "clang/AST/DeclOpenMP.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/DeclTemplate.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000025#include "clang/AST/DeclarationName.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000026#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000027#include "clang/AST/ExprCXX.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000028#include "clang/AST/ExternalASTSource.h"
Richard Trieue6caa262017-12-23 00:41:01 +000029#include "clang/AST/ODRHash.h"
Jordan Rose1e879d82018-03-23 00:07:18 +000030#include "clang/AST/PrettyDeclStackTrace.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000031#include "clang/AST/PrettyPrinter.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000032#include "clang/AST/Redeclarable.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000033#include "clang/AST/Stmt.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000034#include "clang/AST/TemplateBase.h"
35#include "clang/AST/Type.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000036#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000037#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000038#include "clang/Basic/IdentifierTable.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000039#include "clang/Basic/LLVM.h"
40#include "clang/Basic/LangOptions.h"
41#include "clang/Basic/Linkage.h"
Douglas Gregorba345522011-12-02 23:23:56 +000042#include "clang/Basic/Module.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000043#include "clang/Basic/PartialDiagnostic.h"
44#include "clang/Basic/SanitizerBlacklist.h"
45#include "clang/Basic/Sanitizers.h"
46#include "clang/Basic/SourceLocation.h"
47#include "clang/Basic/SourceManager.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000048#include "clang/Basic/Specifiers.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000049#include "clang/Basic/TargetCXXABI.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000050#include "clang/Basic/TargetInfo.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000051#include "clang/Basic/Visibility.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000052#include "llvm/ADT/APSInt.h"
53#include "llvm/ADT/ArrayRef.h"
54#include "llvm/ADT/None.h"
55#include "llvm/ADT/Optional.h"
56#include "llvm/ADT/STLExtras.h"
57#include "llvm/ADT/SmallVector.h"
58#include "llvm/ADT/StringSwitch.h"
59#include "llvm/ADT/StringRef.h"
60#include "llvm/ADT/Triple.h"
61#include "llvm/Support/Casting.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000062#include "llvm/Support/ErrorHandling.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000063#include "llvm/Support/raw_ostream.h"
David Blaikie9c70e042011-09-21 18:16:56 +000064#include <algorithm>
Eugene Zelenkode0215c2017-11-13 23:01:27 +000065#include <cassert>
66#include <cstddef>
67#include <cstring>
68#include <memory>
69#include <string>
70#include <tuple>
71#include <type_traits>
David Blaikie9c70e042011-09-21 18:16:56 +000072
Chris Lattner6d9a6852006-10-25 05:11:20 +000073using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000074
Richard Smith0b87e072013-10-07 08:02:11 +000075Decl *clang::getPrimaryMergedDecl(Decl *D) {
76 return D->getASTContext().getPrimaryMergedDecl(D);
77}
78
Jordan Rose1e879d82018-03-23 00:07:18 +000079void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
80 SourceLocation Loc = this->Loc;
81 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
82 if (Loc.isValid()) {
83 Loc.print(OS, Context.getSourceManager());
84 OS << ": ";
85 }
86 OS << Message;
87
88 if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
89 OS << " '";
90 ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
91 OS << "'";
92 }
93
94 OS << '\n';
95}
96
Richard Smith73b21d82014-09-03 02:33:22 +000097// Defined here so that it can be inlined into its direct callers.
98bool Decl::isOutOfLine() const {
99 return !getLexicalDeclContext()->Equals(getDeclContext());
100}
101
Richard Smith42413142015-05-15 20:05:43 +0000102TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
103 : Decl(TranslationUnit, nullptr, SourceLocation()),
Eugene Zelenkode0215c2017-11-13 23:01:27 +0000104 DeclContext(TranslationUnit), Ctx(ctx) {}
Richard Smith42413142015-05-15 20:05:43 +0000105
Chris Lattner88f70d62008-03-15 05:43:15 +0000106//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000107// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000108//===----------------------------------------------------------------------===//
109
John McCalldf25c432013-02-16 00:17:33 +0000110// Visibility rules aren't rigorously externally specified, but here
111// are the basic principles behind what we implement:
112//
113// 1. An explicit visibility attribute is generally a direct expression
114// of the user's intent and should be honored. Only the innermost
115// visibility attribute applies. If no visibility attribute applies,
116// global visibility settings are considered.
117//
118// 2. There is one caveat to the above: on or in a template pattern,
119// an explicit visibility attribute is just a default rule, and
120// visibility can be decreased by the visibility of template
121// arguments. But this, too, has an exception: an attribute on an
122// explicit specialization or instantiation causes all the visibility
123// restrictions of the template arguments to be ignored.
124//
125// 3. A variable that does not otherwise have explicit visibility can
126// be restricted by the visibility of its type.
127//
128// 4. A visibility restriction is explicit if it comes from an
129// attribute (or something like it), not a global visibility setting.
130// When emitting a reference to an external symbol, visibility
131// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +0000132//
133// 5. When computing the visibility of a non-type, including a
134// non-type member of a class, only non-type visibility restrictions
135// are considered: the 'visibility' attribute, global value-visibility
136// settings, and a few special cases like __private_extern.
137//
138// 6. When computing the visibility of a type, including a type member
139// of a class, only type visibility restrictions are considered:
140// the 'type_visibility' attribute and global type-visibility settings.
141// However, a 'visibility' attribute counts as a 'type_visibility'
142// attribute on any declaration that only has the former.
143//
144// The visibility of a "secondary" entity, like a template argument,
145// is computed using the kind of that entity, not the kind of the
146// primary entity for which we are computing visibility. For example,
147// the visibility of a specialization of either of these templates:
148// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
149// template <class T, bool (&compare)(T, X)> class matcher;
150// is restricted according to the type visibility of the argument 'T',
151// the type visibility of 'bool(&)(T,X)', and the value visibility of
152// the argument function 'compare'. That 'has_match' is a value
153// and 'matcher' is a type only matters when looking for attributes
154// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +0000155
John McCalld041a9b2013-02-20 01:54:26 +0000156/// Does this computation kind permit us to consider additional
157/// visibility settings from attributes and the like?
158static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000159 return computation.IgnoreExplicitVisibility;
John McCalld041a9b2013-02-20 01:54:26 +0000160}
161
162/// Given an LVComputationKind, return one of the same type/value sort
163/// that records that it already has explicit visibility.
164static LVComputationKind
Richard Smithfbe7b462017-09-22 02:22:32 +0000165withExplicitVisibilityAlready(LVComputationKind Kind) {
166 Kind.IgnoreExplicitVisibility = true;
167 return Kind;
John McCalld041a9b2013-02-20 01:54:26 +0000168}
169
David Blaikie05785d12013-02-20 22:23:23 +0000170static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
171 LVComputationKind kind) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000172 assert(!kind.IgnoreExplicitVisibility &&
John McCalld041a9b2013-02-20 01:54:26 +0000173 "asking for explicit visibility when we shouldn't be");
Richard Smithfbe7b462017-09-22 02:22:32 +0000174 return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
John McCalld041a9b2013-02-20 01:54:26 +0000175}
176
John McCalldf25c432013-02-16 00:17:33 +0000177/// Is the given declaration a "type" or a "value" for the purposes of
178/// visibility computation?
179static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000180 return isa<TypeDecl>(D) ||
181 isa<ClassTemplateDecl>(D) ||
182 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000183}
184
John McCall5f46c482013-02-21 23:42:58 +0000185/// Does the given declaration have member specialization information,
186/// and if so, is it an explicit specialization?
187template <class T> static typename
Benjamin Kramered2f4762014-03-07 14:30:23 +0000188std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-02-21 23:42:58 +0000189isExplicitMemberSpecialization(const T *D) {
190 if (const MemberSpecializationInfo *member =
191 D->getMemberSpecializationInfo()) {
192 return member->isExplicitSpecialization();
193 }
194 return false;
195}
196
197/// For templates, this question is easier: a member template can't be
198/// explicitly instantiated, so there's a single bit indicating whether
199/// or not this is an explicit member specialization.
200static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
201 return D->isMemberSpecialization();
202}
203
John McCalld041a9b2013-02-20 01:54:26 +0000204/// Given a visibility attribute, return the explicit visibility
205/// associated with it.
206template <class T>
207static Visibility getVisibilityFromAttr(const T *attr) {
208 switch (attr->getVisibility()) {
209 case T::Default:
210 return DefaultVisibility;
211 case T::Hidden:
212 return HiddenVisibility;
213 case T::Protected:
214 return ProtectedVisibility;
215 }
216 llvm_unreachable("bad visibility kind");
217}
218
John McCalldf25c432013-02-16 00:17:33 +0000219/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000220static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000221 NamedDecl::ExplicitVisibilityKind kind) {
222 // If we're ultimately computing the visibility of a type, look for
223 // a 'type_visibility' attribute before looking for 'visibility'.
224 if (kind == NamedDecl::VisibilityForType) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000225 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000226 return getVisibilityFromAttr(A);
227 }
228 }
229
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000230 // If this declaration has an explicit visibility attribute, use it.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000231 if (const auto *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000232 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000233 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000234
David Blaikie7a30dc52013-02-21 01:47:18 +0000235 return None;
John McCall457a04e2010-10-22 21:05:15 +0000236}
237
George Burgess IV99db3ea2017-08-09 04:02:49 +0000238LinkageInfo LinkageComputer::getLVForType(const Type &T,
239 LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000240 if (computation.IgnoreAllVisibility)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000241 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
George Burgess IV35cb4f82017-08-09 04:12:17 +0000242 return getTypeLinkageAndVisibility(&T);
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000243}
244
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000245/// Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000246/// template parameter list. For visibility purposes, template
247/// parameters are part of the signature of a template.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000248LinkageInfo LinkageComputer::getLVForTemplateParameterList(
249 const TemplateParameterList *Params, LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000250 LinkageInfo LV;
David Majnemerc7b85c42014-04-23 05:16:48 +0000251 for (const NamedDecl *P : *Params) {
John McCalldf25c432013-02-16 00:17:33 +0000252 // Template type parameters are the most common and never
253 // contribute to visibility, pack or not.
David Majnemerc7b85c42014-04-23 05:16:48 +0000254 if (isa<TemplateTypeParmDecl>(P))
John McCalldf25c432013-02-16 00:17:33 +0000255 continue;
256
257 // Non-type template parameters can be restricted by the value type, e.g.
258 // template <enum X> class A { ... };
259 // We have to be careful here, though, because we can be dealing with
260 // dependent types.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000261 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
John McCalldf25c432013-02-16 00:17:33 +0000262 // Handle the non-pack case first.
263 if (!NTTP->isExpandedParameterPack()) {
264 if (!NTTP->getType()->isDependentType()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000265 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000266 }
267 continue;
268 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000269
John McCalldf25c432013-02-16 00:17:33 +0000270 // Look at all the types in an expanded pack.
271 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
272 QualType type = NTTP->getExpansionType(i);
273 if (!type->isDependentType())
George Burgess IV35cb4f82017-08-09 04:12:17 +0000274 LV.merge(getTypeLinkageAndVisibility(type));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000275 }
John McCalldf25c432013-02-16 00:17:33 +0000276 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000277 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000278
John McCalldf25c432013-02-16 00:17:33 +0000279 // Template template parameters can be restricted by their
280 // template parameters, recursively.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000281 const auto *TTP = cast<TemplateTemplateParmDecl>(P);
John McCalldf25c432013-02-16 00:17:33 +0000282
283 // Handle the non-pack case first.
284 if (!TTP->isExpandedParameterPack()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000285 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
286 computation));
John McCalldf25c432013-02-16 00:17:33 +0000287 continue;
288 }
289
290 // Look at all expansions in an expanded pack.
291 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
292 i != n; ++i) {
293 LV.merge(getLVForTemplateParameterList(
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000294 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000295 }
296 }
297
John McCall457a04e2010-10-22 21:05:15 +0000298 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000299}
300
Eli Friedman7e346a82013-07-01 20:22:57 +0000301static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
Craig Topper36250ad2014-05-12 05:36:57 +0000302 const Decl *Ret = nullptr;
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000303 const DeclContext *DC = D->getDeclContext();
304 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman7e346a82013-07-01 20:22:57 +0000305 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
306 Ret = cast<Decl>(DC);
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000307 DC = DC->getParent();
308 }
309 return Ret;
310}
311
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000312/// Get the most restrictive linkage for the types and
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000313/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000314///
315/// Note that we don't take an LVComputationKind because we always
316/// want to honor the visibility of template arguments in the same way.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000317LinkageInfo
318LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
319 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000320 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000321
David Majnemerc7b85c42014-04-23 05:16:48 +0000322 for (const TemplateArgument &Arg : Args) {
323 switch (Arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000324 case TemplateArgument::Null:
325 case TemplateArgument::Integral:
326 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000327 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000328
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000329 case TemplateArgument::Type:
David Majnemerc7b85c42014-04-23 05:16:48 +0000330 LV.merge(getLVForType(*Arg.getAsType(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000331 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000332
George Burgess IV00f70bd2018-03-01 05:43:23 +0000333 case TemplateArgument::Declaration: {
334 const NamedDecl *ND = Arg.getAsDecl();
335 assert(!usesTypeVisibility(ND));
336 LV.merge(getLVForDecl(ND, computation));
John McCalldf25c432013-02-16 00:17:33 +0000337 continue;
George Burgess IV00f70bd2018-03-01 05:43:23 +0000338 }
Eli Friedmanb826a002012-09-26 02:36:12 +0000339
340 case TemplateArgument::NullPtr:
George Burgess IV35cb4f82017-08-09 04:12:17 +0000341 LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
John McCalldf25c432013-02-16 00:17:33 +0000342 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000343
344 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000345 case TemplateArgument::TemplateExpansion:
David Majnemerc7b85c42014-04-23 05:16:48 +0000346 if (TemplateDecl *Template =
347 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000348 LV.merge(getLVForDecl(Template, computation));
John McCalldf25c432013-02-16 00:17:33 +0000349 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000350
351 case TemplateArgument::Pack:
David Majnemerc7b85c42014-04-23 05:16:48 +0000352 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000353 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000354 }
John McCalldf25c432013-02-16 00:17:33 +0000355 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000356 }
357
John McCall457a04e2010-10-22 21:05:15 +0000358 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000359}
360
George Burgess IV99db3ea2017-08-09 04:02:49 +0000361LinkageInfo
362LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
363 LVComputationKind computation) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000364 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall8823c652010-08-13 08:35:10 +0000365}
366
John McCall5f46c482013-02-21 23:42:58 +0000367static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
368 const FunctionTemplateSpecializationInfo *specInfo) {
369 // Include visibility from the template parameters and arguments
370 // only if this is not an explicit instantiation or specialization
371 // with direct explicit visibility. (Implicit instantiations won't
372 // have a direct attribute.)
373 if (!specInfo->isExplicitInstantiationOrSpecialization())
374 return true;
375
376 return !fn->hasAttr<VisibilityAttr>();
377}
378
John McCalldf25c432013-02-16 00:17:33 +0000379/// Merge in template-related linkage and visibility for the given
380/// function template specialization.
381///
382/// We don't need a computation kind here because we can assume
383/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000384///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000385/// \param[out] LV the computation to use for the parent
George Burgess IV99db3ea2017-08-09 04:02:49 +0000386void LinkageComputer::mergeTemplateLV(
387 LinkageInfo &LV, const FunctionDecl *fn,
388 const FunctionTemplateSpecializationInfo *specInfo,
389 LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000390 bool considerVisibility =
391 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000392
393 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000394 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000395 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000396 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000397 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
398
399 // Merge information from the template arguments.
400 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000401 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCalldf25c432013-02-16 00:17:33 +0000402 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000403}
404
John McCall5f46c482013-02-21 23:42:58 +0000405/// Does the given declaration have a direct visibility attribute
406/// that would match the given rules?
407static bool hasDirectVisibilityAttribute(const NamedDecl *D,
408 LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000409 if (computation.IgnoreAllVisibility)
John McCall5f46c482013-02-21 23:42:58 +0000410 return false;
Richard Smithfbe7b462017-09-22 02:22:32 +0000411
412 return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
413 D->hasAttr<VisibilityAttr>();
John McCall5f46c482013-02-21 23:42:58 +0000414}
415
John McCalld041a9b2013-02-20 01:54:26 +0000416/// Should we consider visibility associated with the template
417/// arguments and parameters of the given class template specialization?
418static bool shouldConsiderTemplateVisibility(
419 const ClassTemplateSpecializationDecl *spec,
420 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000421 // Include visibility from the template parameters and arguments
422 // only if this is not an explicit instantiation or specialization
423 // with direct explicit visibility (and note that implicit
424 // instantiations won't have a direct attribute).
425 //
426 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000427 // for an explicit specialization when computing the visibility of a
428 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000429 //
430 // This is a bit complex; let's unpack it.
431 //
432 // An explicit class specialization is an independent, top-level
433 // declaration. As such, if it or any of its members has an
434 // explicit visibility attribute, that must directly express the
435 // user's intent, and we should honor it. The same logic applies to
436 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000437
438 // Fast path: if this is not an explicit instantiation or
439 // specialization, we always want to consider template-related
440 // visibility restrictions.
441 if (!spec->isExplicitInstantiationOrSpecialization())
442 return true;
443
444 // This is the 'member thereof' check.
445 if (spec->isExplicitSpecialization() &&
446 hasExplicitVisibilityAlready(computation))
447 return false;
448
John McCall5f46c482013-02-21 23:42:58 +0000449 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000450}
451
452/// Merge in template-related linkage and visibility for the given
453/// class template specialization.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000454void LinkageComputer::mergeTemplateLV(
455 LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,
456 LVComputationKind computation) {
John McCalld041a9b2013-02-20 01:54:26 +0000457 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000458
459 // Merge information from the template parameters, but ignore
460 // visibility if we're only considering template arguments.
461
John McCalld041a9b2013-02-20 01:54:26 +0000462 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000463 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000464 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000465 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000466 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000467
468 // Merge information from the template arguments. We ignore
469 // template-argument visibility if we've got an explicit
470 // instantiation with a visibility attribute.
471 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000472 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000473 if (considerVisibility)
474 LV.mergeVisibility(argsLV);
475 LV.mergeExternalVisibility(argsLV);
John McCallb8c604a2011-06-27 23:06:04 +0000476}
477
Larisse Voufo5899e192014-07-02 23:08:34 +0000478/// Should we consider visibility associated with the template
479/// arguments and parameters of the given variable template
480/// specialization? As usual, follow class template specialization
481/// logic up to initialization.
482static bool shouldConsiderTemplateVisibility(
483 const VarTemplateSpecializationDecl *spec,
484 LVComputationKind computation) {
485 // Include visibility from the template parameters and arguments
486 // only if this is not an explicit instantiation or specialization
487 // with direct explicit visibility (and note that implicit
488 // instantiations won't have a direct attribute).
489 if (!spec->isExplicitInstantiationOrSpecialization())
490 return true;
491
492 // An explicit variable specialization is an independent, top-level
493 // declaration. As such, if it has an explicit visibility attribute,
494 // that must directly express the user's intent, and we should honor
495 // it.
496 if (spec->isExplicitSpecialization() &&
497 hasExplicitVisibilityAlready(computation))
498 return false;
499
500 return !hasDirectVisibilityAttribute(spec, computation);
501}
502
503/// Merge in template-related linkage and visibility for the given
504/// variable template specialization. As usual, follow class template
505/// specialization logic up to initialization.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000506void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
507 const VarTemplateSpecializationDecl *spec,
508 LVComputationKind computation) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000509 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
510
511 // Merge information from the template parameters, but ignore
512 // visibility if we're only considering template arguments.
513
514 VarTemplateDecl *temp = spec->getSpecializedTemplate();
515 LinkageInfo tempLV =
516 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
517 LV.mergeMaybeWithVisibility(tempLV,
518 considerVisibility && !hasExplicitVisibilityAlready(computation));
519
520 // Merge information from the template arguments. We ignore
521 // template-argument visibility if we've got an explicit
522 // instantiation with a visibility attribute.
523 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
524 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
525 if (considerVisibility)
526 LV.mergeVisibility(argsLV);
527 LV.mergeExternalVisibility(argsLV);
528}
529
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000530static bool useInlineVisibilityHidden(const NamedDecl *D) {
531 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000532 const LangOptions &Opts = D->getASTContext().getLangOpts();
533 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000534 return false;
535
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000536 const auto *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000537 if (!FD)
538 return false;
539
540 TemplateSpecializationKind TSK = TSK_Undeclared;
541 if (FunctionTemplateSpecializationInfo *spec
542 = FD->getTemplateSpecializationInfo()) {
543 TSK = spec->getTemplateSpecializationKind();
544 } else if (MemberSpecializationInfo *MSI =
545 FD->getMemberSpecializationInfo()) {
546 TSK = MSI->getTemplateSpecializationKind();
547 }
548
Craig Topper36250ad2014-05-12 05:36:57 +0000549 const FunctionDecl *Def = nullptr;
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000550 // InlineVisibilityHidden only applies to definitions, and
551 // isInlined() only gives meaningful answers on definitions
552 // anyway.
553 return TSK != TSK_ExplicitInstantiationDeclaration &&
554 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000555 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000556}
557
Rafael Espindola593537a2013-05-05 20:15:21 +0000558template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000559 const T *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +0000560 return First->isInExternCContext();
Rafael Espindolaf4187652013-02-14 01:18:37 +0000561}
562
Richard Smith03c05032014-02-17 23:34:47 +0000563static bool isSingleLineLanguageLinkage(const Decl &D) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000564 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Richard Smith03c05032014-02-17 23:34:47 +0000565 if (!SD->hasBraces())
Rafael Espindola327be3c2013-04-26 01:30:23 +0000566 return true;
567 return false;
568}
569
Richard Smitha5bbbfe2019-04-18 21:12:54 +0000570/// Determine whether D is declared in the purview of a named module.
571static bool isInModulePurview(const NamedDecl *D) {
572 if (auto *M = D->getOwningModule())
573 return M->isModulePurview();
574 return false;
575}
576
Ali Tamurb6a8a6c2019-04-19 02:15:57 +0000577static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D) {
Richard Smithbecb92d2017-10-10 22:33:17 +0000578 // FIXME: Handle isModulePrivate.
Richard Smith1283e982017-07-07 20:04:28 +0000579 switch (D->getModuleOwnershipKind()) {
580 case Decl::ModuleOwnershipKind::Unowned:
581 case Decl::ModuleOwnershipKind::ModulePrivate:
582 return false;
583 case Decl::ModuleOwnershipKind::Visible:
584 case Decl::ModuleOwnershipKind::VisibleWhenImported:
Richard Smitha5bbbfe2019-04-18 21:12:54 +0000585 return isInModulePurview(D);
Richard Smith1283e982017-07-07 20:04:28 +0000586 }
587 llvm_unreachable("unexpected module ownership kind");
588}
589
590static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
591 // Internal linkage declarations within a module interface unit are modeled
592 // as "module-internal linkage", which means that they have internal linkage
593 // formally but can be indirectly accessed from outside the module via inline
594 // functions and templates defined within the module.
Richard Smitha5bbbfe2019-04-18 21:12:54 +0000595 if (isInModulePurview(D))
596 return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false);
Richard Smith1283e982017-07-07 20:04:28 +0000597
598 return LinkageInfo::internal();
599}
600
601static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
602 // C++ Modules TS [basic.link]/6.8:
603 // - A name declared at namespace scope that does not have internal linkage
604 // by the previous rules and that is introduced by a non-exported
605 // declaration has module linkage.
Richard Smith96451e32019-04-19 02:46:50 +0000606 if (isInModulePurview(D) && !isExportedFromModuleInterfaceUnit(
607 cast<NamedDecl>(D->getCanonicalDecl())))
Richard Smitha5bbbfe2019-04-18 21:12:54 +0000608 return LinkageInfo(ModuleLinkage, DefaultVisibility, false);
Richard Smith1283e982017-07-07 20:04:28 +0000609
610 return LinkageInfo::external();
611}
612
Richard Smithbb750682019-04-26 01:51:08 +0000613static StorageClass getStorageClass(const Decl *D) {
614 if (auto *TD = dyn_cast<TemplateDecl>(D))
615 D = TD->getTemplatedDecl();
Hans Wennborgb0dbc9612019-05-14 10:11:33 +0000616 if (D) {
617 if (auto *VD = dyn_cast<VarDecl>(D))
618 return VD->getStorageClass();
619 if (auto *FD = dyn_cast<FunctionDecl>(D))
620 return FD->getStorageClass();
Richard Smithbb750682019-04-26 01:51:08 +0000621 }
622 return SC_None;
623}
624
George Burgess IV99db3ea2017-08-09 04:02:49 +0000625LinkageInfo
626LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +0000627 LVComputationKind computation,
628 bool IgnoreVarTypeLinkage) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000629 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000630 "Not a name having namespace scope");
631 ASTContext &Context = D->getASTContext();
632
633 // C++ [basic.link]p3:
634 // A name having namespace scope (3.3.6) has internal linkage if it
635 // is the name of
Ilya Biryukovb8292c92019-04-24 08:50:24 +0000636
Hans Wennborgb0dbc9612019-05-14 10:11:33 +0000637 if (getStorageClass(D->getCanonicalDecl()) == SC_Static) {
Richard Smithbb750682019-04-26 01:51:08 +0000638 // - a variable, variable template, function, or function template
639 // that is explicitly declared static; or
640 // (This bullet corresponds to C99 6.2.2p3.)
641 return getInternalLinkageFor(D);
642 }
643
644 if (const auto *Var = dyn_cast<VarDecl>(D)) {
645 // - a non-template variable of non-volatile const-qualified type, unless
646 // - it is explicitly declared extern, or
647 // - it is inline or exported, or
648 // - it was previously declared and the prior declaration did not have
649 // internal linkage
650 // (There is no equivalent in C99.)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000651 if (Context.getLangOpts().CPlusPlus &&
Fangrui Song6907ce22018-07-30 19:24:48 +0000652 Var->getType().isConstQualified() &&
Richard Smith62f19e72016-06-25 00:15:56 +0000653 !Var->getType().isVolatileQualified() &&
Richard Smith1283e982017-07-07 20:04:28 +0000654 !Var->isInline() &&
Richard Smithbb750682019-04-26 01:51:08 +0000655 !isExportedFromModuleInterfaceUnit(Var) &&
656 !isa<VarTemplateSpecializationDecl>(Var) &&
657 !Var->getDescribedVarTemplate()) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000658 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000659 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000660 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000661
662 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000663 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000664 !isSingleLineLanguageLinkage(*Var))
Richard Smith1283e982017-07-07 20:04:28 +0000665 return getInternalLinkageFor(Var);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000666 }
667
668 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
669 PrevVar = PrevVar->getPreviousDecl()) {
670 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
671 Var->getStorageClass() == SC_None)
George Burgess IV35cb4f82017-08-09 04:12:17 +0000672 return getDeclLinkageAndVisibility(PrevVar);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000673 // Explicitly declared static.
674 if (PrevVar->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000675 return getInternalLinkageFor(Var);
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000676 }
David Majnemer18fac3b2014-12-10 22:58:14 +0000677 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
678 // - a data member of an anonymous union.
679 const VarDecl *VD = IFD->getVarDecl();
680 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
Richard Smithc95d2c52017-09-22 04:25:05 +0000681 return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000682 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000683 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000684
Richard Smithbb750682019-04-26 01:51:08 +0000685 // FIXME: This gives internal linkage to names that should have no linkage
686 // (those not covered by [basic.link]p6).
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000687 if (D->isInAnonymousNamespace()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000688 const auto *Var = dyn_cast<VarDecl>(D);
689 const auto *Func = dyn_cast<FunctionDecl>(D);
Richard Smithdf963a32017-09-22 22:21:44 +0000690 // FIXME: The check for extern "C" here is not justified by the standard
691 // wording, but we retain it from the pre-DR1113 model to avoid breaking
692 // code.
Richard Smith1283e982017-07-07 20:04:28 +0000693 //
694 // C++11 [basic.link]p4:
695 // An unnamed namespace or a namespace declared directly or indirectly
696 // within an unnamed namespace has internal linkage.
Rafael Espindola593537a2013-05-05 20:15:21 +0000697 if ((!Var || !isFirstInExternCContext(Var)) &&
698 (!Func || !isFirstInExternCContext(Func)))
Richard Smithdf963a32017-09-22 22:21:44 +0000699 return getInternalLinkageFor(D);
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000700 }
John McCallb7139c42010-10-28 04:18:25 +0000701
John McCall457a04e2010-10-22 21:05:15 +0000702 // Set up the defaults.
703
704 // C99 6.2.2p5:
705 // If the declaration of an identifier for an object has file
706 // scope and no storage-class specifier, its linkage is
707 // external.
Richard Smithdd8b5332017-09-04 05:37:53 +0000708 LinkageInfo LV = getExternalLinkageFor(D);
John McCallc273f242010-10-30 11:50:40 +0000709
John McCalld041a9b2013-02-20 01:54:26 +0000710 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000711 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000712 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000713 } else {
714 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000715 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000716 for (const DeclContext *DC = D->getDeclContext();
717 !isa<TranslationUnitDecl>(DC);
718 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000719 const auto *ND = dyn_cast<NamespaceDecl>(DC);
Rafael Espindola78158af2012-04-16 18:46:26 +0000720 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000721 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000722 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000723 break;
724 }
725 }
726 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000727
John McCalldf25c432013-02-16 00:17:33 +0000728 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000729 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000730 // Use global type/value visibility as appropriate.
Richard Smithfbe7b462017-09-22 02:22:32 +0000731 Visibility globalVisibility =
732 computation.isValueVisibility()
733 ? Context.getLangOpts().getValueVisibilityMode()
734 : Context.getLangOpts().getTypeVisibilityMode();
John McCallb4a99d32013-02-19 01:57:35 +0000735 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000736
737 // If we're paying attention to global visibility, apply
738 // -finline-visibility-hidden if this is an inline method.
739 if (useInlineVisibilityHidden(D))
Reid Klecknera52d1512018-10-10 21:59:56 +0000740 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
John McCalldf25c432013-02-16 00:17:33 +0000741 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000742 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000743
Douglas Gregorf73b2822009-11-25 22:24:25 +0000744 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000745
Richard Smithbb750682019-04-26 01:51:08 +0000746 // A name having namespace scope that has not been given internal linkage
747 // above and that is the name of
748 // [...bullets...]
749 // has its linkage determined as follows:
750 // - if the enclosing namespace has internal linkage, the name has
751 // internal linkage; [handled above]
752 // - otherwise, if the declaration of the name is attached to a named
753 // module and is not exported, the name has module linkage;
754 // - otherwise, the name has external linkage.
755 // LV is currently set up to handle the last two bullets.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000756 //
Richard Smithbb750682019-04-26 01:51:08 +0000757 // The bullets are:
758
759 // - a variable; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000760 if (const auto *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000761 // GCC applies the following optimization to variables and static
762 // data members, but not to functions:
763 //
John McCall457a04e2010-10-22 21:05:15 +0000764 // Modify the variable's LV by the LV of its type unless this is
765 // C or extern "C". This follows from [basic.link]p9:
766 // A type without linkage shall not be used as the type of a
767 // variable or function with external linkage unless
768 // - the entity has C language linkage, or
769 // - the entity is declared within an unnamed namespace, or
770 // - the entity is not used or is defined in the same
771 // translation unit.
772 // and [basic.link]p10:
773 // ...the types specified by all declarations referring to a
774 // given variable or function shall be identical...
775 // C does not have an equivalent rule.
776 //
John McCall5fe84122010-10-26 04:59:26 +0000777 // Ignore this if we've got an explicit attribute; the user
778 // probably knows what they're doing.
779 //
John McCall457a04e2010-10-22 21:05:15 +0000780 // Note that we don't want to make the variable non-external
781 // because of this, but unique-external linkage suits us.
Richard Smithc95d2c52017-09-22 04:25:05 +0000782 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
783 !IgnoreVarTypeLinkage) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000784 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Richard Smith405e2db2017-09-20 07:22:00 +0000785 if (!isExternallyVisible(TypeLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000786 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000787 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000788 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000789 }
790
John McCall23032652010-11-02 18:38:13 +0000791 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000792 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000793
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000794 // Note that Sema::MergeVarDecl already takes care of implementing
795 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
796 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000797
Larisse Voufo5899e192014-07-02 23:08:34 +0000798 // As per function and class template specializations (below),
799 // consider LV for the template and template arguments. We're at file
800 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000801 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000802 mergeTemplateLV(LV, spec, computation);
803 }
804
Richard Smithbb750682019-04-26 01:51:08 +0000805 // - a function; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000806 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000807 // In theory, we can modify the function's LV by the LV of its
808 // type unless it has C linkage (see comment above about variables
809 // for justification). In practice, GCC doesn't do this, so it's
810 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000811
John McCall23032652010-11-02 18:38:13 +0000812 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000813 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000814
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000815 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
816 // merging storage classes and visibility attributes, so we don't have to
817 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000818
John McCallf768aa72011-02-10 06:50:24 +0000819 // In C++, then if the type of the function uses a type with
820 // unique-external linkage, it's not legally usable from outside
821 // this translation unit. However, we should use the C linkage
822 // rules instead for extern "C" declarations.
Richard Smith99f54792018-01-03 02:34:35 +0000823 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
Richard Smithc95d2c52017-09-22 04:25:05 +0000824 // Only look at the type-as-written. Otherwise, deducing the return type
825 // of a function could change its linkage.
Richard Smith50f4afc2013-05-12 23:17:59 +0000826 QualType TypeAsWritten = Function->getType();
827 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
828 TypeAsWritten = TSI->getType();
Richard Smith405e2db2017-09-20 07:22:00 +0000829 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
Richard Smith50f4afc2013-05-12 23:17:59 +0000830 return LinkageInfo::uniqueExternal();
831 }
John McCallf768aa72011-02-10 06:50:24 +0000832
John McCall5f46c482013-02-21 23:42:58 +0000833 // Consider LV from the template and the template arguments.
834 // We're at file scope, so we do not need to worry about nested
835 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000836 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000837 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000838 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000839 }
840
Douglas Gregorf73b2822009-11-25 22:24:25 +0000841 // - a named class (Clause 9), or an unnamed class defined in a
842 // typedef declaration in which the class has the typedef name
843 // for linkage purposes (7.1.3); or
844 // - a named enumeration (7.2), or an unnamed enumeration
845 // defined in a typedef declaration in which the enumeration
846 // has the typedef name for linkage purposes (7.1.3); or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000847 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000848 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000849 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000850 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000851
John McCall457a04e2010-10-22 21:05:15 +0000852 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000853 // linkage of the template and template arguments. We're at file
854 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000855 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000856 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000857 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000858
Richard Smithbb750682019-04-26 01:51:08 +0000859 // FIXME: This is not part of the C++ standard any more.
860 // - an enumerator belonging to an enumeration with external linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000861 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000862 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000863 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000864 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000865 return LinkageInfo::none();
866 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000867
Richard Smithbb750682019-04-26 01:51:08 +0000868 // - a template
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000869 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000870 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000871 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000872 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000873 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
874
Richard Smithbb750682019-04-26 01:51:08 +0000875 // An unnamed namespace or a namespace declared directly or indirectly
876 // within an unnamed namespace has internal linkage. All other namespaces
877 // have external linkage.
Richard Smith1283e982017-07-07 20:04:28 +0000878 //
879 // We handled names in anonymous namespaces above.
880 } else if (isa<NamespaceDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000881 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000882
John McCall457a04e2010-10-22 21:05:15 +0000883 // By extension, we assign external linkage to Objective-C
884 // interfaces.
885 } else if (isa<ObjCInterfaceDecl>(D)) {
886 // fallout
887
Richard Smith97135cc2015-11-12 22:19:45 +0000888 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
889 // A typedef declaration has linkage if it gives a type a name for
890 // linkage purposes.
891 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
892 return LinkageInfo::none();
893
John McCall457a04e2010-10-22 21:05:15 +0000894 // Everything not covered here has no linkage.
895 } else {
John McCallc273f242010-10-30 11:50:40 +0000896 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000897 }
898
Richard Smithc445d5d2017-10-03 01:58:15 +0000899 // If we ended up with non-externally-visible linkage, visibility should
John McCall457a04e2010-10-22 21:05:15 +0000900 // always be default.
Richard Smithc445d5d2017-10-03 01:58:15 +0000901 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola4a5da442013-02-27 02:56:45 +0000902 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000903
Alexey Bataevbbc328c2019-11-21 11:30:43 -0500904 // Mark the symbols as hidden when compiling for the device.
905 if (Context.getLangOpts().OpenMP && Context.getLangOpts().OpenMPIsDevice)
906 LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
907
John McCall457a04e2010-10-22 21:05:15 +0000908 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000909}
910
George Burgess IV99db3ea2017-08-09 04:02:49 +0000911LinkageInfo
912LinkageComputer::getLVForClassMember(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +0000913 LVComputationKind computation,
914 bool IgnoreVarTypeLinkage) {
John McCall457a04e2010-10-22 21:05:15 +0000915 // Only certain class members have linkage. Note that fields don't
916 // really have linkage, but it's convenient to say they do for the
917 // purposes of calculating linkage of pointer-to-data-member
918 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000919 //
920 // Templates also don't officially have linkage, but since we ignore
921 // the C++ standard and look at template arguments when determining
922 // linkage and visibility of a template specialization, we might hit
923 // a template template argument that way. If we do, we need to
924 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000925 if (!(isa<CXXMethodDecl>(D) ||
926 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000927 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000928 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000929 isa<TagDecl>(D) ||
930 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000931 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000932
John McCall07072662010-11-02 01:45:15 +0000933 LinkageInfo LV;
934
John McCall07072662010-11-02 01:45:15 +0000935 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000936 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000937 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000938 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000939 // If we're paying attention to global visibility, apply
940 // -finline-visibility-hidden if this is an inline method.
941 //
942 // Note that we do this before merging information about
943 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000944 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Reid Klecknera52d1512018-10-10 21:59:56 +0000945 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
John McCall07072662010-11-02 01:45:15 +0000946 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000947
948 // If this class member has an explicit visibility attribute, the only
949 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000950 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000951 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000952 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000953 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000954
John McCall5f46c482013-02-21 23:42:58 +0000955 LinkageInfo classLV =
956 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
Richard Smithcdb06f22017-09-23 04:02:17 +0000957 // The member has the same linkage as the class. If that's not externally
958 // visible, we don't need to compute anything about the linkage.
959 // FIXME: If we're only computing linkage, can we bail out here?
Rafael Espindolae6190db2013-05-28 02:22:10 +0000960 if (!isExternallyVisible(classLV.getLinkage()))
Richard Smithcdb06f22017-09-23 04:02:17 +0000961 return classLV;
Rafael Espindolae6190db2013-05-28 02:22:10 +0000962
963
John McCall5f46c482013-02-21 23:42:58 +0000964 // Otherwise, don't merge in classLV yet, because in certain cases
965 // we need to completely ignore the visibility from it.
966
967 // Specifically, if this decl exists and has an explicit attribute.
Craig Topper36250ad2014-05-12 05:36:57 +0000968 const NamedDecl *explicitSpecSuppressor = nullptr;
John McCall5f46c482013-02-21 23:42:58 +0000969
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000970 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc95d2c52017-09-22 04:25:05 +0000971 // Only look at the type-as-written. Otherwise, deducing the return type
972 // of a function could change its linkage.
973 QualType TypeAsWritten = MD->getType();
974 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
975 TypeAsWritten = TSI->getType();
976 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
977 return LinkageInfo::uniqueExternal();
978
John McCall457a04e2010-10-22 21:05:15 +0000979 // If this is a method template specialization, use the linkage for
980 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000981 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000982 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000983 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000984 if (spec->isExplicitSpecialization()) {
985 explicitSpecSuppressor = MD;
986 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
987 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
988 }
989 } else if (isExplicitMemberSpecialization(MD)) {
990 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000991 }
John McCall457a04e2010-10-22 21:05:15 +0000992
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000993 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
994 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000995 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000996 if (spec->isExplicitSpecialization()) {
997 explicitSpecSuppressor = spec;
998 } else {
999 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
1000 if (isExplicitMemberSpecialization(temp)) {
1001 explicitSpecSuppressor = temp->getTemplatedDecl();
1002 }
1003 }
1004 } else if (isExplicitMemberSpecialization(RD)) {
1005 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +00001006 }
1007
John McCall37bb6c92010-10-29 22:22:43 +00001008 // Static data members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001009 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
1010 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
Larisse Voufo5899e192014-07-02 23:08:34 +00001011 mergeTemplateLV(LV, spec, computation);
1012
John McCall36cd5cc2010-10-30 09:18:49 +00001013 // Modify the variable's linkage by its type, but ignore the
1014 // type's visibility unless it's a definition.
Richard Smithc95d2c52017-09-22 04:25:05 +00001015 if (!IgnoreVarTypeLinkage) {
1016 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
1017 // FIXME: If the type's linkage is not externally visible, we can
1018 // give this static data member UniqueExternalLinkage.
1019 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
1020 LV.mergeVisibility(typeLV);
1021 LV.mergeExternalVisibility(typeLV);
1022 }
John McCall5f46c482013-02-21 23:42:58 +00001023
1024 if (isExplicitMemberSpecialization(VD)) {
1025 explicitSpecSuppressor = VD;
1026 }
John McCalldf25c432013-02-16 00:17:33 +00001027
1028 // Template members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001029 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001030 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +00001031 (!LV.isVisibilityExplicit() &&
1032 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +00001033 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +00001034 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +00001035 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +00001036 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +00001037
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001038 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
John McCall5f46c482013-02-21 23:42:58 +00001039 if (isExplicitMemberSpecialization(redeclTemp)) {
1040 explicitSpecSuppressor = temp->getTemplatedDecl();
1041 }
1042 }
John McCall37bb6c92010-10-29 22:22:43 +00001043 }
1044
John McCall5f46c482013-02-21 23:42:58 +00001045 // We should never be looking for an attribute directly on a template.
1046 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1047
1048 // If this member is an explicit member specialization, and it has
1049 // an explicit attribute, ignore visibility from the parent.
1050 bool considerClassVisibility = true;
1051 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +00001052 // optimization: hasDVA() is true only with explicit visibility.
1053 LV.isVisibilityExplicit() &&
1054 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +00001055 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
1056 considerClassVisibility = false;
1057 }
1058
1059 // Finally, merge in information from the class.
1060 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +00001061 return LV;
John McCall8823c652010-08-13 08:35:10 +00001062}
1063
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001064void NamedDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00001065
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001066bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001067 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001068 return true;
John McCalld396b972011-02-08 19:01:05 +00001069
Richard Smithfbe7b462017-09-22 02:22:32 +00001070 Linkage L = LinkageComputer{}
1071 .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
1072 .getLinkage();
George Burgess IV99db3ea2017-08-09 04:02:49 +00001073 return L == getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +00001074}
1075
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001076ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1077 StringRef name = getName();
1078 if (name.empty()) return SFF_None;
Fangrui Song6907ce22018-07-30 19:24:48 +00001079
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001080 if (name.front() == 'C')
1081 if (name == "CFStringCreateWithFormat" ||
1082 name == "CFStringCreateWithFormatAndArguments" ||
1083 name == "CFStringAppendFormat" ||
1084 name == "CFStringAppendFormatAndArguments")
1085 return SFF_CFString;
1086 return SFF_None;
1087}
1088
Rafael Espindola3ae00052013-05-13 00:12:11 +00001089Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +00001090 // We don't care about visibility here, so ask for the cheapest
1091 // possible visibility analysis.
Richard Smithfbe7b462017-09-22 02:22:32 +00001092 return LinkageComputer{}
1093 .getLVForDecl(this, LVComputationKind::forLinkageOnly())
1094 .getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001095}
1096
John McCallc273f242010-10-30 11:50:40 +00001097LinkageInfo NamedDecl::getLinkageAndVisibility() const {
George Burgess IV99db3ea2017-08-09 04:02:49 +00001098 return LinkageComputer{}.getDeclLinkageAndVisibility(this);
John McCall033caa52010-10-29 00:29:13 +00001099}
Ted Kremenek926d8602010-04-20 23:15:35 +00001100
Rafael Espindola9ad61122013-11-26 16:09:08 +00001101static Optional<Visibility>
1102getExplicitVisibilityAux(const NamedDecl *ND,
1103 NamedDecl::ExplicitVisibilityKind kind,
1104 bool IsMostRecent) {
1105 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1106
Rafael Espindola3a52c442013-02-26 19:33:14 +00001107 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001108 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001109 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001110
Rafael Espindola3a52c442013-02-26 19:33:14 +00001111 // If this is a member class of a specialization of a class template
1112 // and the corresponding decl has explicit visibility, use that.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001113 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +00001114 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1115 if (InstantiatedFrom)
1116 return getVisibilityOf(InstantiatedFrom, kind);
1117 }
1118
1119 // If there wasn't explicit visibility there, and this is a
1120 // specialization of a class template, check for visibility
1121 // on the pattern.
Steven Wu79cbd112018-04-19 15:46:43 +00001122 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
1123 // Walk all the template decl till this point to see if there are
1124 // explicit visibility attributes.
1125 const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();
1126 while (TD != nullptr) {
1127 auto Vis = getVisibilityOf(TD, kind);
1128 if (Vis != None)
1129 return Vis;
1130 TD = TD->getPreviousDecl();
1131 }
1132 return None;
1133 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001134
1135 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +00001136 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +00001137 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1138 if (MostRecent != ND)
1139 return getExplicitVisibilityAux(MostRecent, kind, true);
1140 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001141
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001142 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +00001143 if (Var->isStaticDataMember()) {
1144 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1145 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001146 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +00001147 }
1148
David Majnemer35b02bc2014-04-29 07:32:26 +00001149 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1150 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1151 kind);
1152
David Blaikie7a30dc52013-02-21 01:47:18 +00001153 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +00001154 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001155 // Also handle function template specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001156 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001157 // If the function is a specialization of a template with an
1158 // explicit visibility attribute, use that.
1159 if (FunctionTemplateSpecializationInfo *templateInfo
1160 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +00001161 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1162 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001163
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001164 // If the function is a member of a specialization of a class template
1165 // and the corresponding decl has explicit visibility, use that.
1166 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1167 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001168 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001169
David Blaikie7a30dc52013-02-21 01:47:18 +00001170 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001171 }
1172
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001173 // The visibility of a template is stored in the templated decl.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001174 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001175 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001176
David Blaikie7a30dc52013-02-21 01:47:18 +00001177 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001178}
1179
Rafael Espindola9ad61122013-11-26 16:09:08 +00001180Optional<Visibility>
1181NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1182 return getExplicitVisibilityAux(this, kind, false);
1183}
1184
George Burgess IV99db3ea2017-08-09 04:02:49 +00001185LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1186 Decl *ContextDecl,
1187 LVComputationKind computation) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001188 // This lambda has its linkage/visibility determined by its owner.
Richard Smithc95d2c52017-09-22 04:25:05 +00001189 const NamedDecl *Owner;
1190 if (!ContextDecl)
1191 Owner = dyn_cast<NamedDecl>(DC);
1192 else if (isa<ParmVarDecl>(ContextDecl))
1193 Owner =
1194 dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1195 else
1196 Owner = cast<NamedDecl>(ContextDecl);
1197
Richard Smithc95d2c52017-09-22 04:25:05 +00001198 if (!Owner)
Richard Smith7ff83042017-09-22 04:33:20 +00001199 return LinkageInfo::none();
Richard Smithc95d2c52017-09-22 04:25:05 +00001200
1201 // If the owner has a deduced type, we need to skip querying the linkage and
1202 // visibility of that type, because it might involve this closure type. The
1203 // only effect of this is that we might give a lambda VisibleNoLinkage rather
1204 // than NoLinkage when we don't strictly need to, which is benign.
1205 auto *VD = dyn_cast<VarDecl>(Owner);
Richard Smith7ff83042017-09-22 04:33:20 +00001206 LinkageInfo OwnerLV =
Richard Smithc95d2c52017-09-22 04:25:05 +00001207 VD && VD->getType()->getContainedDeducedType()
1208 ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1209 : getLVForDecl(Owner, computation);
1210
Richard Smith7ff83042017-09-22 04:33:20 +00001211 // A lambda never formally has linkage. But if the owner is externally
1212 // visible, then the lambda is too. We apply the same rules to blocks.
1213 if (!isExternallyVisible(OwnerLV.getLinkage()))
1214 return LinkageInfo::none();
1215 return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
1216 OwnerLV.isVisibilityExplicit());
Eli Friedman7e346a82013-07-01 20:22:57 +00001217}
1218
George Burgess IV99db3ea2017-08-09 04:02:49 +00001219LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1220 LVComputationKind computation) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001221 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001222 if (Function->isInAnonymousNamespace() &&
Richard Smith99f54792018-01-03 02:34:35 +00001223 !isFirstInExternCContext(Function))
Richard Smithdf963a32017-09-22 22:21:44 +00001224 return getInternalLinkageFor(Function);
John McCalldf25c432013-02-16 00:17:33 +00001225
1226 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001227 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +00001228 return getInternalLinkageFor(Function);
John McCalldf25c432013-02-16 00:17:33 +00001229
1230 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001231 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001232 if (Optional<Visibility> Vis =
1233 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001234 LV.mergeVisibility(*Vis, true);
1235 }
1236
1237 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1238 // merging storage classes and visibility attributes, so we don't have to
1239 // look at previous decls in here.
1240
1241 return LV;
1242 }
1243
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001244 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001245 if (Var->hasExternalStorage()) {
Richard Smith99f54792018-01-03 02:34:35 +00001246 if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
Richard Smithdf963a32017-09-22 22:21:44 +00001247 return getInternalLinkageFor(Var);
John McCalldf25c432013-02-16 00:17:33 +00001248
John McCalldf25c432013-02-16 00:17:33 +00001249 LinkageInfo LV;
1250 if (Var->getStorageClass() == SC_PrivateExtern)
1251 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001252 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001253 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001254 LV.mergeVisibility(*Vis, true);
1255 }
1256
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001257 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1258 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1259 if (PrevLV.getLinkage())
1260 LV.setLinkage(PrevLV.getLinkage());
1261 LV.mergeVisibility(PrevLV);
1262 }
1263
John McCalldf25c432013-02-16 00:17:33 +00001264 return LV;
1265 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001266
1267 if (!Var->isStaticLocal())
1268 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001269 }
1270
Rafael Espindolaa4184182013-06-17 20:04:51 +00001271 ASTContext &Context = D->getASTContext();
1272 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001273 return LinkageInfo::none();
1274
Eli Friedman7e346a82013-07-01 20:22:57 +00001275 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
Alexey Bataev0a47e652016-01-12 09:01:25 +00001276 if (!OuterD || OuterD->isInvalidDecl())
Rafael Espindola50df3a02013-05-25 17:16:20 +00001277 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001278
Eli Friedman7e346a82013-07-01 20:22:57 +00001279 LinkageInfo LV;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001280 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001281 if (!BD->getBlockManglingNumber())
1282 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001283
Eli Friedman7e346a82013-07-01 20:22:57 +00001284 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1285 BD->getBlockManglingContextDecl(), computation);
1286 } else {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001287 const auto *FD = cast<FunctionDecl>(OuterD);
Eli Friedman7e346a82013-07-01 20:22:57 +00001288 if (!FD->isInlined() &&
David Majnemer9963ade2014-12-16 04:52:14 +00001289 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
Eli Friedman7e346a82013-07-01 20:22:57 +00001290 return LinkageInfo::none();
1291
Hiroshi Inoue03ff37d2018-08-22 05:43:27 +00001292 // If a function is hidden by -fvisibility-inlines-hidden option and
1293 // is not explicitly attributed as a hidden function,
1294 // we should not make static local variables in the function hidden.
Eli Friedman7e346a82013-07-01 20:22:57 +00001295 LV = getLVForDecl(FD, computation);
Reid Klecknera52d1512018-10-10 21:59:56 +00001296 if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) &&
1297 !LV.isVisibilityExplicit()) {
1298 assert(cast<VarDecl>(D)->isStaticLocal());
1299 // If this was an implicitly hidden inline method, check again for
1300 // explicit visibility on the parent class, and use that for static locals
1301 // if present.
1302 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1303 LV = getLVForDecl(MD->getParent(), computation);
1304 if (!LV.isVisibilityExplicit()) {
1305 Visibility globalVisibility =
1306 computation.isValueVisibility()
1307 ? Context.getLangOpts().getValueVisibilityMode()
1308 : Context.getLangOpts().getTypeVisibilityMode();
1309 return LinkageInfo(VisibleNoLinkage, globalVisibility,
1310 /*visibilityExplicit=*/false);
1311 }
1312 }
Eli Friedman7e346a82013-07-01 20:22:57 +00001313 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001314 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001315 return LinkageInfo::none();
1316 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1317 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001318}
1319
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001320static inline const CXXRecordDecl*
1321getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1322 const CXXRecordDecl *Ret = Record;
1323 while (Record && Record->isLambda()) {
1324 Ret = Record;
1325 if (!Record->getParent()) break;
1326 // Get the Containing Class of this Lambda Class
1327 Record = dyn_cast_or_null<CXXRecordDecl>(
1328 Record->getParent()->getParent());
1329 }
1330 return Ret;
1331}
1332
George Burgess IV99db3ea2017-08-09 04:02:49 +00001333LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +00001334 LVComputationKind computation,
1335 bool IgnoreVarTypeLinkage) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001336 // Internal_linkage attribute overrides other considerations.
1337 if (D->hasAttr<InternalLinkageAttr>())
Richard Smith1283e982017-07-07 20:04:28 +00001338 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001339
Ted Kremenek926d8602010-04-20 23:15:35 +00001340 // Objective-C: treat all Objective-C declarations as having external
1341 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001342 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001343 default:
1344 break;
Richard Smith97135cc2015-11-12 22:19:45 +00001345
1346 // Per C++ [basic.link]p2, only the names of objects, references,
1347 // functions, types, templates, namespaces, and values ever have linkage.
1348 //
1349 // Note that the name of a typedef, namespace alias, using declaration,
1350 // and so on are not the name of the corresponding type, namespace, or
1351 // declaration, so they do *not* have linkage.
Richard Smith97135cc2015-11-12 22:19:45 +00001352 case Decl::ImplicitParam:
1353 case Decl::Label:
1354 case Decl::NamespaceAlias:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001355 case Decl::ParmVar:
Richard Smith97135cc2015-11-12 22:19:45 +00001356 case Decl::Using:
1357 case Decl::UsingShadow:
1358 case Decl::UsingDirective:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001359 return LinkageInfo::none();
Richard Smith97135cc2015-11-12 22:19:45 +00001360
Richard Smith26210db2015-11-13 03:52:13 +00001361 case Decl::EnumConstant:
1362 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
Bruno Cardoso Lopes057c82c2017-07-01 00:06:27 +00001363 if (D->getASTContext().getLangOpts().CPlusPlus)
1364 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1365 return LinkageInfo::visible_none();
Richard Smith26210db2015-11-13 03:52:13 +00001366
Richard Smith97135cc2015-11-12 22:19:45 +00001367 case Decl::Typedef:
1368 case Decl::TypeAlias:
1369 // A typedef declaration has linkage if it gives a type a name for
1370 // linkage purposes.
Vassil Vassilevb00ea082017-07-01 20:44:49 +00001371 if (!cast<TypedefNameDecl>(D)
Richard Smith97135cc2015-11-12 22:19:45 +00001372 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1373 return LinkageInfo::none();
1374 break;
1375
John McCall457a04e2010-10-22 21:05:15 +00001376 case Decl::TemplateTemplateParm: // count these as external
1377 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001378 case Decl::ObjCAtDefsField:
1379 case Decl::ObjCCategory:
1380 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001381 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001382 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001383 case Decl::ObjCMethod:
1384 case Decl::ObjCProperty:
1385 case Decl::ObjCPropertyImpl:
1386 case Decl::ObjCProtocol:
Richard Smith1283e982017-07-07 20:04:28 +00001387 return getExternalLinkageFor(D);
Fangrui Song6907ce22018-07-30 19:24:48 +00001388
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001389 case Decl::CXXRecord: {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001390 const auto *Record = cast<CXXRecordDecl>(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001391 if (Record->isLambda()) {
Michael Liao243ebfb2019-10-19 00:15:19 +00001392 if (Record->hasKnownLambdaInternalLinkage() ||
1393 !Record->getLambdaManglingNumber()) {
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001394 // This lambda has no mangling number, so it's internal.
Richard Smith1283e982017-07-07 20:04:28 +00001395 return getInternalLinkageFor(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001396 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001397
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001398 // This lambda has its linkage/visibility determined:
Fangrui Song6907ce22018-07-30 19:24:48 +00001399 // - either by the outermost lambda if that lambda has no mangling
1400 // number.
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001401 // - or by the parent of the outer most lambda
Fangrui Song6907ce22018-07-30 19:24:48 +00001402 // This prevents infinite recursion in settings such as nested lambdas
1403 // used in NSDMI's, for e.g.
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001404 // struct L {
1405 // int t{};
Fangrui Song6907ce22018-07-30 19:24:48 +00001406 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001407 // };
Fangrui Song6907ce22018-07-30 19:24:48 +00001408 const CXXRecordDecl *OuterMostLambda =
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001409 getOutermostEnclosingLambda(Record);
Michael Liao243ebfb2019-10-19 00:15:19 +00001410 if (OuterMostLambda->hasKnownLambdaInternalLinkage() ||
1411 !OuterMostLambda->getLambdaManglingNumber())
Richard Smith1283e982017-07-07 20:04:28 +00001412 return getInternalLinkageFor(D);
Fangrui Song6907ce22018-07-30 19:24:48 +00001413
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001414 return getLVForClosure(
1415 OuterMostLambda->getDeclContext()->getRedeclContext(),
1416 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001417 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001418
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001419 break;
1420 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001421 }
1422
Douglas Gregorf73b2822009-11-25 22:24:25 +00001423 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001424 if (D->getDeclContext()->getRedeclContext()->isFileContext())
Richard Smithc95d2c52017-09-22 04:25:05 +00001425 return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
Fangrui Song6907ce22018-07-30 19:24:48 +00001426
Douglas Gregorf73b2822009-11-25 22:24:25 +00001427 // C++ [basic.link]p5:
1428 // In addition, a member function, static data member, a named
1429 // class or enumeration of class scope, or an unnamed class or
1430 // enumeration defined in a class-scope typedef declaration such
1431 // that the class or enumeration has the typedef name for linkage
1432 // purposes (7.1.3), has external linkage if the name of the class
1433 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001434 if (D->getDeclContext()->isRecord())
Richard Smithc95d2c52017-09-22 04:25:05 +00001435 return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001436
1437 // C++ [basic.link]p6:
1438 // The name of a function declared in block scope and the name of
1439 // an object declared by a block scope extern declaration have
1440 // linkage. If there is a visible declaration of an entity with
1441 // linkage having the same name and type, ignoring entities
1442 // declared outside the innermost enclosing namespace scope, the
1443 // block scope declaration declares that same entity and receives
1444 // the linkage of the previous declaration. If there is more than
1445 // one such matching entity, the program is ill-formed. Otherwise,
1446 // if no matching entity is found, the block scope entity receives
1447 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001448 if (D->getDeclContext()->isFunctionOrMethod())
1449 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001450
1451 // C++ [basic.link]p6:
1452 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001453 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001454}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001455
George Burgess IV99db3ea2017-08-09 04:02:49 +00001456/// getLVForDecl - Get the linkage and visibility for the given declaration.
1457LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1458 LVComputationKind computation) {
1459 // Internal_linkage attribute overrides other considerations.
1460 if (D->hasAttr<InternalLinkageAttr>())
1461 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001462
Richard Smithfbe7b462017-09-22 02:22:32 +00001463 if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
George Burgess IV99db3ea2017-08-09 04:02:49 +00001464 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001465
George Burgess IV35cb4f82017-08-09 04:12:17 +00001466 if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
1467 return *LI;
1468
George Burgess IV99db3ea2017-08-09 04:02:49 +00001469 LinkageInfo LV = computeLVForDecl(D, computation);
1470 if (D->hasCachedLinkage())
1471 assert(D->getCachedLinkage() == LV.getLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001472
George Burgess IV99db3ea2017-08-09 04:02:49 +00001473 D->setCachedLinkage(LV.getLinkage());
George Burgess IV35cb4f82017-08-09 04:12:17 +00001474 cache(D, computation, LV);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001475
1476#ifndef NDEBUG
George Burgess IV99db3ea2017-08-09 04:02:49 +00001477 // In C (because of gnu inline) and in c++ with microsoft extensions an
1478 // static can follow an extern, so we can have two decls with different
1479 // linkages.
1480 const LangOptions &Opts = D->getASTContext().getLangOpts();
1481 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1482 return LV;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001483
George Burgess IV99db3ea2017-08-09 04:02:49 +00001484 // We have just computed the linkage for this decl. By induction we know
1485 // that all other computed linkages match, check that the one we just
1486 // computed also does.
1487 NamedDecl *Old = nullptr;
1488 for (auto I : D->redecls()) {
1489 auto *T = cast<NamedDecl>(I);
1490 if (T == D)
1491 continue;
1492 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1493 Old = T;
1494 break;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001495 }
George Burgess IV99db3ea2017-08-09 04:02:49 +00001496 }
1497 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001498#endif
1499
George Burgess IV99db3ea2017-08-09 04:02:49 +00001500 return LV;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001501}
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001502
George Burgess IV99db3ea2017-08-09 04:02:49 +00001503LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
Richard Smithfbe7b462017-09-22 02:22:32 +00001504 return getLVForDecl(D,
1505 LVComputationKind(usesTypeVisibility(D)
1506 ? NamedDecl::VisibilityForType
1507 : NamedDecl::VisibilityForValue));
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001508}
1509
Richard Smithbecb92d2017-10-10 22:33:17 +00001510Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
Richard Smithdd8b5332017-09-04 05:37:53 +00001511 Module *M = getOwningModule();
1512 if (!M)
1513 return nullptr;
1514
1515 switch (M->Kind) {
1516 case Module::ModuleMapModule:
1517 // Module map modules have no special linkage semantics.
1518 return nullptr;
1519
1520 case Module::ModuleInterfaceUnit:
1521 return M;
1522
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001523 case Module::GlobalModuleFragment: {
Richard Smithdd8b5332017-09-04 05:37:53 +00001524 // External linkage declarations in the global module have no owning module
1525 // for linkage purposes. But internal linkage declarations in the global
1526 // module fragment of a particular module are owned by that module for
1527 // linkage purposes.
Richard Smithbecb92d2017-10-10 22:33:17 +00001528 if (IgnoreLinkage)
1529 return nullptr;
1530 bool InternalLinkage;
1531 if (auto *ND = dyn_cast<NamedDecl>(this))
1532 InternalLinkage = !ND->hasExternalFormalLinkage();
1533 else {
1534 auto *NSD = dyn_cast<NamespaceDecl>(this);
1535 InternalLinkage = (NSD && NSD->isAnonymousNamespace()) ||
1536 isInAnonymousNamespace();
1537 }
1538 return InternalLinkage ? M->Parent : nullptr;
Richard Smithdd8b5332017-09-04 05:37:53 +00001539 }
Richard Smitha5bbbfe2019-04-18 21:12:54 +00001540
1541 case Module::PrivateModuleFragment:
1542 // The private module fragment is part of its containing module for linkage
1543 // purposes.
1544 return M->Parent;
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001545 }
Richard Smithdd8b5332017-09-04 05:37:53 +00001546
1547 llvm_unreachable("unknown module kind");
1548}
1549
Richard Smith7873de02016-08-11 22:25:46 +00001550void NamedDecl::printName(raw_ostream &os) const {
1551 os << Name;
1552}
1553
Douglas Gregor2ada0482009-02-04 17:27:36 +00001554std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001555 std::string QualName;
1556 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001557 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001558 return OS.str();
1559}
1560
1561void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1562 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1563}
1564
1565void NamedDecl::printQualifiedName(raw_ostream &OS,
1566 const PrintingPolicy &P) const {
Ilya Biryukov66482232019-09-25 15:46:04 +00001567 if (getDeclContext()->isFunctionOrMethod()) {
1568 // We do not print '(anonymous)' for function parameters without name.
1569 printName(OS);
1570 return;
1571 }
1572 printNestedNameSpecifier(OS, P);
1573 if (getDeclName() || isa<DecompositionDecl>(this))
1574 OS << *this;
1575 else
1576 OS << "(anonymous)";
1577}
1578
1579void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
1580 printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
1581}
1582
1583void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
1584 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001585 const DeclContext *Ctx = getDeclContext();
1586
David Goldman19d21852019-04-04 20:13:22 +00001587 // For ObjC methods and properties, look through categories and use the
1588 // interface as context.
Argyrios Kyrtzidisa166a2b2017-03-07 09:26:07 +00001589 if (auto *MD = dyn_cast<ObjCMethodDecl>(this))
1590 if (auto *ID = MD->getClassInterface())
1591 Ctx = ID;
David Goldman19d21852019-04-04 20:13:22 +00001592 if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
1593 if (auto *MD = PD->getGetterMethodDecl())
1594 if (auto *ID = MD->getClassInterface())
1595 Ctx = ID;
1596 }
Argyrios Kyrtzidisa166a2b2017-03-07 09:26:07 +00001597
Ilya Biryukov66482232019-09-25 15:46:04 +00001598 if (Ctx->isFunctionOrMethod())
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001599 return;
Douglas Gregor2ada0482009-02-04 17:27:36 +00001600
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001601 using ContextsTy = SmallVector<const DeclContext *, 8>;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001602 ContextsTy Contexts;
1603
Sam McCall34f9d3f2018-02-02 13:34:47 +00001604 // Collect named contexts.
1605 while (Ctx) {
1606 if (isa<NamedDecl>(Ctx))
1607 Contexts.push_back(Ctx);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001608 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001609 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001610
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001611 for (const DeclContext *DC : llvm::reverse(Contexts)) {
David Majnemerf7e36092016-06-23 00:15:04 +00001612 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001613 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001614 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Serge Pavlov03e672c2017-11-28 16:14:14 +00001615 printTemplateArgumentList(OS, TemplateArgs.asArray(), P);
David Majnemerf7e36092016-06-23 00:15:04 +00001616 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
Richard Smith46dd5bb2014-05-30 22:16:51 +00001617 if (P.SuppressUnwrittenScope &&
1618 (ND->isAnonymousNamespace() || ND->isInline()))
1619 continue;
Reid Kleckner60103382015-12-16 02:04:40 +00001620 if (ND->isAnonymousNamespace()) {
1621 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1622 : "(anonymous namespace)");
1623 }
Sam Weinig07d211e2009-12-24 23:15:03 +00001624 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001625 OS << *ND;
David Majnemerf7e36092016-06-23 00:15:04 +00001626 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001627 if (!RD->getIdentifier())
David Blaikieabe1a392014-04-02 05:58:29 +00001628 OS << "(anonymous " << RD->getKindName() << ')';
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001629 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001630 OS << *RD;
David Majnemerf7e36092016-06-23 00:15:04 +00001631 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
Craig Topper36250ad2014-05-12 05:36:57 +00001632 const FunctionProtoType *FT = nullptr;
Sam Weinigb999f682009-12-28 03:19:38 +00001633 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001634 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001635
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001636 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001637 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001638 unsigned NumParams = FD->getNumParams();
1639 for (unsigned i = 0; i < NumParams; ++i) {
1640 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001641 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001642 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001643 }
1644
1645 if (FT->isVariadic()) {
1646 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001647 OS << ", ";
1648 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001649 }
1650 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001651 OS << ')';
David Majnemerf7e36092016-06-23 00:15:04 +00001652 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
Alexander Kornienko4f355322015-11-09 16:45:17 +00001653 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1654 // enumerator is declared in the scope that immediately contains
1655 // the enum-specifier. Each scoped enumerator is declared in the
1656 // scope of the enumeration.
Paul Robinsonf1838482017-12-21 21:47:22 +00001657 // For the case of unscoped enumerator, do not include in the qualified
Paul Robinsond1c3dd82017-12-26 18:01:19 +00001658 // name any information about its enum enclosing scope, as its visibility
Paul Robinsonf1838482017-12-21 21:47:22 +00001659 // is global.
1660 if (ED->isScoped())
Alexander Kornienko4f355322015-11-09 16:45:17 +00001661 OS << *ED;
1662 else
1663 continue;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001664 } else {
David Majnemerf7e36092016-06-23 00:15:04 +00001665 OS << *cast<NamedDecl>(DC);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001666 }
1667 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001668 }
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001669}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001670
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001671void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1672 const PrintingPolicy &Policy,
1673 bool Qualified) const {
1674 if (Qualified)
1675 printQualifiedName(OS, Policy);
1676 else
1677 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001678}
1679
Richard Smithe8292b12015-02-10 03:28:10 +00001680template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1681 return true;
1682}
1683static bool isRedeclarableImpl(...) { return false; }
1684static bool isRedeclarable(Decl::Kind K) {
1685 switch (K) {
1686#define DECL(Type, Base) \
1687 case Decl::Type: \
1688 return isRedeclarableImpl((Type##Decl *)nullptr);
1689#define ABSTRACT_DECL(DECL)
1690#include "clang/AST/DeclNodes.inc"
1691 }
1692 llvm_unreachable("unknown decl kind");
1693}
1694
1695bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001696 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1697
Richard Smithfe620d22015-03-05 23:24:12 +00001698 // Never replace one imported declaration with another; we need both results
1699 // when re-exporting.
1700 if (OldD->isFromASTFile() && isFromASTFile())
1701 return false;
1702
Richard Smith5cd86f82015-11-03 03:13:11 +00001703 // A kind mismatch implies that the declaration is not replaced.
1704 if (OldD->getKind() != getKind())
Richard Smithe8292b12015-02-10 03:28:10 +00001705 return false;
1706
Richard Smith5cd86f82015-11-03 03:13:11 +00001707 // For method declarations, we never replace. (Why?)
1708 if (isa<ObjCMethodDecl>(this))
1709 return false;
1710
1711 // For parameters, pick the newer one. This is either an error or (in
1712 // Objective-C) permitted as an extension.
1713 if (isa<ParmVarDecl>(this))
1714 return true;
1715
Richard Smithe8292b12015-02-10 03:28:10 +00001716 // Inline namespaces can give us two declarations with the same
1717 // name and kind in the same scope but different contexts; we should
1718 // keep both declarations in this case.
1719 if (!this->getDeclContext()->getRedeclContext()->Equals(
1720 OldD->getDeclContext()->getRedeclContext()))
1721 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001722
Richard Smith5cd86f82015-11-03 03:13:11 +00001723 // Using declarations can be replaced if they import the same name from the
1724 // same context.
Richard Smithe8292b12015-02-10 03:28:10 +00001725 if (auto *UD = dyn_cast<UsingDecl>(this)) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001726 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001727 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001728 Context.getCanonicalNestedNameSpecifier(
Richard Smithe8292b12015-02-10 03:28:10 +00001729 cast<UsingDecl>(OldD)->getQualifier());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001730 }
Richard Smithe8292b12015-02-10 03:28:10 +00001731 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001732 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001733 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001734 Context.getCanonicalNestedNameSpecifier(
1735 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1736 }
1737
Richard Smith5cd86f82015-11-03 03:13:11 +00001738 if (isRedeclarable(getKind())) {
1739 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1740 return false;
1741
1742 if (IsKnownNewer)
1743 return true;
1744
Richard Smithe8292b12015-02-10 03:28:10 +00001745 // Check whether this is actually newer than OldD. We want to keep the
1746 // newer declaration. This loop will usually only iterate once, because
1747 // OldD is usually the previous declaration.
1748 for (auto D : redecls()) {
1749 if (D == OldD)
1750 break;
1751
1752 // If we reach the canonical declaration, then OldD is not actually older
1753 // than this one.
1754 //
1755 // FIXME: In this case, we should not add this decl to the lookup table.
1756 if (D->isCanonicalDecl())
1757 return false;
1758 }
Richard Smith5cd86f82015-11-03 03:13:11 +00001759
1760 // It's a newer declaration of the same kind of declaration in the same
1761 // scope: we want this decl instead of the existing one.
1762 return true;
Richard Smithe8292b12015-02-10 03:28:10 +00001763 }
1764
Richard Smith5cd86f82015-11-03 03:13:11 +00001765 // In all other cases, we need to keep both declarations in case they have
1766 // different visibility. Any attempt to use the name will result in an
1767 // ambiguity if more than one is visible.
1768 return false;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001769}
1770
Douglas Gregoreddf4332009-02-24 20:03:32 +00001771bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001772 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001773}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001774
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001775NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001776 NamedDecl *ND = this;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001777 while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001778 ND = UD->getTargetDecl();
1779
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001780 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001781 return AD->getClassInterface();
1782
Richard Smithf2005d32015-12-29 23:34:32 +00001783 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1784 return AD->getNamespace();
1785
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001786 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001787}
1788
John McCalla8ae2222010-04-06 21:38:20 +00001789bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001790 if (!isCXXClassMember())
1791 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001792
John McCalla8ae2222010-04-06 21:38:20 +00001793 const NamedDecl *D = this;
1794 if (isa<UsingShadowDecl>(D))
1795 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1796
John McCall5e77d762013-04-16 07:28:30 +00001797 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001798 return true;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001799 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
Alp Tokera2794f92014-01-22 07:29:52 +00001800 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001801 return false;
1802}
1803
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001804//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001805// DeclaratorDecl Implementation
1806//===----------------------------------------------------------------------===//
1807
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001808template <typename DeclT>
1809static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1810 if (decl->getNumTemplateParameterLists() > 0)
1811 return decl->getTemplateParameterList(0)->getTemplateLoc();
1812 else
1813 return decl->getInnerLocStart();
1814}
1815
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001816SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001817 TypeSourceInfo *TSI = getTypeSourceInfo();
1818 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001819 return SourceLocation();
1820}
1821
Douglas Gregor14454802011-02-25 02:25:35 +00001822void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1823 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001824 // Make sure the extended decl info is allocated.
1825 if (!hasExtInfo()) {
1826 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001827 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
John McCall3e11ebe2010-03-15 10:12:16 +00001828 // Allocate external info struct.
1829 DeclInfo = new (getASTContext()) ExtInfo;
1830 // Restore savedTInfo into (extended) decl info.
1831 getExtInfo()->TInfo = savedTInfo;
1832 }
1833 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001834 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001835 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001836 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001837 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001838 if (getExtInfo()->NumTemplParamLists == 0) {
1839 // Save type source info pointer.
1840 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1841 // Deallocate the extended decl info.
1842 getASTContext().Deallocate(getExtInfo());
1843 // Restore savedTInfo into (non-extended) decl info.
1844 DeclInfo = savedTInfo;
1845 }
1846 else
1847 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001848 }
1849 }
1850}
1851
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001852void DeclaratorDecl::setTemplateParameterListsInfo(
1853 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1854 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00001855 // Make sure the extended decl info is allocated.
1856 if (!hasExtInfo()) {
1857 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001858 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
Abramo Bagnara60804e12011-03-18 15:16:37 +00001859 // Allocate external info struct.
1860 DeclInfo = new (getASTContext()) ExtInfo;
1861 // Restore savedTInfo into (extended) decl info.
1862 getExtInfo()->TInfo = savedTInfo;
1863 }
1864 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001865 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00001866}
1867
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001868SourceLocation DeclaratorDecl::getOuterLocStart() const {
1869 return getTemplateOrInnerLocStart(this);
1870}
1871
Abramo Bagnaraea947882011-03-08 16:41:52 +00001872// Helper function: returns true if QT is or contains a type
1873// having a postfix component.
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001874static bool typeIsPostfix(QualType QT) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00001875 while (true) {
1876 const Type* T = QT.getTypePtr();
1877 switch (T->getTypeClass()) {
1878 default:
1879 return false;
1880 case Type::Pointer:
1881 QT = cast<PointerType>(T)->getPointeeType();
1882 break;
1883 case Type::BlockPointer:
1884 QT = cast<BlockPointerType>(T)->getPointeeType();
1885 break;
1886 case Type::MemberPointer:
1887 QT = cast<MemberPointerType>(T)->getPointeeType();
1888 break;
1889 case Type::LValueReference:
1890 case Type::RValueReference:
1891 QT = cast<ReferenceType>(T)->getPointeeType();
1892 break;
1893 case Type::PackExpansion:
1894 QT = cast<PackExpansionType>(T)->getPattern();
1895 break;
1896 case Type::Paren:
1897 case Type::ConstantArray:
1898 case Type::DependentSizedArray:
1899 case Type::IncompleteArray:
1900 case Type::VariableArray:
1901 case Type::FunctionProto:
1902 case Type::FunctionNoProto:
1903 return true;
1904 }
1905 }
1906}
1907
Abramo Bagnaraea947882011-03-08 16:41:52 +00001908SourceRange DeclaratorDecl::getSourceRange() const {
1909 SourceLocation RangeEnd = getLocation();
1910 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001911 // If the declaration has no name or the type extends past the name take the
1912 // end location of the type.
1913 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001914 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1915 }
1916 return SourceRange(getOuterLocStart(), RangeEnd);
1917}
1918
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001919void QualifierInfo::setTemplateParameterListsInfo(
1920 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001921 // Free previous template parameters (if any).
1922 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001923 Context.Deallocate(TemplParamLists);
Craig Topper36250ad2014-05-12 05:36:57 +00001924 TemplParamLists = nullptr;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001925 NumTemplParamLists = 0;
1926 }
1927 // Set info on matched template parameter lists (if any).
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001928 if (!TPLists.empty()) {
1929 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1930 NumTemplParamLists = TPLists.size();
1931 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001932 }
1933}
1934
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001935//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001936// VarDecl Implementation
1937//===----------------------------------------------------------------------===//
1938
Sebastian Redl833ef452010-01-26 22:01:41 +00001939const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1940 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001941 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001942 case SC_Auto: return "auto";
1943 case SC_Extern: return "extern";
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001944 case SC_PrivateExtern: return "__private_extern__";
1945 case SC_Register: return "register";
1946 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001947 }
1948
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001949 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001950}
1951
Richard Smith053f6c62014-05-16 23:01:30 +00001952VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1953 SourceLocation StartLoc, SourceLocation IdLoc,
1954 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1955 StorageClass SC)
1956 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001957 redeclarable_base(C) {
Benjamin Kramera939c232014-03-15 18:54:13 +00001958 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1959 "VarDeclBitfields too large!");
1960 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1961 "ParmVarDeclBitfields too large!");
David Majnemerfa7bc782015-05-19 00:57:16 +00001962 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1963 "NonParmVarDeclBitfields too large!");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001964 AllBits = 0;
1965 VarDeclBits.SClass = SC;
1966 // Everything else is implicitly initialized to false.
1967}
1968
Abramo Bagnaradff19302011-03-08 08:55:46 +00001969VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1970 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001971 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001972 StorageClass S) {
Richard Smith053f6c62014-05-16 23:01:30 +00001973 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001974}
1975
Douglas Gregor72172e92012-01-05 21:55:30 +00001976VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00001977 return new (C, ID)
1978 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1979 QualType(), nullptr, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001980}
1981
Douglas Gregorbf62d642010-12-06 18:36:25 +00001982void VarDecl::setStorageClass(StorageClass SC) {
1983 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001984 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001985}
1986
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001987VarDecl::TLSKind VarDecl::getTLSKind() const {
1988 switch (VarDeclBits.TSCSpec) {
1989 case TSCS_unspecified:
Samuel Antaof8b50122015-07-13 22:54:53 +00001990 if (!hasAttr<ThreadAttr>() &&
1991 !(getASTContext().getLangOpts().OpenMPUseTLS &&
1992 getASTContext().getTargetInfo().isTLSSupported() &&
1993 hasAttr<OMPThreadPrivateDeclAttr>()))
David Majnemer1b5baff2015-05-14 05:19:23 +00001994 return TLS_None;
Samuel Antaof8b50122015-07-13 22:54:53 +00001995 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1996 LangOptions::MSVC2015)) ||
1997 hasAttr<OMPThreadPrivateDeclAttr>())
David Majnemer1b5baff2015-05-14 05:19:23 +00001998 ? TLS_Dynamic
1999 : TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00002000 case TSCS___thread: // Fall through.
2001 case TSCS__Thread_local:
Samuel Antaof8b50122015-07-13 22:54:53 +00002002 return TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00002003 case TSCS_thread_local:
2004 return TLS_Dynamic;
2005 }
2006 llvm_unreachable("Unknown thread storage class specifier!");
2007}
2008
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002009SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00002010 if (const Expr *Init = getInit()) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002011 SourceLocation InitEnd = Init->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002012 // If Init is implicit, ignore its source range and fallback on
Nico Weberbbe13942013-01-22 17:00:09 +00002013 // DeclaratorDecl::getSourceRange() to handle postfix elements.
2014 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00002015 return SourceRange(getOuterLocStart(), InitEnd);
2016 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00002017 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002018}
2019
Rafael Espindola88510672013-01-04 21:18:45 +00002020template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00002021static LanguageLinkage getDeclLanguageLinkage(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00002022 // C++ [dcl.link]p1: All function types, function names with external linkage,
2023 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00002024 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00002025 return NoLanguageLinkage;
2026
2027 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00002028 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00002029 ASTContext &Context = D.getASTContext();
2030 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00002031 return CLanguageLinkage;
2032
Rafael Espindola5bda63f2013-02-14 01:47:04 +00002033 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
2034 // language linkage of the names of class members and the function type of
2035 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00002036 const DeclContext *DC = D.getDeclContext();
2037 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002038 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00002039
2040 // If the first decl is in an extern "C" context, any other redeclaration
2041 // will have C language linkage. If the first one is not in an extern "C"
2042 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00002043 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00002044 return CLanguageLinkage;
2045 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00002046}
2047
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002048template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00002049static bool isDeclExternC(const T &D) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002050 // Since the context is ignored for class members, they can only have C++
2051 // language linkage or no language linkage.
2052 const DeclContext *DC = D.getDeclContext();
2053 if (DC->isRecord()) {
2054 assert(D.getASTContext().getLangOpts().CPlusPlus);
2055 return false;
2056 }
2057
2058 return D.getLanguageLinkage() == CLanguageLinkage;
2059}
2060
Rafael Espindolaf4187652013-02-14 01:18:37 +00002061LanguageLinkage VarDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00002062 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002063}
2064
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002065bool VarDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00002066 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002067}
2068
Rafael Espindola593537a2013-05-05 20:15:21 +00002069bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002070 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002071}
2072
2073bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002074 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002075}
2076
Rafael Espindola8db352d2013-10-17 15:37:26 +00002077VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002078
Nico Weber7f5015a2015-04-15 21:53:00 +00002079VarDecl::DefinitionKind
2080VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
Richard Smitha22d9a52017-12-02 00:55:48 +00002081 if (isThisDeclarationADemotedDefinition())
2082 return DeclarationOnly;
2083
Sebastian Redl35351a92010-01-31 22:27:38 +00002084 // C++ [basic.def]p2:
2085 // A declaration is a definition unless [...] it contains the 'extern'
2086 // specifier or a linkage-specification and neither an initializer [...],
Richard Smith62f19e72016-06-25 00:15:56 +00002087 // it declares a non-inline static data member in a class declaration [...],
2088 // it declares a static data member outside a class definition and the variable
2089 // was defined within the class with the constexpr specifier [...],
Richard Smith8809a0c2013-09-27 20:14:12 +00002090 // C++1y [temp.expl.spec]p15:
2091 // An explicit specialization of a static data member or an explicit
2092 // specialization of a static data member template is a definition if the
2093 // declaration includes an initializer; otherwise, it is a declaration.
2094 //
2095 // FIXME: How do you declare (but not define) a partial specialization of
2096 // a static data member template outside the containing class?
Sebastian Redl35351a92010-01-31 22:27:38 +00002097 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002098 if (isOutOfLine() &&
Richard Smith62f19e72016-06-25 00:15:56 +00002099 !(getCanonicalDecl()->isInline() &&
2100 getCanonicalDecl()->isConstexpr()) &&
Richard Smith8809a0c2013-09-27 20:14:12 +00002101 (hasInit() ||
2102 // If the first declaration is out-of-line, this may be an
2103 // instantiation of an out-of-line partial specialization of a variable
2104 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00002105 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00002106 ? getTemplateSpecializationKind() == TSK_Undeclared
2107 : getTemplateSpecializationKind() !=
2108 TSK_ExplicitSpecialization) ||
2109 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00002110 return Definition;
Richard Smith62f19e72016-06-25 00:15:56 +00002111 else if (!isOutOfLine() && isInline())
2112 return Definition;
Sebastian Redl35351a92010-01-31 22:27:38 +00002113 else
2114 return DeclarationOnly;
2115 }
2116 // C99 6.7p5:
2117 // A definition of an identifier is a declaration for that identifier that
2118 // [...] causes storage to be reserved for that object.
2119 // Note: that applies for all non-file-scope objects.
2120 // C99 6.9.2p1:
2121 // If the declaration of an identifier for an object has file scope and an
2122 // initializer, the declaration is an external definition for the identifier
2123 if (hasInit())
2124 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00002125
Dmitry Polukhin85eda122016-04-11 07:48:59 +00002126 if (hasDefiningAttr())
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002127 return Definition;
2128
David Majnemerdd0bed12015-05-14 05:19:20 +00002129 if (const auto *SAA = getAttr<SelectAnyAttr>())
2130 if (!SAA->isInherited())
2131 return Definition;
2132
Richard Smith8809a0c2013-09-27 20:14:12 +00002133 // A variable template specialization (other than a static data member
2134 // template or an explicit specialization) is a declaration until we
2135 // instantiate its initializer.
Richard Smith435e6472017-12-02 02:48:42 +00002136 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2137 if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2138 !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2139 !VTSD->IsCompleteDefinition)
2140 return DeclarationOnly;
2141 }
Richard Smith8809a0c2013-09-27 20:14:12 +00002142
Nico Weber608e7682015-04-15 23:04:24 +00002143 if (hasExternalStorage())
Sebastian Redl35351a92010-01-31 22:27:38 +00002144 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00002145
Rafael Espindolabff59562013-04-25 12:11:36 +00002146 // [dcl.link] p7:
2147 // A declaration directly contained in a linkage-specification is treated
2148 // as if it contains the extern specifier for the purpose of determining
2149 // the linkage of the declared name and whether it is a definition.
Nico Weber608e7682015-04-15 23:04:24 +00002150 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00002151 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00002152
Sebastian Redl35351a92010-01-31 22:27:38 +00002153 // C99 6.9.2p2:
2154 // A declaration of an object that has file scope without an initializer,
2155 // and without a storage class specifier or the scs 'static', constitutes
2156 // a tentative definition.
2157 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002158 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00002159 return TentativeDefinition;
2160
2161 // What's left is (in C, block-scope) declarations without initializers or
2162 // external storage. These are definitions.
2163 return Definition;
2164}
2165
Sebastian Redl35351a92010-01-31 22:27:38 +00002166VarDecl *VarDecl::getActingDefinition() {
2167 DefinitionKind Kind = isThisDeclarationADefinition();
2168 if (Kind != TentativeDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00002169 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002170
Craig Topper36250ad2014-05-12 05:36:57 +00002171 VarDecl *LastTentative = nullptr;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002172 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002173 for (auto I : First->redecls()) {
2174 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00002175 if (Kind == Definition)
Craig Topper36250ad2014-05-12 05:36:57 +00002176 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002177 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00002178 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00002179 }
2180 return LastTentative;
2181}
2182
Daniel Dunbar9d355812012-03-09 01:51:51 +00002183VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002184 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002185 for (auto I : First->redecls()) {
2186 if (I->isThisDeclarationADefinition(C) == Definition)
2187 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002188 }
Craig Topper36250ad2014-05-12 05:36:57 +00002189 return nullptr;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002190}
2191
Daniel Dunbar9d355812012-03-09 01:51:51 +00002192VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00002193 DefinitionKind Kind = DeclarationOnly;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002194
Rafael Espindola8db352d2013-10-17 15:37:26 +00002195 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002196 for (auto I : First->redecls()) {
2197 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00002198 if (Kind == Definition)
2199 break;
2200 }
John McCall37bb6c92010-10-29 22:22:43 +00002201
2202 return Kind;
2203}
2204
Sebastian Redl5ca79842010-02-01 20:16:42 +00002205const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002206 for (auto I : redecls()) {
2207 if (auto Expr = I->getInit()) {
2208 D = I;
2209 return Expr;
2210 }
Sebastian Redl833ef452010-01-26 22:01:41 +00002211 }
Craig Topper36250ad2014-05-12 05:36:57 +00002212 return nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002213}
2214
Chandler Carruth813faed2015-12-30 02:51:00 +00002215bool VarDecl::hasInit() const {
2216 if (auto *P = dyn_cast<ParmVarDecl>(this))
2217 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2218 return false;
2219
2220 return !Init.isNull();
2221}
2222
2223Expr *VarDecl::getInit() {
2224 if (!hasInit())
2225 return nullptr;
2226
2227 if (auto *S = Init.dyn_cast<Stmt *>())
2228 return cast<Expr>(S);
2229
2230 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2231}
2232
2233Stmt **VarDecl::getInitAddress() {
2234 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2235 return &ES->Value;
2236
2237 return Init.getAddrOfPtr1();
2238}
2239
Richard Smitha6e8b682019-09-04 20:30:37 +00002240VarDecl *VarDecl::getInitializingDeclaration() {
2241 VarDecl *Def = nullptr;
2242 for (auto I : redecls()) {
2243 if (I->hasInit())
2244 return I;
2245
2246 if (I->isThisDeclarationADefinition()) {
2247 if (isStaticDataMember())
2248 return I;
2249 else
2250 Def = I;
2251 }
2252 }
2253 return Def;
2254}
2255
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002256bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002257 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002258 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00002259
2260 if (!isStaticDataMember())
2261 return false;
2262
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002263 // If this static data member was instantiated from a static data member of
Fangrui Song6907ce22018-07-30 19:24:48 +00002264 // a class template, check whether that static data member was defined
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002265 // out-of-line.
2266 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2267 return VD->isOutOfLine();
Fangrui Song6907ce22018-07-30 19:24:48 +00002268
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002269 return false;
2270}
2271
Douglas Gregord5058122010-02-11 01:19:42 +00002272void VarDecl::setInit(Expr *I) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002273 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
Sebastian Redl833ef452010-01-26 22:01:41 +00002274 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00002275 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00002276 }
2277
2278 Init = I;
2279}
2280
Richard Smith715f7a12019-06-11 17:50:32 +00002281bool VarDecl::mightBeUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002282 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00002283
Richard Smith35ecb362012-03-02 04:14:40 +00002284 if (!Lang.CPlusPlus)
2285 return false;
2286
Richard Smith715f7a12019-06-11 17:50:32 +00002287 // Function parameters are never usable in constant expressions.
2288 if (isa<ParmVarDecl>(this))
2289 return false;
2290
Richard Smith35ecb362012-03-02 04:14:40 +00002291 // In C++11, any variable of reference type can be used in a constant
2292 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002293 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00002294 return true;
2295
2296 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00002297 // not require the variable to be non-volatile, but we consider this to be a
2298 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00002299 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00002300 return false;
2301
2302 // In C++, const, non-volatile variables of integral or enumeration types
2303 // can be used in constant expressions.
2304 if (getType()->isIntegralOrEnumerationType())
2305 return true;
2306
Richard Smith35ecb362012-03-02 04:14:40 +00002307 // Additionally, in C++11, non-volatile constexpr variables can be used in
2308 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002309 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00002310}
2311
Richard Smith715f7a12019-06-11 17:50:32 +00002312bool VarDecl::isUsableInConstantExpressions(ASTContext &Context) const {
2313 // C++2a [expr.const]p3:
2314 // A variable is usable in constant expressions after its initializing
2315 // declaration is encountered...
2316 const VarDecl *DefVD = nullptr;
2317 const Expr *Init = getAnyInitializer(DefVD);
Richard Smith94bc88e2019-06-17 21:46:17 +00002318 if (!Init || Init->isValueDependent() || getType()->isDependentType())
Richard Smith715f7a12019-06-11 17:50:32 +00002319 return false;
2320 // ... if it is a constexpr variable, or it is of reference type or of
2321 // const-qualified integral or enumeration type, ...
2322 if (!DefVD->mightBeUsableInConstantExpressions(Context))
2323 return false;
2324 // ... and its initializer is a constant initializer.
2325 return DefVD->checkInitIsICE();
2326}
2327
Richard Smithd0b4dd62011-12-19 06:19:21 +00002328/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2329/// form, which contains extra information on the evaluated value of the
2330/// initializer.
2331EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002332 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002333 if (!Eval) {
Manuel Klimeka7328992013-06-03 13:51:33 +00002334 // Note: EvaluatedStmt contains an APValue, which usually holds
2335 // resources not allocated from the ASTContext. We need to do some
2336 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2337 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002338 Eval = new (getASTContext()) EvaluatedStmt;
Chandler Carruth813faed2015-12-30 02:51:00 +00002339 Eval->Value = Init.get<Stmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002340 Init = Eval;
2341 }
2342 return Eval;
2343}
2344
Richard Smithdafff942012-01-14 04:30:29 +00002345APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002346 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00002347 return evaluateValue(Notes);
2348}
2349
2350APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002351 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002352 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2353
2354 // We only produce notes indicating why an initializer is non-constant the
2355 // first time it is evaluated. FIXME: The notes won't always be emitted the
2356 // first time we try evaluation, so might not be produced at all.
2357 if (Eval->WasEvaluated)
Richard Smithe637cbe2019-05-21 23:15:18 +00002358 return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002359
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002360 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002361 assert(!Init->isValueDependent());
2362
2363 if (Eval->IsEvaluating) {
2364 // FIXME: Produce a diagnostic for self-initialization.
2365 Eval->CheckedICE = true;
2366 Eval->IsICE = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002367 return nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002368 }
2369
2370 Eval->IsEvaluating = true;
2371
2372 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2373 this, Notes);
2374
Manuel Klimeka7328992013-06-03 13:51:33 +00002375 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2376 // or that it's empty (so that there's nothing to clean up) if evaluation
2377 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002378 if (!Result)
2379 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00002380 else if (Eval->Evaluated.needsCleanup())
George Burgess IVb61bfbd2017-02-14 05:37:36 +00002381 getASTContext().addDestruction(&Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002382
2383 Eval->IsEvaluating = false;
2384 Eval->WasEvaluated = true;
2385
2386 // In C++11, we have determined whether the initializer was a constant
2387 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002388 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002389 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00002390 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002391 }
2392
Craig Topper36250ad2014-05-12 05:36:57 +00002393 return Result ? &Eval->Evaluated : nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002394}
2395
Chandler Carruth813faed2015-12-30 02:51:00 +00002396APValue *VarDecl::getEvaluatedValue() const {
2397 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2398 if (Eval->WasEvaluated)
2399 return &Eval->Evaluated;
2400
2401 return nullptr;
2402}
2403
2404bool VarDecl::isInitKnownICE() const {
2405 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2406 return Eval->CheckedICE;
2407
2408 return false;
2409}
2410
2411bool VarDecl::isInitICE() const {
2412 assert(isInitKnownICE() &&
2413 "Check whether we already know that the initializer is an ICE");
2414 return Init.get<EvaluatedStmt *>()->IsICE;
2415}
2416
Richard Smithd0b4dd62011-12-19 06:19:21 +00002417bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00002418 // Initializers of weak variables are never ICEs.
2419 if (isWeak())
2420 return false;
2421
Richard Smithd0b4dd62011-12-19 06:19:21 +00002422 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2423 if (Eval->CheckedICE)
2424 // We have already checked whether this subexpression is an
2425 // integral constant expression.
2426 return Eval->IsICE;
2427
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002428 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002429 assert(!Init->isValueDependent());
2430
2431 // In C++11, evaluate the initializer to check whether it's a constant
2432 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002433 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002434 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002435 evaluateValue(Notes);
2436 return Eval->IsICE;
2437 }
2438
2439 // It's an ICE whether or not the definition we found is
2440 // out-of-line. See DR 721 and the discussion in Clang PR
2441 // 6206 for details.
2442
2443 if (Eval->CheckingICE)
2444 return false;
2445 Eval->CheckingICE = true;
2446
2447 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2448 Eval->CheckingICE = false;
2449 Eval->CheckedICE = true;
2450 return Eval->IsICE;
2451}
2452
Richard Smithb2997f52019-05-21 20:10:50 +00002453bool VarDecl::isParameterPack() const {
2454 return isa<PackExpansionType>(getType());
2455}
2456
Richard Smith2195ec92017-04-21 01:15:13 +00002457template<typename DeclT>
2458static DeclT *getDefinitionOrSelf(DeclT *D) {
2459 assert(D);
2460 if (auto *Def = D->getDefinition())
2461 return Def;
2462 return D;
2463}
2464
Akira Hatanaka8e57b072018-10-01 21:51:28 +00002465bool VarDecl::isEscapingByref() const {
2466 return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
2467}
2468
2469bool VarDecl::isNonEscapingByref() const {
2470 return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
2471}
2472
Richard Smithedbc6e92016-10-14 21:41:24 +00002473VarDecl *VarDecl::getTemplateInstantiationPattern() const {
Richard Smitha6b41d72019-05-03 23:51:38 +00002474 const VarDecl *VD = this;
Richard Smithedbc6e92016-10-14 21:41:24 +00002475
Richard Smitha6b41d72019-05-03 23:51:38 +00002476 // If this is an instantiated member, walk back to the template from which
2477 // it was instantiated.
2478 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) {
Richard Smithedbc6e92016-10-14 21:41:24 +00002479 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
Richard Smitha6b41d72019-05-03 23:51:38 +00002480 VD = VD->getInstantiatedFromStaticDataMember();
Richard Smithedbc6e92016-10-14 21:41:24 +00002481 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2482 VD = NewVD;
Richard Smithedbc6e92016-10-14 21:41:24 +00002483 }
2484 }
2485
Richard Smitha6b41d72019-05-03 23:51:38 +00002486 // If it's an instantiated variable template specialization, find the
2487 // template or partial specialization from which it was instantiated.
2488 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2489 if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
2490 auto From = VDTemplSpec->getInstantiatedFrom();
2491 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2492 while (!VTD->isMemberSpecialization()) {
2493 auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
2494 if (!NewVTD)
2495 break;
2496 VTD = NewVTD;
2497 }
2498 return getDefinitionOrSelf(VTD->getTemplatedDecl());
2499 }
2500 if (auto *VTPSD =
2501 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2502 while (!VTPSD->isMemberSpecialization()) {
2503 auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
2504 if (!NewVTPSD)
2505 break;
2506 VTPSD = NewVTPSD;
2507 }
2508 return getDefinitionOrSelf<VarDecl>(VTPSD);
2509 }
2510 }
2511 }
2512
2513 // If this is the pattern of a variable template, find where it was
2514 // instantiated from. FIXME: Is this necessary?
2515 if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {
2516 while (!VarTemplate->isMemberSpecialization()) {
2517 auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
2518 if (!NewVT)
Richard Smithedbc6e92016-10-14 21:41:24 +00002519 break;
Richard Smitha6b41d72019-05-03 23:51:38 +00002520 VarTemplate = NewVT;
Richard Smithedbc6e92016-10-14 21:41:24 +00002521 }
2522
Richard Smith2195ec92017-04-21 01:15:13 +00002523 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
Richard Smithedbc6e92016-10-14 21:41:24 +00002524 }
Richard Smitha6b41d72019-05-03 23:51:38 +00002525
2526 if (VD == this)
2527 return nullptr;
2528 return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
Richard Smithedbc6e92016-10-14 21:41:24 +00002529}
2530
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002531VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002532 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002533 return cast<VarDecl>(MSI->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002534
2535 return nullptr;
Douglas Gregor86d142a2009-10-08 07:24:58 +00002536}
2537
Douglas Gregor3c74d412009-10-14 20:14:33 +00002538TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002539 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002540 return Spec->getSpecializationKind();
2541
Sebastian Redl35351a92010-01-31 22:27:38 +00002542 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002543 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002544
Douglas Gregor86d142a2009-10-08 07:24:58 +00002545 return TSK_Undeclared;
2546}
2547
Richard Smitha6b41d72019-05-03 23:51:38 +00002548TemplateSpecializationKind
2549VarDecl::getTemplateSpecializationKindForInstantiation() const {
2550 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2551 return MSI->getTemplateSpecializationKind();
2552
2553 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2554 return Spec->getSpecializationKind();
2555
2556 return TSK_Undeclared;
2557}
2558
Richard Smith8809a0c2013-09-27 20:14:12 +00002559SourceLocation VarDecl::getPointOfInstantiation() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002560 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Richard Smith8809a0c2013-09-27 20:14:12 +00002561 return Spec->getPointOfInstantiation();
2562
2563 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2564 return MSI->getPointOfInstantiation();
2565
2566 return SourceLocation();
2567}
2568
Larisse Voufo39a1e502013-08-06 01:03:05 +00002569VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2570 return getASTContext().getTemplateOrSpecializationInfo(this)
2571 .dyn_cast<VarTemplateDecl *>();
2572}
2573
2574void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2575 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2576}
2577
Justin Lebar5489f852018-05-17 16:15:07 +00002578bool VarDecl::isKnownToBeDefined() const {
2579 const auto &LangOpts = getASTContext().getLangOpts();
2580 // In CUDA mode without relocatable device code, variables of form 'extern
2581 // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2582 // memory pool. These are never undefined variables, even if they appear
2583 // inside of an anon namespace or static function.
2584 //
2585 // With CUDA relocatable device code enabled, these variables don't get
2586 // special handling; they're treated like regular extern variables.
Yaxun Liu97670892018-10-02 17:48:54 +00002587 if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
Justin Lebar5489f852018-05-17 16:15:07 +00002588 hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
2589 isa<IncompleteArrayType>(getType()))
2590 return true;
2591
2592 return hasDefinition();
2593}
2594
Erik Pilkington5a559e62018-08-21 17:24:06 +00002595bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
2596 return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||
2597 (!Ctx.getLangOpts().RegisterStaticDestructors &&
2598 !hasAttr<AlwaysDestroyAttr>()));
2599}
2600
Richard Smith2b4fa532019-09-29 05:08:46 +00002601QualType::DestructionKind
2602VarDecl::needsDestruction(const ASTContext &Ctx) const {
2603 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2604 if (Eval->HasConstantDestruction)
2605 return QualType::DK_none;
2606
2607 if (isNoDestroy(Ctx))
2608 return QualType::DK_none;
2609
2610 return getType().isDestructedType();
2611}
2612
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002613MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002614 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002615 // FIXME: Remove ?
2616 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2617 return getASTContext().getTemplateOrSpecializationInfo(this)
2618 .dyn_cast<MemberSpecializationInfo *>();
Craig Topper36250ad2014-05-12 05:36:57 +00002619 return nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002620}
2621
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002622void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2623 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002624 assert((isa<VarTemplateSpecializationDecl>(this) ||
2625 getMemberSpecializationInfo()) &&
2626 "not a variable or static data member template specialization");
2627
Larisse Voufo39a1e502013-08-06 01:03:05 +00002628 if (VarTemplateSpecializationDecl *Spec =
2629 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2630 Spec->setSpecializationKind(TSK);
Richard Smitha6b41d72019-05-03 23:51:38 +00002631 if (TSK != TSK_ExplicitSpecialization &&
2632 PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00002633 Spec->getPointOfInstantiation().isInvalid()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002634 Spec->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00002635 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2636 L->InstantiationRequested(this);
2637 }
Richard Smitha6b41d72019-05-03 23:51:38 +00002638 } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002639 MSI->setTemplateSpecializationKind(TSK);
2640 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00002641 MSI->getPointOfInstantiation().isInvalid()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002642 MSI->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00002643 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2644 L->InstantiationRequested(this);
2645 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002646 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002647}
2648
2649void
2650VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2651 TemplateSpecializationKind TSK) {
2652 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2653 "Previous template or instantiation?");
2654 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002655}
2656
Sebastian Redl833ef452010-01-26 22:01:41 +00002657//===----------------------------------------------------------------------===//
2658// ParmVarDecl Implementation
2659//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002660
Sebastian Redl833ef452010-01-26 22:01:41 +00002661ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002662 SourceLocation StartLoc,
2663 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002664 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002665 StorageClass S, Expr *DefArg) {
Richard Smith053f6c62014-05-16 23:01:30 +00002666 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smithf7981722013-11-22 09:01:48 +00002667 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002668}
2669
Reid Kleckner8a365022013-06-24 17:51:48 +00002670QualType ParmVarDecl::getOriginalType() const {
2671 TypeSourceInfo *TSI = getTypeSourceInfo();
2672 QualType T = TSI ? TSI->getType() : getType();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002673 if (const auto *DT = dyn_cast<DecayedType>(T))
Reid Kleckner8a365022013-06-24 17:51:48 +00002674 return DT->getOriginalType();
2675 return T;
2676}
2677
Douglas Gregor72172e92012-01-05 21:55:30 +00002678ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00002679 return new (C, ID)
2680 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2681 nullptr, QualType(), nullptr, SC_None, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00002682}
2683
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002684SourceRange ParmVarDecl::getSourceRange() const {
2685 if (!hasInheritedDefaultArg()) {
2686 SourceRange ArgRange = getDefaultArgRange();
2687 if (ArgRange.isValid())
2688 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2689 }
2690
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002691 // DeclaratorDecl considers the range of postfix types as overlapping with the
2692 // declaration name, but this is not the case with parameters in ObjC methods.
2693 if (isa<ObjCMethodDecl>(getDeclContext()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002694 return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002695
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002696 return DeclaratorDecl::getSourceRange();
2697}
2698
Sebastian Redl833ef452010-01-26 22:01:41 +00002699Expr *ParmVarDecl::getDefaultArg() {
2700 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2701 assert(!hasUninstantiatedDefaultArg() &&
2702 "Default argument is not yet instantiated!");
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002703
Sebastian Redl833ef452010-01-26 22:01:41 +00002704 Expr *Arg = getInit();
Bill Wendling7c44da22018-10-31 03:48:47 +00002705 if (auto *E = dyn_cast_or_null<FullExpr>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002706 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002707
Sebastian Redl833ef452010-01-26 22:01:41 +00002708 return Arg;
2709}
2710
Chandler Carruth813faed2015-12-30 02:51:00 +00002711void ParmVarDecl::setDefaultArg(Expr *defarg) {
2712 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2713 Init = defarg;
2714}
Sebastian Redl833ef452010-01-26 22:01:41 +00002715
Chandler Carruth813faed2015-12-30 02:51:00 +00002716SourceRange ParmVarDecl::getDefaultArgRange() const {
2717 switch (ParmVarDeclBits.DefaultArgKind) {
2718 case DAK_None:
2719 case DAK_Unparsed:
2720 // Nothing we can do here.
2721 return SourceRange();
2722
2723 case DAK_Uninstantiated:
Sebastian Redl833ef452010-01-26 22:01:41 +00002724 return getUninstantiatedDefaultArg()->getSourceRange();
2725
Chandler Carruth813faed2015-12-30 02:51:00 +00002726 case DAK_Normal:
2727 if (const Expr *E = getInit())
2728 return E->getSourceRange();
2729
2730 // Missing an actual expression, may be invalid.
2731 return SourceRange();
2732 }
2733 llvm_unreachable("Invalid default argument kind.");
2734}
2735
2736void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2737 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2738 Init = arg;
2739}
2740
2741Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2742 assert(hasUninstantiatedDefaultArg() &&
2743 "Wrong kind of initialization expression!");
2744 return cast_or_null<Expr>(Init.get<Stmt *>());
2745}
2746
2747bool ParmVarDecl::hasDefaultArg() const {
2748 // FIXME: We should just return false for DAK_None here once callers are
2749 // prepared for the case that we encountered an invalid default argument and
2750 // were unable to even build an invalid expression.
2751 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2752 !Init.isNull();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002753}
2754
Ted Kremenek540017e2011-10-06 05:00:56 +00002755void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2756 getASTContext().setParameterIndex(this, parameterIndex);
2757 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2758}
2759
2760unsigned ParmVarDecl::getParameterIndexLarge() const {
2761 return getASTContext().getParameterIndex(this);
2762}
2763
Nuno Lopes394ec982008-12-17 23:39:55 +00002764//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002765// FunctionDecl Implementation
2766//===----------------------------------------------------------------------===//
2767
Erich Keane9c665062018-08-01 21:02:40 +00002768FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,
2769 SourceLocation StartLoc,
2770 const DeclarationNameInfo &NameInfo, QualType T,
2771 TypeSourceInfo *TInfo, StorageClass S,
Gauthier Harnisch796ed032019-06-14 08:56:20 +00002772 bool isInlineSpecified,
2773 ConstexprSpecKind ConstexprKind)
Erich Keane9c665062018-08-01 21:02:40 +00002774 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
2775 StartLoc),
2776 DeclContext(DK), redeclarable_base(C), ODRHash(0),
2777 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002778 assert(T.isNull() || T->isFunctionType());
Bruno Ricci0b639da2018-12-03 13:04:10 +00002779 FunctionDeclBits.SClass = S;
2780 FunctionDeclBits.IsInline = isInlineSpecified;
2781 FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
Bruno Ricci0b639da2018-12-03 13:04:10 +00002782 FunctionDeclBits.IsVirtualAsWritten = false;
2783 FunctionDeclBits.IsPure = false;
2784 FunctionDeclBits.HasInheritedPrototype = false;
2785 FunctionDeclBits.HasWrittenPrototype = true;
2786 FunctionDeclBits.IsDeleted = false;
2787 FunctionDeclBits.IsTrivial = false;
2788 FunctionDeclBits.IsTrivialForCall = false;
2789 FunctionDeclBits.IsDefaulted = false;
2790 FunctionDeclBits.IsExplicitlyDefaulted = false;
2791 FunctionDeclBits.HasImplicitReturnZero = false;
2792 FunctionDeclBits.IsLateTemplateParsed = false;
Gauthier Harnisch796ed032019-06-14 08:56:20 +00002793 FunctionDeclBits.ConstexprKind = ConstexprKind;
Bruno Ricci0b639da2018-12-03 13:04:10 +00002794 FunctionDeclBits.InstantiationIsPending = false;
2795 FunctionDeclBits.UsesSEHTry = false;
2796 FunctionDeclBits.HasSkippedBody = false;
2797 FunctionDeclBits.WillHaveBody = false;
2798 FunctionDeclBits.IsMultiVersion = false;
2799 FunctionDeclBits.IsCopyDeductionCandidate = false;
2800 FunctionDeclBits.HasODRHash = false;
Erich Keane9c665062018-08-01 21:02:40 +00002801}
2802
Benjamin Kramer9170e912013-02-22 15:46:01 +00002803void FunctionDecl::getNameForDiagnostic(
2804 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2805 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002806 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2807 if (TemplateArgs)
Serge Pavlov03e672c2017-11-28 16:14:14 +00002808 printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002809}
2810
Ted Kremenek186a0742010-04-29 16:49:01 +00002811bool FunctionDecl::isVariadic() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002812 if (const auto *FT = getType()->getAs<FunctionProtoType>())
Ted Kremenek186a0742010-04-29 16:49:01 +00002813 return FT->isVariadic();
2814 return false;
2815}
2816
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002817bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002818 for (auto I : redecls()) {
Serge Pavlov9a618e12017-02-15 12:30:35 +00002819 if (I->doesThisDeclarationHaveABody()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002820 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002821 return true;
2822 }
2823 }
2824
2825 return false;
2826}
2827
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002828bool FunctionDecl::hasTrivialBody() const
2829{
2830 Stmt *S = getBody();
2831 if (!S) {
2832 // Since we don't have a body for this function, we don't know if it's
2833 // trivial or not.
2834 return false;
2835 }
2836
2837 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2838 return true;
2839 return false;
2840}
2841
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002842bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002843 for (auto I : redecls()) {
Serge Pavlov10673c92017-06-04 12:53:12 +00002844 if (I->isThisDeclarationADefinition()) {
2845 Definition = I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002846 return true;
2847 }
2848 }
2849
2850 return false;
2851}
2852
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002853Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002854 if (!hasBody(Definition))
Craig Topper36250ad2014-05-12 05:36:57 +00002855 return nullptr;
Rafael Espindola44503012013-10-19 01:37:17 +00002856
2857 if (Definition->Body)
2858 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002859
Craig Topper36250ad2014-05-12 05:36:57 +00002860 return nullptr;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002861}
2862
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002863void FunctionDecl::setBody(Stmt *B) {
2864 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002865 if (B)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002866 EndRangeLoc = B->getEndLoc();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002867}
2868
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002869void FunctionDecl::setPure(bool P) {
Erich Keane9c665062018-08-01 21:02:40 +00002870 FunctionDeclBits.IsPure = P;
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002871 if (P)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002872 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002873 Parent->markedVirtualFunctionPure();
2874}
2875
Richard Smith8d0dc312013-07-21 23:12:18 +00002876template<std::size_t Len>
2877static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2878 IdentifierInfo *II = ND->getIdentifier();
2879 return II && II->isStr(Str);
2880}
2881
Douglas Gregor16618f22009-09-12 00:17:51 +00002882bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002883 const TranslationUnitDecl *tunit =
2884 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2885 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002886 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002887 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002888}
2889
David Majnemerc729b0b2013-09-16 22:44:20 +00002890bool FunctionDecl::isMSVCRTEntryPoint() const {
2891 const TranslationUnitDecl *TUnit =
2892 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2893 if (!TUnit)
2894 return false;
2895
2896 // Even though we aren't really targeting MSVCRT if we are freestanding,
2897 // semantic analysis for these functions remains the same.
2898
2899 // MSVCRT entry points only exist on MSVCRT targets.
2900 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2901 return false;
2902
2903 // Nameless functions like constructors cannot be entry points.
2904 if (!getIdentifier())
2905 return false;
2906
2907 return llvm::StringSwitch<bool>(getName())
2908 .Cases("main", // an ANSI console app
2909 "wmain", // a Unicode console App
2910 "WinMain", // an ANSI GUI app
2911 "wWinMain", // a Unicode GUI app
2912 "DllMain", // a DLL
2913 true)
2914 .Default(false);
2915}
2916
John McCall53ffd372011-05-15 17:49:20 +00002917bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2918 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2919 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2920 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2921 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2922 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2923
Richard Smithf6004412014-01-19 23:25:37 +00002924 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2925 return false;
John McCall53ffd372011-05-15 17:49:20 +00002926
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002927 const auto *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002928 if (proto->getNumParams() != 2 || proto->isVariadic())
2929 return false;
John McCall53ffd372011-05-15 17:49:20 +00002930
2931 ASTContext &Context =
2932 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2933 ->getASTContext();
2934
2935 // The result type and first argument type are constant across all
2936 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002937 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002938}
2939
Akira Hatanakacae83f72017-06-29 18:48:40 +00002940bool FunctionDecl::isReplaceableGlobalAllocationFunction(bool *IsAligned) const {
Richard Smith8d0dc312013-07-21 23:12:18 +00002941 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2942 return false;
2943 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2944 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2945 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2946 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2947 return false;
2948
2949 if (isa<CXXRecordDecl>(getDeclContext()))
2950 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002951
2952 // This can only fail for an invalid 'operator new' declaration.
2953 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2954 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002955
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002956 const auto *FPT = getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00002957 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002958 return false;
2959
2960 // If this is a single-parameter function, it must be a replaceable global
2961 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002962 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002963 return true;
2964
Richard Smithb2f0f052016-10-10 18:54:32 +00002965 unsigned Params = 1;
2966 QualType Ty = FPT->getParamType(Params);
Richard Smith1cdec012013-09-29 04:40:38 +00002967 ASTContext &Ctx = getASTContext();
Richard Smithb2f0f052016-10-10 18:54:32 +00002968
2969 auto Consume = [&] {
2970 ++Params;
2971 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
2972 };
2973
2974 // In C++14, the next parameter can be a 'std::size_t' for sized delete.
2975 bool IsSizedDelete = false;
Richard Smithb47c36f2013-11-05 09:12:18 +00002976 if (Ctx.getLangOpts().SizedDeallocation &&
Richard Smithb2f0f052016-10-10 18:54:32 +00002977 (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2978 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
2979 Ctx.hasSameType(Ty, Ctx.getSizeType())) {
2980 IsSizedDelete = true;
2981 Consume();
2982 }
2983
2984 // In C++17, the next parameter can be a 'std::align_val_t' for aligned
2985 // new/delete.
Akira Hatanakacae83f72017-06-29 18:48:40 +00002986 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
2987 if (IsAligned)
2988 *IsAligned = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00002989 Consume();
Akira Hatanakacae83f72017-06-29 18:48:40 +00002990 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002991
2992 // Finally, if this is not a sized delete, the final parameter can
2993 // be a 'const std::nothrow_t&'.
2994 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
2995 Ty = Ty->getPointeeType();
2996 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2997 return false;
Richard Smith62a95562019-09-27 01:26:49 +00002998 if (Ty->isNothrowT())
Richard Smithb2f0f052016-10-10 18:54:32 +00002999 Consume();
3000 }
3001
3002 return Params == FPT->getNumParams();
Richard Smith8d0dc312013-07-21 23:12:18 +00003003}
3004
Richard Smith5b349582017-10-13 01:55:36 +00003005bool FunctionDecl::isDestroyingOperatorDelete() const {
3006 // C++ P0722:
3007 // Within a class C, a single object deallocation function with signature
3008 // (T, std::destroying_delete_t, <more params>)
3009 // is a destroying operator delete.
3010 if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
3011 getNumParams() < 2)
3012 return false;
3013
3014 auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
3015 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
3016 RD->getIdentifier()->isStr("destroying_delete_t");
3017}
3018
Rafael Espindolaf4187652013-02-14 01:18:37 +00003019LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00003020 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00003021}
3022
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003023bool FunctionDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00003024 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003025}
3026
Rafael Espindola593537a2013-05-05 20:15:21 +00003027bool FunctionDecl::isInExternCContext() const {
Anastasia Stulovad6865b72019-05-07 14:22:34 +00003028 if (hasAttr<OpenCLKernelAttr>())
3029 return true;
Serge Pavlov3cb80222013-11-14 02:13:03 +00003030 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00003031}
3032
3033bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00003034 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00003035}
3036
Douglas Gregorf1b876d2009-03-31 16:35:03 +00003037bool FunctionDecl::isGlobal() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003038 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
Douglas Gregorf1b876d2009-03-31 16:35:03 +00003039 return Method->isStatic();
3040
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003041 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00003042 return false;
3043
Mike Stump11289f42009-09-09 15:08:12 +00003044 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00003045 DC->isNamespace();
3046 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003047 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
Douglas Gregorf1b876d2009-03-31 16:35:03 +00003048 if (!Namespace->getDeclName())
3049 return false;
3050 break;
3051 }
3052 }
3053
3054 return true;
3055}
3056
Richard Smith10876ef2013-01-17 01:30:42 +00003057bool FunctionDecl::isNoReturn() const {
Adrian Prantl721c7cb2016-08-17 16:42:15 +00003058 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
3059 hasAttr<C11NoReturnAttr>())
3060 return true;
3061
3062 if (auto *FnTy = getType()->getAs<FunctionType>())
3063 return FnTy->getNoReturnAttr();
3064
3065 return false;
Richard Smith10876ef2013-01-17 01:30:42 +00003066}
3067
Erich Keane5c0d1922018-11-28 18:34:14 +00003068
3069MultiVersionKind FunctionDecl::getMultiVersionKind() const {
3070 if (hasAttr<TargetAttr>())
3071 return MultiVersionKind::Target;
3072 if (hasAttr<CPUDispatchAttr>())
3073 return MultiVersionKind::CPUDispatch;
3074 if (hasAttr<CPUSpecificAttr>())
3075 return MultiVersionKind::CPUSpecific;
3076 return MultiVersionKind::None;
3077}
3078
Erich Keane3efe0022018-07-20 14:13:28 +00003079bool FunctionDecl::isCPUDispatchMultiVersion() const {
3080 return isMultiVersion() && hasAttr<CPUDispatchAttr>();
3081}
3082
3083bool FunctionDecl::isCPUSpecificMultiVersion() const {
3084 return isMultiVersion() && hasAttr<CPUSpecificAttr>();
3085}
3086
Erich Keane19a8adc2018-10-25 18:57:19 +00003087bool FunctionDecl::isTargetMultiVersion() const {
3088 return isMultiVersion() && hasAttr<TargetAttr>();
3089}
3090
Sebastian Redl833ef452010-01-26 22:01:41 +00003091void
3092FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00003093 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00003094
3095 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
3096 FunctionTemplateDecl *PrevFunTmpl
Craig Topper36250ad2014-05-12 05:36:57 +00003097 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00003098 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00003099 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00003100 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003101
Erich Keane9c665062018-08-01 21:02:40 +00003102 if (PrevDecl && PrevDecl->isInlined())
3103 setImplicitlyInline(true);
Sebastian Redl833ef452010-01-26 22:01:41 +00003104}
3105
Rafael Espindola8db352d2013-10-17 15:37:26 +00003106FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00003107
Erik Pilkingtonb6e16ea2019-03-18 19:23:45 +00003108/// Returns a value indicating whether this function corresponds to a builtin
3109/// function.
Douglas Gregorb9063fc2009-02-13 23:20:09 +00003110///
Erik Pilkingtonb6e16ea2019-03-18 19:23:45 +00003111/// The function corresponds to a built-in function if it is declared at
3112/// translation scope or within an extern "C" block and its name matches with
3113/// the name of a builtin. The returned value will be 0 for functions that do
3114/// not correspond to a builtin, a value of type \c Builtin::ID if in the
3115/// target-independent range \c [1,Builtin::First), or a target-specific builtin
3116/// value.
3117///
3118/// \param ConsiderWrapperFunctions If true, we should consider wrapper
3119/// functions as their wrapped builtins. This shouldn't be done in general, but
3120/// it's useful in Sema to diagnose calls to wrappers based on their semantics.
3121unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
Simon Tatham7c11da02019-09-02 15:35:09 +01003122 unsigned BuiltinID;
Douglas Gregore711f702009-02-14 18:57:46 +00003123
Simon Tatham7c11da02019-09-02 15:35:09 +01003124 if (const auto *AMAA = getAttr<ArmMveAliasAttr>()) {
3125 BuiltinID = AMAA->getBuiltinName()->getBuiltinID();
3126 } else {
3127 if (!getIdentifier())
3128 return 0;
3129
3130 BuiltinID = getIdentifier()->getBuiltinID();
3131 }
3132
Daniel Dunbar304314d2012-03-06 23:52:37 +00003133 if (!BuiltinID)
3134 return 0;
3135
3136 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00003137 if (Context.getLangOpts().CPlusPlus) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003138 const auto *LinkageDecl =
3139 dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
Warren Hunt445d83e2013-11-01 23:46:51 +00003140 // In C++, the first declaration of a builtin is always inside an implicit
3141 // extern "C".
3142 // FIXME: A recognised library function may not be directly in an extern "C"
3143 // declaration, for instance "extern "C" { namespace std { decl } }".
David Majnemerba3e5ec2015-03-13 18:26:17 +00003144 if (!LinkageDecl) {
3145 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
David Majnemer145abde2016-01-26 01:12:17 +00003146 Context.getTargetInfo().getCXXABI().isMicrosoft())
David Majnemerba3e5ec2015-03-13 18:26:17 +00003147 return Builtin::BI__GetExceptionInfo;
3148 return 0;
3149 }
3150 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
Warren Hunt445d83e2013-11-01 23:46:51 +00003151 return 0;
3152 }
3153
3154 // If the function is marked "overloadable", it has a different mangled name
3155 // and is not the C library function.
Simon Tatham7c11da02019-09-02 15:35:09 +01003156 if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&
3157 !hasAttr<ArmMveAliasAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00003158 return 0;
3159
Douglas Gregore711f702009-02-14 18:57:46 +00003160 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3161 return BuiltinID;
3162
3163 // This function has the name of a known C library
3164 // function. Determine whether it actually refers to the C library
3165 // function or whether it just has the same name.
3166
Douglas Gregora908e7f2009-02-17 03:23:10 +00003167 // If this is a static function, it's not a builtin.
Erik Pilkingtonb6e16ea2019-03-18 19:23:45 +00003168 if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00003169 return 0;
3170
Anastasia Stulova1202de32016-02-12 12:07:04 +00003171 // OpenCL v1.2 s6.9.f - The library functions defined in
3172 // the C99 standard headers are not available.
3173 if (Context.getLangOpts().OpenCL &&
3174 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3175 return 0;
3176
Artem Belevich5ecdb942018-01-23 19:08:18 +00003177 // CUDA does not have device-side standard library. printf and malloc are the
3178 // only special cases that are supported by device-side runtime.
3179 if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
3180 !hasAttr<CUDAHostAttr>() &&
3181 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3182 return 0;
3183
Warren Hunt445d83e2013-11-01 23:46:51 +00003184 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00003185}
3186
Chris Lattner47c0d002009-04-25 06:03:53 +00003187/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00003188/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00003189/// after it has been created.
3190unsigned FunctionDecl::getNumParams() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003191 const auto *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003192 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00003193}
3194
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003195void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003196 ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00003197 assert(!ParamInfo && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00003198 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00003199
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00003200 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003201 if (!NewParamInfo.empty()) {
3202 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
3203 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00003204 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00003205}
Chris Lattner41943152007-01-25 04:52:46 +00003206
Chris Lattner58258242008-04-10 02:22:51 +00003207/// getMinRequiredArguments - Returns the minimum number of arguments
3208/// needed to call this function. This may be fewer than the number of
3209/// function parameters, if some of the parameters have default
Richard Smith91151782014-04-01 19:18:16 +00003210/// arguments (in C++) or are parameter packs (C++11).
Chris Lattner58258242008-04-10 02:22:51 +00003211unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003212 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003213 return getNumParams();
Chris Lattner58258242008-04-10 02:22:51 +00003214
Richard Smith91151782014-04-01 19:18:16 +00003215 unsigned NumRequiredArgs = 0;
David Majnemer59f77922016-06-24 04:05:48 +00003216 for (auto *Param : parameters())
Richard Smith91151782014-04-01 19:18:16 +00003217 if (!Param->isParameterPack() && !Param->hasDefaultArg())
3218 ++NumRequiredArgs;
Chris Lattner58258242008-04-10 02:22:51 +00003219 return NumRequiredArgs;
3220}
3221
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003222/// The combination of the extern and inline keywords under MSVC forces
David Majnemer54e3ba52014-04-02 23:17:29 +00003223/// the function to be required.
3224///
3225/// Note: This function assumes that we will only get called when isInlined()
3226/// would return true for this FunctionDecl.
3227bool FunctionDecl::isMSExternInline() const {
3228 assert(isInlined() && "expected to get called on an inlined function!");
3229
3230 const ASTContext &Context = getASTContext();
David Majnemer3f021502015-10-08 04:53:31 +00003231 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3232 !hasAttr<DLLExportAttr>())
David Majnemer54e3ba52014-04-02 23:17:29 +00003233 return false;
3234
David Majnemer73768702015-03-20 00:02:27 +00003235 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
3236 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00003237 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00003238 return true;
3239
3240 return false;
3241}
3242
3243static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3244 if (Redecl->getStorageClass() != SC_Extern)
3245 return false;
3246
3247 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
3248 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00003249 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00003250 return false;
3251
3252 return true;
3253}
3254
Eli Friedman1b125c32012-02-07 03:50:18 +00003255static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3256 // Only consider file-scope declarations in this test.
3257 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3258 return false;
3259
3260 // Only consider explicit declarations; the presence of a builtin for a
3261 // libcall shouldn't affect whether a definition is externally visible.
3262 if (Redecl->isImplicit())
3263 return false;
3264
Fangrui Song6907ce22018-07-30 19:24:48 +00003265 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00003266 return true; // Not an inline definition
3267
3268 return false;
3269}
3270
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003271/// For a function declaration in C or C++, determine whether this
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003272/// declaration causes the definition to be externally visible.
3273///
David Majnemer54e3ba52014-04-02 23:17:29 +00003274/// For instance, this determines if adding the current declaration to the set
Eli Friedman1b125c32012-02-07 03:50:18 +00003275/// of redeclarations of the given functions causes
3276/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003277bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
Justin Lebar0241c962016-10-28 16:46:39 +00003278 assert(!doesThisDeclarationHaveABody() &&
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003279 "Must have a declaration without a body.");
3280
3281 ASTContext &Context = getASTContext();
3282
David Majnemer54e3ba52014-04-02 23:17:29 +00003283 if (Context.getLangOpts().MSVCCompat) {
3284 const FunctionDecl *Definition;
3285 if (hasBody(Definition) && Definition->isInlined() &&
3286 redeclForcesDefMSVC(this))
3287 return true;
3288 }
3289
Martin Storsjo71decf82019-09-27 12:25:19 +00003290 if (Context.getLangOpts().CPlusPlus)
3291 return false;
3292
David Blaikiebbafb8a2012-03-11 07:00:24 +00003293 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003294 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3295 // an externally visible definition.
3296 //
3297 // FIXME: What happens if gnu_inline gets added on after the first
3298 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003299 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00003300 return false;
3301
3302 const FunctionDecl *Prev = this;
3303 bool FoundBody = false;
3304 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00003305 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00003306
3307 if (Prev->Body) {
3308 // If it's not the case that both 'inline' and 'extern' are
3309 // specified on the definition, then it is always externally visible.
3310 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003311 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00003312 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003313 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003314 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003315 return false;
3316 }
3317 }
3318 return FoundBody;
3319 }
3320
Eli Friedman1b125c32012-02-07 03:50:18 +00003321 // C99 6.7.4p6:
Fangrui Song6907ce22018-07-30 19:24:48 +00003322 // [...] If all of the file scope declarations for a function in a
3323 // translation unit include the inline function specifier without extern,
Eli Friedman1b125c32012-02-07 03:50:18 +00003324 // then the definition in that translation unit is an inline definition.
3325 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003326 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00003327 const FunctionDecl *Prev = this;
3328 bool FoundBody = false;
3329 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00003330 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00003331 if (RedeclForcesDefC99(Prev))
3332 return false;
3333 }
3334 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003335}
3336
Richard Smithd052a5782019-10-22 17:44:08 -07003337FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const {
Alp Tokerd0787eb2014-07-02 01:47:15 +00003338 const TypeSourceInfo *TSI = getTypeSourceInfo();
Richard Smithd052a5782019-10-22 17:44:08 -07003339 return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>()
3340 : FunctionTypeLoc();
3341}
3342
3343SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3344 FunctionTypeLoc FTL = getFunctionTypeLoc();
Alp Tokerf5b10792014-07-02 12:55:58 +00003345 if (!FTL)
Alp Tokerd0787eb2014-07-02 01:47:15 +00003346 return SourceRange();
3347
Alp Tokerf5b10792014-07-02 12:55:58 +00003348 // Skip self-referential return types.
3349 const SourceManager &SM = getASTContext().getSourceManager();
3350 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003351 SourceLocation Boundary = getNameInfo().getBeginLoc();
Alp Tokerf5b10792014-07-02 12:55:58 +00003352 if (RTRange.isInvalid() || Boundary.isInvalid() ||
3353 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3354 return SourceRange();
Alp Tokerd0787eb2014-07-02 01:47:15 +00003355
Alp Tokerf5b10792014-07-02 12:55:58 +00003356 return RTRange;
Alp Tokerd0787eb2014-07-02 01:47:15 +00003357}
3358
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003359SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
Richard Smithd052a5782019-10-22 17:44:08 -07003360 FunctionTypeLoc FTL = getFunctionTypeLoc();
3361 return FTL ? FTL.getExceptionSpecRange() : SourceRange();
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003362}
3363
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003364/// For an inline function definition in C, or for a gnu_inline function
Richard Smithf3814ad2013-01-25 00:08:28 +00003365/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00003366///
3367/// Inline function definitions are always available for inlining optimizations.
3368/// However, depending on the language dialect, declaration specifiers, and
3369/// attributes, the definition of an inline function may or may not be
3370/// "externally" visible to other translation units in the program.
3371///
3372/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00003373/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00003374/// inline definition becomes externally visible (C99 6.7.4p6).
3375///
3376/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
Fangrui Song6907ce22018-07-30 19:24:48 +00003377/// definition, we use the GNU semantics for inline, which are nearly the
3378/// opposite of C99 semantics. In particular, "inline" by itself will create
3379/// an externally visible symbol, but "extern inline" will not create an
Douglas Gregor299d76e2009-09-13 07:46:26 +00003380/// externally visible symbol.
3381bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Nick Desaulniers58060222019-09-12 19:53:35 +00003382 assert((doesThisDeclarationHaveABody() || willHaveBody() ||
3383 hasAttr<AliasAttr>()) &&
Manuel Klimekda7456a2016-11-01 10:30:50 +00003384 "Must be a function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003385 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00003386 ASTContext &Context = getASTContext();
Fangrui Song6907ce22018-07-30 19:24:48 +00003387
David Blaikiebbafb8a2012-03-11 07:00:24 +00003388 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003389 // Note: If you change the logic here, please change
3390 // doesDeclarationForceExternallyVisibleDefinition as well.
3391 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00003392 // If it's not the case that both 'inline' and 'extern' are
3393 // specified on the definition, then this inline definition is
3394 // externally visible.
Martin Storsjo71decf82019-09-27 12:25:19 +00003395 if (Context.getLangOpts().CPlusPlus)
3396 return false;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003397 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00003398 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003399
Douglas Gregorff76cb92010-12-09 16:59:22 +00003400 // If any declaration is 'inline' but not 'extern', then this definition
3401 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00003402 for (auto Redecl : redecls()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003403 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003404 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00003405 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003406 }
3407
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003408 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003409 }
Eli Friedman1b125c32012-02-07 03:50:18 +00003410
Richard Smithf3814ad2013-01-25 00:08:28 +00003411 // The rest of this function is C-only.
3412 assert(!Context.getLangOpts().CPlusPlus &&
3413 "should not use C inline rules in C++");
3414
Douglas Gregor299d76e2009-09-13 07:46:26 +00003415 // C99 6.7.4p6:
Fangrui Song6907ce22018-07-30 19:24:48 +00003416 // [...] If all of the file scope declarations for a function in a
3417 // translation unit include the inline function specifier without extern,
Douglas Gregor299d76e2009-09-13 07:46:26 +00003418 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00003419 for (auto Redecl : redecls()) {
3420 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00003421 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003422 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003423
Douglas Gregor299d76e2009-09-13 07:46:26 +00003424 // C99 6.7.4p6:
Fangrui Song6907ce22018-07-30 19:24:48 +00003425 // An inline definition does not provide an external definition for the
3426 // function, and does not forbid an external definition in another
Douglas Gregor299d76e2009-09-13 07:46:26 +00003427 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003428 return false;
3429}
3430
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003431/// getOverloadedOperator - Which C++ overloaded operator this
3432/// function represents, if any.
3433OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00003434 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3435 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003436 else
3437 return OO_None;
3438}
3439
Alexis Huntc88db062010-01-13 09:01:02 +00003440/// getLiteralIdentifier - The literal suffix identifier this function
3441/// represents, if any.
3442const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3443 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3444 return getDeclName().getCXXLiteralIdentifier();
3445 else
Craig Topper36250ad2014-05-12 05:36:57 +00003446 return nullptr;
Alexis Huntc88db062010-01-13 09:01:02 +00003447}
3448
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003449FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3450 if (TemplateOrSpecialization.isNull())
3451 return TK_NonTemplate;
3452 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3453 return TK_FunctionTemplate;
3454 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3455 return TK_MemberSpecialization;
3456 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3457 return TK_FunctionTemplateSpecialization;
3458 if (TemplateOrSpecialization.is
3459 <DependentFunctionTemplateSpecializationInfo*>())
3460 return TK_DependentFunctionTemplateSpecialization;
3461
David Blaikie83d382b2011-09-23 05:06:16 +00003462 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003463}
3464
Douglas Gregord801b062009-10-07 23:56:10 +00003465FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00003466 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00003467 return cast<FunctionDecl>(Info->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00003468
3469 return nullptr;
Douglas Gregord801b062009-10-07 23:56:10 +00003470}
3471
Chandler Carruth21c90602015-12-30 03:24:14 +00003472MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
Richard Smithf19a8b02019-05-02 00:49:14 +00003473 if (auto *MSI =
3474 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3475 return MSI;
3476 if (auto *FTSI = TemplateOrSpecialization
3477 .dyn_cast<FunctionTemplateSpecializationInfo *>())
3478 return FTSI->getMemberSpecializationInfo();
3479 return nullptr;
Chandler Carruth21c90602015-12-30 03:24:14 +00003480}
3481
Fangrui Song6907ce22018-07-30 19:24:48 +00003482void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003483FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3484 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00003485 TemplateSpecializationKind TSK) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003486 assert(TemplateOrSpecialization.isNull() &&
Douglas Gregord801b062009-10-07 23:56:10 +00003487 "Member function is already a specialization");
Fangrui Song6907ce22018-07-30 19:24:48 +00003488 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003489 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00003490 TemplateOrSpecialization = Info;
3491}
3492
Chandler Carruth21c90602015-12-30 03:24:14 +00003493FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3494 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3495}
3496
3497void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
Richard Smithf19a8b02019-05-02 00:49:14 +00003498 assert(TemplateOrSpecialization.isNull() &&
3499 "Member function is already a specialization");
Chandler Carruth21c90602015-12-30 03:24:14 +00003500 TemplateOrSpecialization = Template;
3501}
3502
Douglas Gregorafca3b42009-10-27 20:53:28 +00003503bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00003504 // If the function is invalid, it can't be implicitly instantiated.
3505 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00003506 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003507
Richard Smithf19a8b02019-05-02 00:49:14 +00003508 switch (getTemplateSpecializationKindForInstantiation()) {
Douglas Gregorafca3b42009-10-27 20:53:28 +00003509 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00003510 case TSK_ExplicitInstantiationDefinition:
Richard Smithf19a8b02019-05-02 00:49:14 +00003511 case TSK_ExplicitSpecialization:
Douglas Gregorafca3b42009-10-27 20:53:28 +00003512 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003513
Douglas Gregorafca3b42009-10-27 20:53:28 +00003514 case TSK_ImplicitInstantiation:
3515 return true;
3516
3517 case TSK_ExplicitInstantiationDeclaration:
3518 // Handled below.
3519 break;
3520 }
3521
3522 // Find the actual template from which we will instantiate.
3523 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003524 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003525 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003526 HasPattern = PatternDecl->hasBody(PatternDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00003527
Douglas Gregorafca3b42009-10-27 20:53:28 +00003528 // C++0x [temp.explicit]p9:
3529 // Except for inline functions, other explicit instantiation declarations
3530 // have the effect of suppressing the implicit instantiation of the entity
Fangrui Song6907ce22018-07-30 19:24:48 +00003531 // to which they refer.
3532 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00003533 return true;
3534
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003535 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00003536}
3537
3538bool FunctionDecl::isTemplateInstantiation() const {
Richard Smithf19a8b02019-05-02 00:49:14 +00003539 // FIXME: Remove this, it's not clear what it means. (Which template
3540 // specialization kind?)
3541 return clang::isTemplateInstantiation(getTemplateSpecializationKind());
Ted Kremenek85825ae2011-12-01 00:59:17 +00003542}
Fangrui Song6907ce22018-07-30 19:24:48 +00003543
Douglas Gregorafca3b42009-10-27 20:53:28 +00003544FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003545 // If this is a generic lambda call operator specialization, its
Faisal Valib90b2112014-04-03 16:32:21 +00003546 // instantiation pattern is always its primary template's pattern
Fangrui Song6907ce22018-07-30 19:24:48 +00003547 // even if its primary template was instantiated from another
Faisal Valib90b2112014-04-03 16:32:21 +00003548 // member template (which happens with nested generic lambdas).
Fangrui Song6907ce22018-07-30 19:24:48 +00003549 // Since a lambda's call operator's body is transformed eagerly,
3550 // we don't have to go hunting for a prototype definition template
3551 // (i.e. instantiated-from-member-template) to use as an instantiation
Faisal Valib90b2112014-04-03 16:32:21 +00003552 // pattern.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003553
Faisal Valib90b2112014-04-03 16:32:21 +00003554 if (isGenericLambdaCallOperatorSpecialization(
3555 dyn_cast<CXXMethodDecl>(this))) {
Richard Smith2195ec92017-04-21 01:15:13 +00003556 assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3557 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
Faisal Valib90b2112014-04-03 16:32:21 +00003558 }
Richard Smith2195ec92017-04-21 01:15:13 +00003559
Richard Smithf19a8b02019-05-02 00:49:14 +00003560 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) {
3561 if (!clang::isTemplateInstantiation(Info->getTemplateSpecializationKind()))
3562 return nullptr;
3563 return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
3564 }
3565
3566 if (!clang::isTemplateInstantiation(getTemplateSpecializationKind()))
3567 return nullptr;
3568
Douglas Gregorafca3b42009-10-27 20:53:28 +00003569 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
Richard Smitha6b41d72019-05-03 23:51:38 +00003570 // If we hit a point where the user provided a specialization of this
3571 // template, we're done looking.
3572 while (!Primary->isMemberSpecialization()) {
3573 auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
3574 if (!NewPrimary)
Douglas Gregorafca3b42009-10-27 20:53:28 +00003575 break;
Richard Smitha6b41d72019-05-03 23:51:38 +00003576 Primary = NewPrimary;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003577 }
Richard Smith2195ec92017-04-21 01:15:13 +00003578
3579 return getDefinitionOrSelf(Primary->getTemplatedDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00003580 }
Richard Smith2195ec92017-04-21 01:15:13 +00003581
Richard Smith2195ec92017-04-21 01:15:13 +00003582 return nullptr;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003583}
3584
Douglas Gregor70d83e22009-06-29 17:30:29 +00003585FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00003586 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003587 = TemplateOrSpecialization
3588 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Richard Smithf19a8b02019-05-02 00:49:14 +00003589 return Info->getTemplate();
Douglas Gregor70d83e22009-06-29 17:30:29 +00003590 }
Craig Topper36250ad2014-05-12 05:36:57 +00003591 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003592}
3593
Chandler Carruth21c90602015-12-30 03:24:14 +00003594FunctionTemplateSpecializationInfo *
3595FunctionDecl::getTemplateSpecializationInfo() const {
3596 return TemplateOrSpecialization
3597 .dyn_cast<FunctionTemplateSpecializationInfo *>();
3598}
3599
Douglas Gregor70d83e22009-06-29 17:30:29 +00003600const TemplateArgumentList *
3601FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00003602 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00003603 = TemplateOrSpecialization
3604 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003605 return Info->TemplateArguments;
3606 }
Craig Topper36250ad2014-05-12 05:36:57 +00003607 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003608}
3609
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00003610const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003611FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3612 if (FunctionTemplateSpecializationInfo *Info
3613 = TemplateOrSpecialization
3614 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3615 return Info->TemplateArgumentsAsWritten;
3616 }
Craig Topper36250ad2014-05-12 05:36:57 +00003617 return nullptr;
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003618}
3619
Mike Stump11289f42009-09-09 15:08:12 +00003620void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003621FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3622 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003623 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003624 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003625 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00003626 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3627 SourceLocation PointOfInstantiation) {
Richard Smithf19a8b02019-05-02 00:49:14 +00003628 assert((TemplateOrSpecialization.isNull() ||
3629 TemplateOrSpecialization.is<MemberSpecializationInfo *>()) &&
3630 "Member function is already a specialization");
Fangrui Song6907ce22018-07-30 19:24:48 +00003631 assert(TSK != TSK_Undeclared &&
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003632 "Must specify the type of function template specialization");
Richard Smithf19a8b02019-05-02 00:49:14 +00003633 assert((TemplateOrSpecialization.isNull() ||
3634 TSK == TSK_ExplicitSpecialization) &&
3635 "Member specialization must be an explicit specialization");
3636 FunctionTemplateSpecializationInfo *Info =
3637 FunctionTemplateSpecializationInfo::Create(
3638 C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
3639 PointOfInstantiation,
3640 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>());
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003641 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00003642 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003643}
3644
John McCallb9c78482010-04-08 09:05:18 +00003645void
3646FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3647 const UnresolvedSetImpl &Templates,
3648 const TemplateArgumentListInfo &TemplateArgs) {
3649 assert(TemplateOrSpecialization.isNull());
John McCallb9c78482010-04-08 09:05:18 +00003650 DependentFunctionTemplateSpecializationInfo *Info =
James Y Knight7a22b242015-08-06 20:26:32 +00003651 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3652 TemplateArgs);
John McCallb9c78482010-04-08 09:05:18 +00003653 TemplateOrSpecialization = Info;
3654}
3655
James Y Knight7a22b242015-08-06 20:26:32 +00003656DependentFunctionTemplateSpecializationInfo *
Chandler Carruth21c90602015-12-30 03:24:14 +00003657FunctionDecl::getDependentSpecializationInfo() const {
3658 return TemplateOrSpecialization
3659 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3660}
3661
3662DependentFunctionTemplateSpecializationInfo *
James Y Knight7a22b242015-08-06 20:26:32 +00003663DependentFunctionTemplateSpecializationInfo::Create(
3664 ASTContext &Context, const UnresolvedSetImpl &Ts,
3665 const TemplateArgumentListInfo &TArgs) {
3666 void *Buffer = Context.Allocate(
3667 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3668 TArgs.size(), Ts.size()));
3669 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3670}
3671
John McCallb9c78482010-04-08 09:05:18 +00003672DependentFunctionTemplateSpecializationInfo::
3673DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3674 const TemplateArgumentListInfo &TArgs)
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003675 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
James Y Knight53c76162015-07-17 18:21:37 +00003676 NumTemplates = Ts.size();
3677 NumArgs = TArgs.size();
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003678
James Y Knight7a22b242015-08-06 20:26:32 +00003679 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
John McCallb9c78482010-04-08 09:05:18 +00003680 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3681 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3682
James Y Knight7a22b242015-08-06 20:26:32 +00003683 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
John McCallb9c78482010-04-08 09:05:18 +00003684 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3685 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3686}
3687
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003688TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00003689 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003690 // information object.
Richard Smithf19a8b02019-05-02 00:49:14 +00003691 if (FunctionTemplateSpecializationInfo *FTSInfo =
3692 TemplateOrSpecialization
3693 .dyn_cast<FunctionTemplateSpecializationInfo *>())
Douglas Gregord801b062009-10-07 23:56:10 +00003694 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00003695
Richard Smithf19a8b02019-05-02 00:49:14 +00003696 if (MemberSpecializationInfo *MSInfo =
3697 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3698 return MSInfo->getTemplateSpecializationKind();
3699
3700 return TSK_Undeclared;
3701}
3702
3703TemplateSpecializationKind
3704FunctionDecl::getTemplateSpecializationKindForInstantiation() const {
3705 // This is the same as getTemplateSpecializationKind(), except that for a
3706 // function that is both a function template specialization and a member
3707 // specialization, we prefer the member specialization information. Eg:
3708 //
3709 // template<typename T> struct A {
3710 // template<typename U> void f() {}
3711 // template<> void f<int>() {}
3712 // };
3713 //
3714 // For A<int>::f<int>():
3715 // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
3716 // * getTemplateSpecializationKindForInstantiation() will return
3717 // TSK_ImplicitInstantiation
3718 //
3719 // This reflects the facts that A<int>::f<int> is an explicit specialization
3720 // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
3721 // from A::f<int> if a definition is needed.
3722 if (FunctionTemplateSpecializationInfo *FTSInfo =
3723 TemplateOrSpecialization
3724 .dyn_cast<FunctionTemplateSpecializationInfo *>()) {
3725 if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
3726 return MSInfo->getTemplateSpecializationKind();
3727 return FTSInfo->getTemplateSpecializationKind();
3728 }
3729
3730 if (MemberSpecializationInfo *MSInfo =
3731 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
Douglas Gregord801b062009-10-07 23:56:10 +00003732 return MSInfo->getTemplateSpecializationKind();
Fangrui Song6907ce22018-07-30 19:24:48 +00003733
Douglas Gregord801b062009-10-07 23:56:10 +00003734 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003735}
3736
Mike Stump11289f42009-09-09 15:08:12 +00003737void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003738FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3739 SourceLocation PointOfInstantiation) {
3740 if (FunctionTemplateSpecializationInfo *FTSInfo
3741 = TemplateOrSpecialization.dyn_cast<
3742 FunctionTemplateSpecializationInfo*>()) {
3743 FTSInfo->setTemplateSpecializationKind(TSK);
3744 if (TSK != TSK_ExplicitSpecialization &&
3745 PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00003746 FTSInfo->getPointOfInstantiation().isInvalid()) {
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003747 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00003748 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3749 L->InstantiationRequested(this);
3750 }
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003751 } else if (MemberSpecializationInfo *MSInfo
3752 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3753 MSInfo->setTemplateSpecializationKind(TSK);
3754 if (TSK != TSK_ExplicitSpecialization &&
3755 PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00003756 MSInfo->getPointOfInstantiation().isInvalid()) {
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003757 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00003758 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3759 L->InstantiationRequested(this);
3760 }
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003761 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003762 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003763}
3764
3765SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00003766 if (FunctionTemplateSpecializationInfo *FTSInfo
3767 = TemplateOrSpecialization.dyn_cast<
3768 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003769 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00003770 else if (MemberSpecializationInfo *MSInfo
3771 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003772 return MSInfo->getPointOfInstantiation();
Fangrui Song6907ce22018-07-30 19:24:48 +00003773
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003774 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00003775}
3776
Douglas Gregor6411b922009-09-11 20:15:17 +00003777bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00003778 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00003779 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003780
3781 // If this function was instantiated from a member function of a
Douglas Gregor6411b922009-09-11 20:15:17 +00003782 // class template, check whether that member function was defined out-of-line.
3783 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3784 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003785 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003786 return Definition->isOutOfLine();
3787 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003788
Douglas Gregor6411b922009-09-11 20:15:17 +00003789 // If this function was instantiated from a function template,
3790 // check whether that function template was defined out-of-line.
3791 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3792 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003793 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003794 return Definition->isOutOfLine();
3795 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003796
Douglas Gregor6411b922009-09-11 20:15:17 +00003797 return false;
3798}
3799
Abramo Bagnaraea947882011-03-08 16:41:52 +00003800SourceRange FunctionDecl::getSourceRange() const {
3801 return SourceRange(getOuterLocStart(), EndRangeLoc);
3802}
3803
Anna Zaks28db7ce2012-01-18 02:45:01 +00003804unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00003805 IdentifierInfo *FnInfo = getIdentifier();
3806
3807 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00003808 return 0;
Fangrui Song6907ce22018-07-30 19:24:48 +00003809
Anna Zaks201d4892012-01-13 21:52:01 +00003810 // Builtin handling.
3811 switch (getBuiltinID()) {
3812 case Builtin::BI__builtin_memset:
3813 case Builtin::BI__builtin___memset_chk:
3814 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003815 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003816
3817 case Builtin::BI__builtin_memcpy:
3818 case Builtin::BI__builtin___memcpy_chk:
3819 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003820 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003821
3822 case Builtin::BI__builtin_memmove:
3823 case Builtin::BI__builtin___memmove_chk:
3824 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003825 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003826
3827 case Builtin::BIstrlcpy:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003828 case Builtin::BI__builtin___strlcpy_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003829 return Builtin::BIstrlcpy;
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003830
Anna Zaks201d4892012-01-13 21:52:01 +00003831 case Builtin::BIstrlcat:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003832 case Builtin::BI__builtin___strlcat_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003833 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003834
3835 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003836 case Builtin::BImemcmp:
3837 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003838
Clement Courbet8c3343d2019-02-14 12:00:34 +00003839 case Builtin::BI__builtin_bcmp:
3840 case Builtin::BIbcmp:
3841 return Builtin::BIbcmp;
3842
Anna Zaks201d4892012-01-13 21:52:01 +00003843 case Builtin::BI__builtin_strncpy:
3844 case Builtin::BI__builtin___strncpy_chk:
3845 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003846 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003847
3848 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003849 case Builtin::BIstrncmp:
3850 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003851
3852 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003853 case Builtin::BIstrncasecmp:
3854 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003855
3856 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003857 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003858 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003859 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003860
3861 case Builtin::BI__builtin_strndup:
3862 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003863 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003864
Anna Zaks314cd092012-02-01 19:08:57 +00003865 case Builtin::BI__builtin_strlen:
3866 case Builtin::BIstrlen:
3867 return Builtin::BIstrlen;
3868
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003869 case Builtin::BI__builtin_bzero:
3870 case Builtin::BIbzero:
3871 return Builtin::BIbzero;
3872
Anna Zaks201d4892012-01-13 21:52:01 +00003873 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003874 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003875 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003876 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003877 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003878 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003879 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003880 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003881 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003882 return Builtin::BImemcmp;
Clement Courbet8c3343d2019-02-14 12:00:34 +00003883 else if (FnInfo->isStr("bcmp"))
3884 return Builtin::BIbcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003885 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003886 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003887 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003888 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003889 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003890 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003891 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003892 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003893 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003894 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003895 else if (FnInfo->isStr("strlen"))
3896 return Builtin::BIstrlen;
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003897 else if (FnInfo->isStr("bzero"))
3898 return Builtin::BIbzero;
Anna Zaks201d4892012-01-13 21:52:01 +00003899 }
3900 break;
3901 }
Anna Zaks22122702012-01-17 00:37:07 +00003902 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003903}
3904
Richard Trieu27c1b1a2018-07-10 01:40:50 +00003905unsigned FunctionDecl::getODRHash() const {
Erich Keane9c665062018-08-01 21:02:40 +00003906 assert(hasODRHash());
Richard Trieu27c1b1a2018-07-10 01:40:50 +00003907 return ODRHash;
3908}
3909
Richard Trieue6caa262017-12-23 00:41:01 +00003910unsigned FunctionDecl::getODRHash() {
Erich Keane9c665062018-08-01 21:02:40 +00003911 if (hasODRHash())
Richard Trieue6caa262017-12-23 00:41:01 +00003912 return ODRHash;
3913
Richard Trieu0ac2eb72018-02-22 05:50:29 +00003914 if (auto *FT = getInstantiatedFromMemberFunction()) {
Erich Keane9c665062018-08-01 21:02:40 +00003915 setHasODRHash(true);
Richard Trieu0ac2eb72018-02-22 05:50:29 +00003916 ODRHash = FT->getODRHash();
3917 return ODRHash;
3918 }
3919
Richard Trieue6caa262017-12-23 00:41:01 +00003920 class ODRHash Hash;
3921 Hash.AddFunctionDecl(this);
Erich Keane9c665062018-08-01 21:02:40 +00003922 setHasODRHash(true);
Richard Trieue6caa262017-12-23 00:41:01 +00003923 ODRHash = Hash.CalculateHash();
3924 return ODRHash;
3925}
3926
Chris Lattner59a25942008-03-31 00:36:02 +00003927//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003928// FieldDecl Implementation
3929//===----------------------------------------------------------------------===//
3930
Jay Foad39c79802011-01-12 09:06:06 +00003931FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003932 SourceLocation StartLoc, SourceLocation IdLoc,
3933 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003934 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003935 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003936 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3937 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003938}
3939
Douglas Gregor72172e92012-01-05 21:55:30 +00003940FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003941 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3942 SourceLocation(), nullptr, QualType(), nullptr,
3943 nullptr, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00003944}
3945
Sebastian Redl833ef452010-01-26 22:01:41 +00003946bool FieldDecl::isAnonymousStructOrUnion() const {
3947 if (!isImplicit() || getDeclName())
3948 return false;
3949
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003950 if (const auto *Record = getType()->getAs<RecordType>())
Sebastian Redl833ef452010-01-26 22:01:41 +00003951 return Record->getDecl()->isAnonymousStructOrUnion();
3952
3953 return false;
3954}
3955
Richard Smithcaf33902011-10-10 18:28:20 +00003956unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3957 assert(isBitField() && "not a bitfield");
Richard Smith6b8e3c02017-08-28 00:28:14 +00003958 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
Richard Smithcaf33902011-10-10 18:28:20 +00003959}
3960
Richard Smith866dee42018-04-02 18:29:43 +00003961bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const {
3962 return isUnnamedBitfield() && !getBitWidth()->isValueDependent() &&
3963 getBitWidthValue(Ctx) == 0;
3964}
3965
Richard Smith78b239e2019-06-20 20:44:45 +00003966bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
3967 if (isZeroLengthBitField(Ctx))
3968 return true;
3969
3970 // C++2a [intro.object]p7:
3971 // An object has nonzero size if it
3972 // -- is not a potentially-overlapping subobject, or
3973 if (!hasAttr<NoUniqueAddressAttr>())
3974 return false;
3975
3976 // -- is not of class type, or
3977 const auto *RT = getType()->getAs<RecordType>();
3978 if (!RT)
3979 return false;
3980 const RecordDecl *RD = RT->getDecl()->getDefinition();
3981 if (!RD) {
3982 assert(isInvalidDecl() && "valid field has incomplete type");
3983 return false;
3984 }
3985
3986 // -- [has] virtual member functions or virtual base classes, or
3987 // -- has subobjects of nonzero size or bit-fields of nonzero length
3988 const auto *CXXRD = cast<CXXRecordDecl>(RD);
3989 if (!CXXRD->isEmpty())
3990 return false;
3991
3992 // Otherwise, [...] the circumstances under which the object has zero size
3993 // are implementation-defined.
3994 // FIXME: This might be Itanium ABI specific; we don't yet know what the MS
3995 // ABI will do.
3996 return true;
3997}
3998
John McCall4e819612011-01-20 07:57:12 +00003999unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00004000 const FieldDecl *Canonical = getCanonicalDecl();
4001 if (Canonical != this)
4002 return Canonical->getFieldIndex();
4003
John McCall4e819612011-01-20 07:57:12 +00004004 if (CachedFieldIndex) return CachedFieldIndex - 1;
4005
Richard Smithd62306a2011-11-10 06:34:14 +00004006 unsigned Index = 0;
Richard Smith85567dd2017-11-15 01:33:46 +00004007 const RecordDecl *RD = getParent()->getDefinition();
4008 assert(RD && "requested index for field of struct with no definition");
Richard Smithd62306a2011-11-10 06:34:14 +00004009
Hans Wennborga302cd92014-08-21 16:06:57 +00004010 for (auto *Field : RD->fields()) {
4011 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
4012 ++Index;
4013 }
John McCall4e819612011-01-20 07:57:12 +00004014
Richard Smithd62306a2011-11-10 06:34:14 +00004015 assert(CachedFieldIndex && "failed to find field in parent");
4016 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00004017}
4018
Abramo Bagnara20c9e242011-03-08 11:07:11 +00004019SourceRange FieldDecl::getSourceRange() const {
Richard Smith6b8e3c02017-08-28 00:28:14 +00004020 const Expr *FinalExpr = getInClassInitializer();
4021 if (!FinalExpr)
4022 FinalExpr = getBitWidth();
4023 if (FinalExpr)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004024 return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
Richard Smith6b8e3c02017-08-28 00:28:14 +00004025 return DeclaratorDecl::getSourceRange();
Alexey Bataev39c81e22014-08-28 04:28:19 +00004026}
4027
4028void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
David Blaikie11ab0782014-10-31 17:18:09 +00004029 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
Alexey Bataev330de032014-10-29 12:21:55 +00004030 "capturing type in non-lambda or captured record.");
Richard Smith6b8e3c02017-08-28 00:28:14 +00004031 assert(InitStorage.getInt() == ISK_NoInit &&
John McCallc90c1492014-10-10 18:44:34 +00004032 InitStorage.getPointer() == nullptr &&
Alexey Bataev39c81e22014-08-28 04:28:19 +00004033 "bit width, initializer or captured type already set");
John McCallc90c1492014-10-10 18:44:34 +00004034 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
4035 ISK_CapturedVLAType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00004036}
4037
Sebastian Redl833ef452010-01-26 22:01:41 +00004038//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00004039// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00004040//===----------------------------------------------------------------------===//
4041
Erich Keanef92f31c2018-08-01 20:48:16 +00004042TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
4043 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
4044 SourceLocation StartL)
4045 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
4046 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
4047 assert((DK != Enum || TK == TTK_Enum) &&
4048 "EnumDecl not matched with TTK_Enum");
4049 setPreviousDecl(PrevDecl);
4050 setTagKind(TK);
4051 setCompleteDefinition(false);
4052 setBeingDefined(false);
4053 setEmbeddedInDeclarator(false);
4054 setFreeStanding(false);
4055 setCompleteDefinitionRequired(false);
4056}
4057
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00004058SourceLocation TagDecl::getOuterLocStart() const {
4059 return getTemplateOrInnerLocStart(this);
4060}
4061
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00004062SourceRange TagDecl::getSourceRange() const {
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004063 SourceLocation RBraceLoc = BraceRange.getEnd();
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00004064 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00004065 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00004066}
4067
Rafael Espindola8db352d2013-10-17 15:37:26 +00004068TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00004069
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00004070void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer00350522015-08-31 18:48:39 +00004071 TypedefNameDeclOrQualifier = TDD;
Reid Klecknercae82a22014-04-23 22:03:04 +00004072 if (const Type *T = getTypeForDecl()) {
4073 (void)T;
Richard Smith5b21db82014-04-23 18:20:42 +00004074 assert(T->isLinkageValid());
Reid Klecknercae82a22014-04-23 22:03:04 +00004075 }
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004076 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00004077}
4078
Douglas Gregordee1be82009-01-17 00:42:38 +00004079void TagDecl::startDefinition() {
Erich Keanef92f31c2018-08-01 20:48:16 +00004080 setBeingDefined(true);
John McCall67da35c2010-02-04 22:26:26 +00004081
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004082 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
Richard Smith053f6c62014-05-16 23:01:30 +00004083 struct CXXRecordDecl::DefinitionData *Data =
John McCall67da35c2010-02-04 22:26:26 +00004084 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00004085 for (auto I : redecls())
Richard Smith64c06302014-05-22 23:19:02 +00004086 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00004087 }
Douglas Gregordee1be82009-01-17 00:42:38 +00004088}
4089
4090void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00004091 assert((!isa<CXXRecordDecl>(this) ||
4092 cast<CXXRecordDecl>(this)->hasDefinition()) &&
4093 "definition completed but not started");
4094
Erich Keanef92f31c2018-08-01 20:48:16 +00004095 setCompleteDefinition(true);
4096 setBeingDefined(false);
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00004097
4098 if (ASTMutationListener *L = getASTMutationListener())
4099 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00004100}
4101
John McCallf937c022011-10-07 06:10:15 +00004102TagDecl *TagDecl::getDefinition() const {
4103 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00004104 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00004105
4106 // If it's possible for us to have an out-of-date definition, check now.
Erich Keanef92f31c2018-08-01 20:48:16 +00004107 if (mayHaveOutOfDateDef()) {
Douglas Gregor7dab26b2013-02-09 01:35:03 +00004108 if (IdentifierInfo *II = getIdentifier()) {
4109 if (II->isOutOfDate()) {
4110 updateOutOfDate(*II);
4111 }
4112 }
4113 }
4114
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004115 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
Andrew Trickba266ee2010-10-19 21:54:32 +00004116 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00004117
Aaron Ballman86c93902014-03-06 23:45:36 +00004118 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00004119 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00004120 return R;
Mike Stump11289f42009-09-09 15:08:12 +00004121
Craig Topper36250ad2014-05-12 05:36:57 +00004122 return nullptr;
Ted Kremenek21475702008-09-05 17:16:31 +00004123}
4124
Douglas Gregor14454802011-02-25 02:25:35 +00004125void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
4126 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00004127 // Make sure the extended qualifier info is allocated.
4128 if (!hasExtInfo())
David Majnemer00350522015-08-31 18:48:39 +00004129 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00004130 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00004131 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004132 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00004133 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00004134 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00004135 if (getExtInfo()->NumTemplParamLists == 0) {
4136 getASTContext().Deallocate(getExtInfo());
David Majnemer00350522015-08-31 18:48:39 +00004137 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
Abramo Bagnara60804e12011-03-18 15:16:37 +00004138 }
4139 else
4140 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00004141 }
4142 }
4143}
4144
Benjamin Kramer9cc210652015-08-05 09:40:49 +00004145void TagDecl::setTemplateParameterListsInfo(
4146 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
4147 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00004148 // Make sure the extended decl info is allocated.
4149 if (!hasExtInfo())
4150 // Allocate external info struct.
David Majnemer00350522015-08-31 18:48:39 +00004151 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00004152 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00004153 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00004154}
4155
Ted Kremenek21475702008-09-05 17:16:31 +00004156//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00004157// EnumDecl Implementation
4158//===----------------------------------------------------------------------===//
4159
Erich Keanef92f31c2018-08-01 20:48:16 +00004160EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4161 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
4162 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
4163 : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4164 assert(Scoped || !ScopedUsingClassTag);
4165 IntegerType = nullptr;
4166 setNumPositiveBits(0);
4167 setNumNegativeBits(0);
4168 setScoped(Scoped);
4169 setScopedUsingClassTag(ScopedUsingClassTag);
4170 setFixed(Fixed);
4171 setHasODRHash(false);
4172 ODRHash = 0;
4173}
4174
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004175void EnumDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004176
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004177EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
4178 SourceLocation StartLoc, SourceLocation IdLoc,
4179 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00004180 EnumDecl *PrevDecl, bool IsScoped,
4181 bool IsScopedUsingClassTag, bool IsFixed) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004182 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
4183 IsScoped, IsScopedUsingClassTag, IsFixed);
Erich Keanef92f31c2018-08-01 20:48:16 +00004184 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
Sebastian Redl833ef452010-01-26 22:01:41 +00004185 C.getTypeDeclType(Enum, PrevDecl);
4186 return Enum;
4187}
4188
Douglas Gregor72172e92012-01-05 21:55:30 +00004189EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004190 EnumDecl *Enum =
4191 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
4192 nullptr, nullptr, false, false, false);
Erich Keanef92f31c2018-08-01 20:48:16 +00004193 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00004194 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00004195}
4196
Alp Tokerb9fa5122014-01-06 11:31:18 +00004197SourceRange EnumDecl::getIntegerTypeRange() const {
4198 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
4199 return TI->getTypeLoc().getSourceRange();
4200 return SourceRange();
4201}
4202
Douglas Gregord5058122010-02-11 01:19:42 +00004203void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00004204 QualType NewPromotionType,
4205 unsigned NumPositiveBits,
4206 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00004207 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00004208 if (!IntegerType)
4209 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00004210 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00004211 setNumPositiveBits(NumPositiveBits);
4212 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00004213 TagDecl::completeDefinition();
4214}
4215
Akira Hatanaka3c268af2017-03-21 02:23:00 +00004216bool EnumDecl::isClosed() const {
4217 if (const auto *A = getAttr<EnumExtensibilityAttr>())
4218 return A->getExtensibility() == EnumExtensibilityAttr::Closed;
4219 return true;
4220}
4221
4222bool EnumDecl::isClosedFlag() const {
4223 return isClosed() && hasAttr<FlagEnumAttr>();
4224}
4225
4226bool EnumDecl::isClosedNonFlag() const {
4227 return isClosed() && !hasAttr<FlagEnumAttr>();
4228}
4229
Richard Smith7d137e32012-03-23 03:33:32 +00004230TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
4231 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
4232 return MSI->getTemplateSpecializationKind();
4233
4234 return TSK_Undeclared;
4235}
4236
4237void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4238 SourceLocation PointOfInstantiation) {
4239 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
4240 assert(MSI && "Not an instantiated member enumeration?");
4241 MSI->setTemplateSpecializationKind(TSK);
4242 if (TSK != TSK_ExplicitSpecialization &&
4243 PointOfInstantiation.isValid() &&
4244 MSI->getPointOfInstantiation().isInvalid())
4245 MSI->setPointOfInstantiation(PointOfInstantiation);
4246}
4247
Richard Smith6739a102016-05-05 00:56:12 +00004248EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
4249 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
4250 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
4251 EnumDecl *ED = getInstantiatedFromMemberEnum();
4252 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
4253 ED = NewED;
Richard Smith2195ec92017-04-21 01:15:13 +00004254 return getDefinitionOrSelf(ED);
Richard Smith6739a102016-05-05 00:56:12 +00004255 }
4256 }
4257
4258 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
4259 "couldn't find pattern for enum instantiation");
4260 return nullptr;
4261}
4262
Richard Smith4b38ded2012-03-14 23:13:10 +00004263EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
4264 if (SpecializationInfo)
4265 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
4266
Craig Topper36250ad2014-05-12 05:36:57 +00004267 return nullptr;
Richard Smith4b38ded2012-03-14 23:13:10 +00004268}
4269
4270void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
4271 TemplateSpecializationKind TSK) {
4272 assert(!SpecializationInfo && "Member enum is already a specialization");
4273 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
4274}
4275
Richard Trieuab4d7302018-07-25 22:52:05 +00004276unsigned EnumDecl::getODRHash() {
Erich Keanef92f31c2018-08-01 20:48:16 +00004277 if (hasODRHash())
Richard Trieuab4d7302018-07-25 22:52:05 +00004278 return ODRHash;
4279
4280 class ODRHash Hash;
4281 Hash.AddEnumDecl(this);
Erich Keanef92f31c2018-08-01 20:48:16 +00004282 setHasODRHash(true);
Richard Trieuab4d7302018-07-25 22:52:05 +00004283 ODRHash = Hash.CalculateHash();
4284 return ODRHash;
4285}
4286
Sebastian Redl833ef452010-01-26 22:01:41 +00004287//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00004288// RecordDecl Implementation
4289//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00004290
Richard Smith053f6c62014-05-16 23:01:30 +00004291RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
4292 DeclContext *DC, SourceLocation StartLoc,
4293 SourceLocation IdLoc, IdentifierInfo *Id,
4294 RecordDecl *PrevDecl)
Erich Keanef92f31c2018-08-01 20:48:16 +00004295 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4296 assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
4297 setHasFlexibleArrayMember(false);
4298 setAnonymousStructOrUnion(false);
4299 setHasObjectMember(false);
4300 setHasVolatileMember(false);
4301 setHasLoadedFieldsFromExternalStorage(false);
4302 setNonTrivialToPrimitiveDefaultInitialize(false);
4303 setNonTrivialToPrimitiveCopy(false);
4304 setNonTrivialToPrimitiveDestroy(false);
Akira Hatanaka09051062019-09-07 00:34:43 +00004305 setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false);
4306 setHasNonTrivialToPrimitiveDestructCUnion(false);
4307 setHasNonTrivialToPrimitiveCopyCUnion(false);
Erich Keanef92f31c2018-08-01 20:48:16 +00004308 setParamDestroyedInCallee(false);
4309 setArgPassingRestrictions(APK_CanPassInRegs);
Ted Kremenek52baf502008-09-02 21:12:32 +00004310}
4311
Jay Foad39c79802011-01-12 09:06:06 +00004312RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004313 SourceLocation StartLoc, SourceLocation IdLoc,
4314 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smith053f6c62014-05-16 23:01:30 +00004315 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
4316 StartLoc, IdLoc, Id, PrevDecl);
Erich Keanef92f31c2018-08-01 20:48:16 +00004317 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00004318
Ted Kremenek21475702008-09-05 17:16:31 +00004319 C.getTypeDeclType(R, PrevDecl);
4320 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00004321}
4322
Douglas Gregor72172e92012-01-05 21:55:30 +00004323RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004324 RecordDecl *R =
4325 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
4326 SourceLocation(), nullptr, nullptr);
Erich Keanef92f31c2018-08-01 20:48:16 +00004327 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00004328 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00004329}
4330
Douglas Gregordfcad112009-03-25 15:59:44 +00004331bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00004332 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00004333 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
4334}
4335
Alexey Bataev39c81e22014-08-28 04:28:19 +00004336bool RecordDecl::isLambda() const {
4337 if (auto RD = dyn_cast<CXXRecordDecl>(this))
4338 return RD->isLambda();
4339 return false;
4340}
4341
Alexey Bataev330de032014-10-29 12:21:55 +00004342bool RecordDecl::isCapturedRecord() const {
4343 return hasAttr<CapturedRecordAttr>();
4344}
4345
4346void RecordDecl::setCapturedRecord() {
4347 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
4348}
4349
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004350RecordDecl::field_iterator RecordDecl::field_begin() const {
Erich Keanef92f31c2018-08-01 20:48:16 +00004351 if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004352 LoadFieldsFromExternalStorage();
4353
4354 return field_iterator(decl_iterator(FirstDecl));
4355}
4356
Douglas Gregorb11aad82011-02-19 18:51:44 +00004357/// completeDefinition - Notes that the definition of this type is now
4358/// complete.
4359void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00004360 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00004361 TagDecl::completeDefinition();
4362}
4363
Eli Friedman9ee2d0472012-10-12 23:29:20 +00004364/// isMsStruct - Get whether or not this record uses ms_struct layout.
4365/// This which can be turned on with an attribute, pragma, or the
4366/// -mms-bitfields command-line option.
4367bool RecordDecl::isMsStruct(const ASTContext &C) const {
David Majnemer8ab003a2015-02-02 19:30:52 +00004368 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00004369}
4370
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004371void RecordDecl::LoadFieldsFromExternalStorage() const {
4372 ExternalASTSource *Source = getASTContext().getExternalSource();
4373 assert(hasExternalLexicalStorage() && Source && "No external storage?");
4374
4375 // Notify that we have a RecordDecl doing some initialization.
4376 ExternalASTSource::Deserializing TheFields(Source);
4377
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004378 SmallVector<Decl*, 64> Decls;
Erich Keanef92f31c2018-08-01 20:48:16 +00004379 setHasLoadedFieldsFromExternalStorage(true);
Richard Smith3cb15722015-08-05 22:41:45 +00004380 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
4381 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
4382 }, Decls);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004383
4384#ifndef NDEBUG
4385 // Check that all decls we got were FieldDecls.
4386 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00004387 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004388#endif
4389
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004390 if (Decls.empty())
4391 return;
4392
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00004393 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00004394 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004395}
4396
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004397bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
4398 ASTContext &Context = getASTContext();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004399 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
4400 (SanitizerKind::Address | SanitizerKind::KernelAddress);
4401 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004402 return false;
Alexey Samsonov33e00e22014-10-16 23:50:26 +00004403 const auto &Blacklist = Context.getSanitizerBlacklist();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004404 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004405 // We may be able to relax some of these requirements.
4406 int ReasonToReject = -1;
4407 if (!CXXRD || CXXRD->isExternCContext())
4408 ReasonToReject = 0; // is not C++.
4409 else if (CXXRD->hasAttr<PackedAttr>())
4410 ReasonToReject = 1; // is packed.
4411 else if (CXXRD->isUnion())
4412 ReasonToReject = 2; // is a union.
4413 else if (CXXRD->isTriviallyCopyable())
4414 ReasonToReject = 3; // is trivially copyable.
4415 else if (CXXRD->hasTrivialDestructor())
4416 ReasonToReject = 4; // has trivial destructor.
4417 else if (CXXRD->isStandardLayout())
4418 ReasonToReject = 5; // is standard layout.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004419 else if (Blacklist.isBlacklistedLocation(EnabledAsanMask, getLocation(),
4420 "field-padding"))
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004421 ReasonToReject = 6; // is in a blacklisted file.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004422 else if (Blacklist.isBlacklistedType(EnabledAsanMask,
4423 getQualifiedNameAsString(),
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004424 "field-padding"))
4425 ReasonToReject = 7; // is blacklisted.
4426
4427 if (EmitRemark) {
4428 if (ReasonToReject >= 0)
4429 Context.getDiagnostics().Report(
4430 getLocation(),
4431 diag::remark_sanitize_address_insert_extra_padding_rejected)
4432 << getQualifiedNameAsString() << ReasonToReject;
4433 else
4434 Context.getDiagnostics().Report(
4435 getLocation(),
4436 diag::remark_sanitize_address_insert_extra_padding_accepted)
4437 << getQualifiedNameAsString();
4438 }
4439 return ReasonToReject < 0;
4440}
4441
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004442const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
4443 for (const auto *I : fields()) {
4444 if (I->getIdentifier())
4445 return I;
4446
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004447 if (const auto *RT = I->getType()->getAs<RecordType>())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004448 if (const FieldDecl *NamedDataMember =
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004449 RT->getDecl()->findFirstNamedDataMember())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004450 return NamedDataMember;
4451 }
4452
4453 // We didn't find a named data member.
4454 return nullptr;
4455}
4456
Steve Naroff415d3d52008-10-08 17:01:13 +00004457//===----------------------------------------------------------------------===//
4458// BlockDecl Implementation
4459//===----------------------------------------------------------------------===//
4460
Erich Keanec9d29902018-08-01 21:16:54 +00004461BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
4462 : Decl(Block, DC, CaretLoc), DeclContext(Block) {
4463 setIsVariadic(false);
4464 setCapturesCXXThis(false);
4465 setBlockMissingReturnType(true);
4466 setIsConversionFromLambda(false);
4467 setDoesNotEscape(false);
Akira Hatanakac5792aa2019-02-27 18:17:16 +00004468 setCanAvoidCopyToHeap(false);
Erich Keanec9d29902018-08-01 21:16:54 +00004469}
4470
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004471void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00004472 assert(!ParamInfo && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00004473
Steve Naroffc4b30e52009-03-13 16:56:44 +00004474 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00004475 if (!NewParamInfo.empty()) {
4476 NumParams = NewParamInfo.size();
4477 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
4478 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00004479 }
4480}
4481
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004482void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4483 bool CapturesCXXThis) {
Erich Keanec9d29902018-08-01 21:16:54 +00004484 this->setCapturesCXXThis(CapturesCXXThis);
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004485 this->NumCaptures = Captures.size();
John McCallc63de662011-02-02 13:00:07 +00004486
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004487 if (Captures.empty()) {
4488 this->Captures = nullptr;
John McCallc63de662011-02-02 13:00:07 +00004489 return;
4490 }
4491
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004492 this->Captures = Captures.copy(Context).data();
Steve Naroffc4b30e52009-03-13 16:56:44 +00004493}
Sebastian Redl833ef452010-01-26 22:01:41 +00004494
John McCallce45f882011-06-15 22:51:16 +00004495bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00004496 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00004497 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00004498 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00004499 return true;
4500
4501 return false;
4502}
4503
Douglas Gregor70226da2010-12-21 16:27:07 +00004504SourceRange BlockDecl::getSourceRange() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004505 return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
Douglas Gregor70226da2010-12-21 16:27:07 +00004506}
Sebastian Redl833ef452010-01-26 22:01:41 +00004507
4508//===----------------------------------------------------------------------===//
4509// Other Decl Allocation/Deallocation Method Implementations
4510//===----------------------------------------------------------------------===//
4511
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004512void TranslationUnitDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004513
Sebastian Redl833ef452010-01-26 22:01:41 +00004514TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Craig Topper36250ad2014-05-12 05:36:57 +00004515 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00004516}
4517
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004518void PragmaCommentDecl::anchor() {}
Nico Weber66220292016-03-02 17:28:48 +00004519
4520PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4521 TranslationUnitDecl *DC,
4522 SourceLocation CommentLoc,
4523 PragmaMSCommentKind CommentKind,
4524 StringRef Arg) {
4525 PragmaCommentDecl *PCD =
4526 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4527 PragmaCommentDecl(DC, CommentLoc, CommentKind);
4528 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4529 PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4530 return PCD;
4531}
4532
4533PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4534 unsigned ID,
4535 unsigned ArgSize) {
4536 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
4537 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
4538}
4539
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004540void PragmaDetectMismatchDecl::anchor() {}
Nico Webercbbaeb12016-03-02 19:28:54 +00004541
4542PragmaDetectMismatchDecl *
4543PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4544 SourceLocation Loc, StringRef Name,
4545 StringRef Value) {
4546 size_t ValueStart = Name.size() + 1;
4547 PragmaDetectMismatchDecl *PDMD =
4548 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4549 PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4550 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4551 PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4552 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4553 Value.size());
4554 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4555 return PDMD;
4556}
4557
4558PragmaDetectMismatchDecl *
4559PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4560 unsigned NameValueSize) {
4561 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4562 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4563}
Nico Weber66220292016-03-02 17:28:48 +00004564
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004565void ExternCContextDecl::anchor() {}
Richard Smithf19e1272015-03-07 00:04:49 +00004566
4567ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4568 TranslationUnitDecl *DC) {
4569 return new (C, DC) ExternCContextDecl(DC);
4570}
4571
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004572void LabelDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004573
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004574LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004575 SourceLocation IdentL, IdentifierInfo *II) {
Craig Topper36250ad2014-05-12 05:36:57 +00004576 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004577}
4578
4579LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4580 SourceLocation IdentL, IdentifierInfo *II,
4581 SourceLocation GnuLabelL) {
4582 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Craig Topper36250ad2014-05-12 05:36:57 +00004583 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004584}
4585
Douglas Gregor72172e92012-01-05 21:55:30 +00004586LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004587 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
4588 SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00004589}
4590
Ehsan Akhgari31097582014-09-22 02:21:54 +00004591void LabelDecl::setMSAsmLabel(StringRef Name) {
Vlad Tsyrklevich38839d02019-10-28 14:36:31 -07004592 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
Ehsan Akhgari31097582014-09-22 02:21:54 +00004593 memcpy(Buffer, Name.data(), Name.size());
4594 Buffer[Name.size()] = '\0';
4595 MSAsmName = Buffer;
4596}
4597
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004598void ValueDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004599
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004600bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00004601 for (const auto *I : attrs())
4602 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004603 return true;
4604
4605 return isWeakImported();
4606}
4607
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004608void ImplicitParamDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004609
Sebastian Redl833ef452010-01-26 22:01:41 +00004610ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004611 SourceLocation IdLoc,
Alexey Bataev56223232017-06-09 13:40:18 +00004612 IdentifierInfo *Id, QualType Type,
4613 ImplicitParamKind ParamKind) {
4614 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
4615}
4616
4617ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
4618 ImplicitParamKind ParamKind) {
4619 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
Sebastian Redl833ef452010-01-26 22:01:41 +00004620}
4621
Richard Smithf7981722013-11-22 09:01:48 +00004622ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004623 unsigned ID) {
Alexey Bataev56223232017-06-09 13:40:18 +00004624 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
Douglas Gregor72172e92012-01-05 21:55:30 +00004625}
4626
Sebastian Redl833ef452010-01-26 22:01:41 +00004627FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004628 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004629 const DeclarationNameInfo &NameInfo,
4630 QualType T, TypeSourceInfo *TInfo,
Gauthier Harnisch796ed032019-06-14 08:56:20 +00004631 StorageClass SC, bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00004632 bool hasWrittenPrototype,
Gauthier Harnisch796ed032019-06-14 08:56:20 +00004633 ConstexprSpecKind ConstexprKind) {
Richard Smithf7981722013-11-22 09:01:48 +00004634 FunctionDecl *New =
Richard Smith053f6c62014-05-16 23:01:30 +00004635 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
Gauthier Harnisch796ed032019-06-14 08:56:20 +00004636 SC, isInlineSpecified, ConstexprKind);
Erich Keane9c665062018-08-01 21:02:40 +00004637 New->setHasWrittenPrototype(hasWrittenPrototype);
Sebastian Redl833ef452010-01-26 22:01:41 +00004638 return New;
4639}
4640
Douglas Gregor72172e92012-01-05 21:55:30 +00004641FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004642 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004643 DeclarationNameInfo(), QualType(), nullptr,
Gauthier Harnisch796ed032019-06-14 08:56:20 +00004644 SC_None, false, CSK_unspecified);
Douglas Gregor72172e92012-01-05 21:55:30 +00004645}
4646
Sebastian Redl833ef452010-01-26 22:01:41 +00004647BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004648 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00004649}
4650
Douglas Gregor72172e92012-01-05 21:55:30 +00004651BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004652 return new (C, ID) BlockDecl(nullptr, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00004653}
4654
Chandler Carruth21c90602015-12-30 03:24:14 +00004655CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
4656 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4657 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
4658
Ben Langmuir37943a72013-05-03 19:00:33 +00004659CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
4660 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004661 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Richard Smithf7981722013-11-22 09:01:48 +00004662 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004663}
4664
Ben Langmuirce914fc2013-05-03 19:20:19 +00004665CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00004666 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004667 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Craig Topper36250ad2014-05-12 05:36:57 +00004668 CapturedDecl(nullptr, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00004669}
4670
Chandler Carruth21c90602015-12-30 03:24:14 +00004671Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4672void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4673
4674bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4675void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4676
Sebastian Redl833ef452010-01-26 22:01:41 +00004677EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4678 SourceLocation L,
4679 IdentifierInfo *Id, QualType T,
4680 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00004681 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00004682}
4683
Douglas Gregor72172e92012-01-05 21:55:30 +00004684EnumConstantDecl *
4685EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004686 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4687 QualType(), nullptr, llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00004688}
4689
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004690void IndirectFieldDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004691
Richard Smith9f951822016-01-06 22:49:11 +00004692IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4693 SourceLocation L, DeclarationName N,
David Majnemer59f77922016-06-24 04:05:48 +00004694 QualType T,
4695 MutableArrayRef<NamedDecl *> CH)
4696 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4697 ChainingSize(CH.size()) {
Richard Smith9f951822016-01-06 22:49:11 +00004698 // In C++, indirect field declarations conflict with tag declarations in the
4699 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4700 if (C.getLangOpts().CPlusPlus)
4701 IdentifierNamespace |= IDNS_Tag;
4702}
4703
Benjamin Kramer39593702010-11-21 14:11:41 +00004704IndirectFieldDecl *
4705IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
David Majnemer59f77922016-06-24 04:05:48 +00004706 IdentifierInfo *Id, QualType T,
4707 llvm::MutableArrayRef<NamedDecl *> CH) {
4708 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
Francois Pichet783dd6e2010-11-21 06:08:52 +00004709}
4710
Douglas Gregor72172e92012-01-05 21:55:30 +00004711IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4712 unsigned ID) {
Richard Smith9f951822016-01-06 22:49:11 +00004713 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
David Majnemer59f77922016-06-24 04:05:48 +00004714 DeclarationName(), QualType(), None);
Douglas Gregor72172e92012-01-05 21:55:30 +00004715}
4716
Douglas Gregorbe996932010-09-01 20:41:53 +00004717SourceRange EnumConstantDecl::getSourceRange() const {
4718 SourceLocation End = getLocation();
4719 if (Init)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004720 End = Init->getEndLoc();
Douglas Gregorbe996932010-09-01 20:41:53 +00004721 return SourceRange(getLocation(), End);
4722}
4723
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004724void TypeDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004725
Sebastian Redl833ef452010-01-26 22:01:41 +00004726TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00004727 SourceLocation StartLoc, SourceLocation IdLoc,
4728 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004729 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00004730}
4731
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004732void TypedefNameDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004733
Richard Smith42413142015-05-15 20:05:43 +00004734TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4735 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4736 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4737 auto *ThisTypedef = this;
4738 if (AnyRedecl && OwningTypedef) {
4739 OwningTypedef = OwningTypedef->getCanonicalDecl();
4740 ThisTypedef = ThisTypedef->getCanonicalDecl();
4741 }
4742 if (OwningTypedef == ThisTypedef)
Richard Smitha5230222015-03-27 01:37:43 +00004743 return TT->getDecl();
Richard Smith42413142015-05-15 20:05:43 +00004744 }
Richard Smitha5230222015-03-27 01:37:43 +00004745
4746 return nullptr;
4747}
4748
Argyrios Kyrtzidis3b25c912017-03-21 16:56:02 +00004749bool TypedefNameDecl::isTransparentTagSlow() const {
4750 auto determineIsTransparent = [&]() {
4751 if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
4752 if (auto *TD = TT->getDecl()) {
4753 if (TD->getName() != getName())
4754 return false;
4755 SourceLocation TTLoc = getLocation();
4756 SourceLocation TDLoc = TD->getLocation();
4757 if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
4758 return false;
4759 SourceManager &SM = getASTContext().getSourceManager();
4760 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
4761 }
4762 }
4763 return false;
4764 };
4765
4766 bool isTransparent = determineIsTransparent();
Benjamin Kramerdfb730a2018-01-26 14:14:11 +00004767 MaybeModedTInfo.setInt((isTransparent << 1) | 1);
Argyrios Kyrtzidis3b25c912017-03-21 16:56:02 +00004768 return isTransparent;
4769}
4770
Douglas Gregor72172e92012-01-05 21:55:30 +00004771TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004772 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004773 nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004774}
4775
Richard Smithdda56e42011-04-15 14:24:37 +00004776TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4777 SourceLocation StartLoc,
4778 SourceLocation IdLoc, IdentifierInfo *Id,
4779 TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004780 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00004781}
4782
Douglas Gregor72172e92012-01-05 21:55:30 +00004783TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004784 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
4785 SourceLocation(), nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004786}
4787
Abramo Bagnaraea947882011-03-08 16:41:52 +00004788SourceRange TypedefDecl::getSourceRange() const {
4789 SourceLocation RangeEnd = getLocation();
4790 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4791 if (typeIsPostfix(TInfo->getType()))
4792 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4793 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004794 return SourceRange(getBeginLoc(), RangeEnd);
Abramo Bagnaraea947882011-03-08 16:41:52 +00004795}
4796
Richard Smithdda56e42011-04-15 14:24:37 +00004797SourceRange TypeAliasDecl::getSourceRange() const {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004798 SourceLocation RangeEnd = getBeginLoc();
Richard Smithdda56e42011-04-15 14:24:37 +00004799 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4800 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004801 return SourceRange(getBeginLoc(), RangeEnd);
Richard Smithdda56e42011-04-15 14:24:37 +00004802}
4803
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004804void FileScopeAsmDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004805
Sebastian Redl833ef452010-01-26 22:01:41 +00004806FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00004807 StringLiteral *Str,
4808 SourceLocation AsmLoc,
4809 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00004810 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00004811}
Douglas Gregorba345522011-12-02 23:23:56 +00004812
Richard Smithf7981722013-11-22 09:01:48 +00004813FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004814 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004815 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4816 SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00004817}
4818
Michael Han84324352013-02-22 17:15:32 +00004819void EmptyDecl::anchor() {}
4820
4821EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004822 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00004823}
4824
4825EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004826 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00004827}
4828
Douglas Gregorba345522011-12-02 23:23:56 +00004829//===----------------------------------------------------------------------===//
4830// ImportDecl Implementation
4831//===----------------------------------------------------------------------===//
4832
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004833/// Retrieve the number of module identifiers needed to name the given
Douglas Gregorba345522011-12-02 23:23:56 +00004834/// module.
4835static unsigned getNumModuleIdentifiers(Module *Mod) {
4836 unsigned Result = 1;
4837 while (Mod->Parent) {
4838 Mod = Mod->Parent;
4839 ++Result;
4840 }
4841 return Result;
4842}
4843
Fangrui Song6907ce22018-07-30 19:24:48 +00004844ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004845 Module *Imported,
4846 ArrayRef<SourceLocation> IdentifierLocs)
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004847 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true) {
Douglas Gregorba345522011-12-02 23:23:56 +00004848 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004849 auto *StoredLocs = getTrailingObjects<SourceLocation>();
James Y Knight7a22b242015-08-06 20:26:32 +00004850 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4851 StoredLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004852}
4853
Fangrui Song6907ce22018-07-30 19:24:48 +00004854ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004855 Module *Imported, SourceLocation EndLoc)
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004856 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false) {
James Y Knight7a22b242015-08-06 20:26:32 +00004857 *getTrailingObjects<SourceLocation>() = EndLoc;
Douglas Gregorba345522011-12-02 23:23:56 +00004858}
4859
Richard Smithf7981722013-11-22 09:01:48 +00004860ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004861 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004862 ArrayRef<SourceLocation> IdentifierLocs) {
James Y Knight7a22b242015-08-06 20:26:32 +00004863 return new (C, DC,
4864 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
Richard Smithf7981722013-11-22 09:01:48 +00004865 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004866}
4867
Richard Smithf7981722013-11-22 09:01:48 +00004868ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004869 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00004870 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004871 SourceLocation EndLoc) {
James Y Knight7a22b242015-08-06 20:26:32 +00004872 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
4873 ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00004874 Import->setImplicit();
4875 return Import;
4876}
4877
Douglas Gregor72172e92012-01-05 21:55:30 +00004878ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4879 unsigned NumLocations) {
James Y Knight7a22b242015-08-06 20:26:32 +00004880 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
Richard Smithf7981722013-11-22 09:01:48 +00004881 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00004882}
4883
4884ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4885 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004886 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00004887
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004888 const auto *StoredLocs = getTrailingObjects<SourceLocation>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00004889 return llvm::makeArrayRef(StoredLocs,
4890 getNumModuleIdentifiers(getImportedModule()));
Douglas Gregorba345522011-12-02 23:23:56 +00004891}
4892
4893SourceRange ImportDecl::getSourceRange() const {
4894 if (!ImportedAndComplete.getInt())
James Y Knight7a22b242015-08-06 20:26:32 +00004895 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
4896
Douglas Gregorba345522011-12-02 23:23:56 +00004897 return SourceRange(getLocation(), getIdentifierLocs().back());
4898}
Richard Smith8df390f2016-09-08 23:14:54 +00004899
4900//===----------------------------------------------------------------------===//
4901// ExportDecl Implementation
4902//===----------------------------------------------------------------------===//
4903
4904void ExportDecl::anchor() {}
4905
4906ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
4907 SourceLocation ExportLoc) {
4908 return new (C, DC) ExportDecl(DC, ExportLoc);
4909}
4910
4911ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4912 return new (C, ID) ExportDecl(nullptr, SourceLocation());
4913}