blob: b85e82d56de9d2c5eb8d9f741f740852e3f46729 [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//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera11999d2006-10-15 22:34:45 +00007//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidis63018842008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Chris Lattnera11999d2006-10-15 22:34:45 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
George Burgess IV99db3ea2017-08-09 04:02:49 +000015#include "Linkage.h"
Chris Lattnera7b32872008-03-15 06:12:44 +000016#include "clang/AST/ASTContext.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"
Kostya Serebryany293dc9b2014-10-16 20:54:52 +000052#include "clang/Frontend/FrontendDiagnostic.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000053#include "llvm/ADT/APSInt.h"
54#include "llvm/ADT/ArrayRef.h"
55#include "llvm/ADT/None.h"
56#include "llvm/ADT/Optional.h"
57#include "llvm/ADT/STLExtras.h"
58#include "llvm/ADT/SmallVector.h"
59#include "llvm/ADT/StringSwitch.h"
60#include "llvm/ADT/StringRef.h"
61#include "llvm/ADT/Triple.h"
62#include "llvm/Support/Casting.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000063#include "llvm/Support/ErrorHandling.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000064#include "llvm/Support/raw_ostream.h"
David Blaikie9c70e042011-09-21 18:16:56 +000065#include <algorithm>
Eugene Zelenkode0215c2017-11-13 23:01:27 +000066#include <cassert>
67#include <cstddef>
68#include <cstring>
69#include <memory>
70#include <string>
71#include <tuple>
72#include <type_traits>
David Blaikie9c70e042011-09-21 18:16:56 +000073
Chris Lattner6d9a6852006-10-25 05:11:20 +000074using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000075
Richard Smith0b87e072013-10-07 08:02:11 +000076Decl *clang::getPrimaryMergedDecl(Decl *D) {
77 return D->getASTContext().getPrimaryMergedDecl(D);
78}
79
Jordan Rose1e879d82018-03-23 00:07:18 +000080void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
81 SourceLocation Loc = this->Loc;
82 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
83 if (Loc.isValid()) {
84 Loc.print(OS, Context.getSourceManager());
85 OS << ": ";
86 }
87 OS << Message;
88
89 if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
90 OS << " '";
91 ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
92 OS << "'";
93 }
94
95 OS << '\n';
96}
97
Richard Smith73b21d82014-09-03 02:33:22 +000098// Defined here so that it can be inlined into its direct callers.
99bool Decl::isOutOfLine() const {
100 return !getLexicalDeclContext()->Equals(getDeclContext());
101}
102
Richard Smith42413142015-05-15 20:05:43 +0000103TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
104 : Decl(TranslationUnit, nullptr, SourceLocation()),
Eugene Zelenkode0215c2017-11-13 23:01:27 +0000105 DeclContext(TranslationUnit), Ctx(ctx) {}
Richard Smith42413142015-05-15 20:05:43 +0000106
Chris Lattner88f70d62008-03-15 05:43:15 +0000107//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000108// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000109//===----------------------------------------------------------------------===//
110
John McCalldf25c432013-02-16 00:17:33 +0000111// Visibility rules aren't rigorously externally specified, but here
112// are the basic principles behind what we implement:
113//
114// 1. An explicit visibility attribute is generally a direct expression
115// of the user's intent and should be honored. Only the innermost
116// visibility attribute applies. If no visibility attribute applies,
117// global visibility settings are considered.
118//
119// 2. There is one caveat to the above: on or in a template pattern,
120// an explicit visibility attribute is just a default rule, and
121// visibility can be decreased by the visibility of template
122// arguments. But this, too, has an exception: an attribute on an
123// explicit specialization or instantiation causes all the visibility
124// restrictions of the template arguments to be ignored.
125//
126// 3. A variable that does not otherwise have explicit visibility can
127// be restricted by the visibility of its type.
128//
129// 4. A visibility restriction is explicit if it comes from an
130// attribute (or something like it), not a global visibility setting.
131// When emitting a reference to an external symbol, visibility
132// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +0000133//
134// 5. When computing the visibility of a non-type, including a
135// non-type member of a class, only non-type visibility restrictions
136// are considered: the 'visibility' attribute, global value-visibility
137// settings, and a few special cases like __private_extern.
138//
139// 6. When computing the visibility of a type, including a type member
140// of a class, only type visibility restrictions are considered:
141// the 'type_visibility' attribute and global type-visibility settings.
142// However, a 'visibility' attribute counts as a 'type_visibility'
143// attribute on any declaration that only has the former.
144//
145// The visibility of a "secondary" entity, like a template argument,
146// is computed using the kind of that entity, not the kind of the
147// primary entity for which we are computing visibility. For example,
148// the visibility of a specialization of either of these templates:
149// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
150// template <class T, bool (&compare)(T, X)> class matcher;
151// is restricted according to the type visibility of the argument 'T',
152// the type visibility of 'bool(&)(T,X)', and the value visibility of
153// the argument function 'compare'. That 'has_match' is a value
154// and 'matcher' is a type only matters when looking for attributes
155// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +0000156
John McCalld041a9b2013-02-20 01:54:26 +0000157/// Does this computation kind permit us to consider additional
158/// visibility settings from attributes and the like?
159static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000160 return computation.IgnoreExplicitVisibility;
John McCalld041a9b2013-02-20 01:54:26 +0000161}
162
163/// Given an LVComputationKind, return one of the same type/value sort
164/// that records that it already has explicit visibility.
165static LVComputationKind
Richard Smithfbe7b462017-09-22 02:22:32 +0000166withExplicitVisibilityAlready(LVComputationKind Kind) {
167 Kind.IgnoreExplicitVisibility = true;
168 return Kind;
John McCalld041a9b2013-02-20 01:54:26 +0000169}
170
David Blaikie05785d12013-02-20 22:23:23 +0000171static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
172 LVComputationKind kind) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000173 assert(!kind.IgnoreExplicitVisibility &&
John McCalld041a9b2013-02-20 01:54:26 +0000174 "asking for explicit visibility when we shouldn't be");
Richard Smithfbe7b462017-09-22 02:22:32 +0000175 return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
John McCalld041a9b2013-02-20 01:54:26 +0000176}
177
John McCalldf25c432013-02-16 00:17:33 +0000178/// Is the given declaration a "type" or a "value" for the purposes of
179/// visibility computation?
180static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000181 return isa<TypeDecl>(D) ||
182 isa<ClassTemplateDecl>(D) ||
183 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000184}
185
John McCall5f46c482013-02-21 23:42:58 +0000186/// Does the given declaration have member specialization information,
187/// and if so, is it an explicit specialization?
188template <class T> static typename
Benjamin Kramered2f4762014-03-07 14:30:23 +0000189std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-02-21 23:42:58 +0000190isExplicitMemberSpecialization(const T *D) {
191 if (const MemberSpecializationInfo *member =
192 D->getMemberSpecializationInfo()) {
193 return member->isExplicitSpecialization();
194 }
195 return false;
196}
197
198/// For templates, this question is easier: a member template can't be
199/// explicitly instantiated, so there's a single bit indicating whether
200/// or not this is an explicit member specialization.
201static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
202 return D->isMemberSpecialization();
203}
204
John McCalld041a9b2013-02-20 01:54:26 +0000205/// Given a visibility attribute, return the explicit visibility
206/// associated with it.
207template <class T>
208static Visibility getVisibilityFromAttr(const T *attr) {
209 switch (attr->getVisibility()) {
210 case T::Default:
211 return DefaultVisibility;
212 case T::Hidden:
213 return HiddenVisibility;
214 case T::Protected:
215 return ProtectedVisibility;
216 }
217 llvm_unreachable("bad visibility kind");
218}
219
John McCalldf25c432013-02-16 00:17:33 +0000220/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000221static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000222 NamedDecl::ExplicitVisibilityKind kind) {
223 // If we're ultimately computing the visibility of a type, look for
224 // a 'type_visibility' attribute before looking for 'visibility'.
225 if (kind == NamedDecl::VisibilityForType) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000226 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000227 return getVisibilityFromAttr(A);
228 }
229 }
230
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000231 // If this declaration has an explicit visibility attribute, use it.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000232 if (const auto *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000233 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000234 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000235
David Blaikie7a30dc52013-02-21 01:47:18 +0000236 return None;
John McCall457a04e2010-10-22 21:05:15 +0000237}
238
George Burgess IV99db3ea2017-08-09 04:02:49 +0000239LinkageInfo LinkageComputer::getLVForType(const Type &T,
240 LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000241 if (computation.IgnoreAllVisibility)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000242 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
George Burgess IV35cb4f82017-08-09 04:12:17 +0000243 return getTypeLinkageAndVisibility(&T);
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000244}
245
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000246/// Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000247/// template parameter list. For visibility purposes, template
248/// parameters are part of the signature of a template.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000249LinkageInfo LinkageComputer::getLVForTemplateParameterList(
250 const TemplateParameterList *Params, LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000251 LinkageInfo LV;
David Majnemerc7b85c42014-04-23 05:16:48 +0000252 for (const NamedDecl *P : *Params) {
John McCalldf25c432013-02-16 00:17:33 +0000253 // Template type parameters are the most common and never
254 // contribute to visibility, pack or not.
David Majnemerc7b85c42014-04-23 05:16:48 +0000255 if (isa<TemplateTypeParmDecl>(P))
John McCalldf25c432013-02-16 00:17:33 +0000256 continue;
257
258 // Non-type template parameters can be restricted by the value type, e.g.
259 // template <enum X> class A { ... };
260 // We have to be careful here, though, because we can be dealing with
261 // dependent types.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000262 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
John McCalldf25c432013-02-16 00:17:33 +0000263 // Handle the non-pack case first.
264 if (!NTTP->isExpandedParameterPack()) {
265 if (!NTTP->getType()->isDependentType()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000266 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000267 }
268 continue;
269 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000270
John McCalldf25c432013-02-16 00:17:33 +0000271 // Look at all the types in an expanded pack.
272 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
273 QualType type = NTTP->getExpansionType(i);
274 if (!type->isDependentType())
George Burgess IV35cb4f82017-08-09 04:12:17 +0000275 LV.merge(getTypeLinkageAndVisibility(type));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000276 }
John McCalldf25c432013-02-16 00:17:33 +0000277 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000278 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000279
John McCalldf25c432013-02-16 00:17:33 +0000280 // Template template parameters can be restricted by their
281 // template parameters, recursively.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000282 const auto *TTP = cast<TemplateTemplateParmDecl>(P);
John McCalldf25c432013-02-16 00:17:33 +0000283
284 // Handle the non-pack case first.
285 if (!TTP->isExpandedParameterPack()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000286 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
287 computation));
John McCalldf25c432013-02-16 00:17:33 +0000288 continue;
289 }
290
291 // Look at all expansions in an expanded pack.
292 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
293 i != n; ++i) {
294 LV.merge(getLVForTemplateParameterList(
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000295 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000296 }
297 }
298
John McCall457a04e2010-10-22 21:05:15 +0000299 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000300}
301
Eli Friedman7e346a82013-07-01 20:22:57 +0000302static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
Craig Topper36250ad2014-05-12 05:36:57 +0000303 const Decl *Ret = nullptr;
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000304 const DeclContext *DC = D->getDeclContext();
305 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman7e346a82013-07-01 20:22:57 +0000306 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
307 Ret = cast<Decl>(DC);
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000308 DC = DC->getParent();
309 }
310 return Ret;
311}
312
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000313/// Get the most restrictive linkage for the types and
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000314/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000315///
316/// Note that we don't take an LVComputationKind because we always
317/// want to honor the visibility of template arguments in the same way.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000318LinkageInfo
319LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
320 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000321 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000322
David Majnemerc7b85c42014-04-23 05:16:48 +0000323 for (const TemplateArgument &Arg : Args) {
324 switch (Arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000325 case TemplateArgument::Null:
326 case TemplateArgument::Integral:
327 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000328 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000329
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000330 case TemplateArgument::Type:
David Majnemerc7b85c42014-04-23 05:16:48 +0000331 LV.merge(getLVForType(*Arg.getAsType(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000332 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000333
George Burgess IV00f70bd2018-03-01 05:43:23 +0000334 case TemplateArgument::Declaration: {
335 const NamedDecl *ND = Arg.getAsDecl();
336 assert(!usesTypeVisibility(ND));
337 LV.merge(getLVForDecl(ND, computation));
John McCalldf25c432013-02-16 00:17:33 +0000338 continue;
George Burgess IV00f70bd2018-03-01 05:43:23 +0000339 }
Eli Friedmanb826a002012-09-26 02:36:12 +0000340
341 case TemplateArgument::NullPtr:
George Burgess IV35cb4f82017-08-09 04:12:17 +0000342 LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
John McCalldf25c432013-02-16 00:17:33 +0000343 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000344
345 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000346 case TemplateArgument::TemplateExpansion:
David Majnemerc7b85c42014-04-23 05:16:48 +0000347 if (TemplateDecl *Template =
348 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000349 LV.merge(getLVForDecl(Template, computation));
John McCalldf25c432013-02-16 00:17:33 +0000350 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000351
352 case TemplateArgument::Pack:
David Majnemerc7b85c42014-04-23 05:16:48 +0000353 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000354 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000355 }
John McCalldf25c432013-02-16 00:17:33 +0000356 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000357 }
358
John McCall457a04e2010-10-22 21:05:15 +0000359 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000360}
361
George Burgess IV99db3ea2017-08-09 04:02:49 +0000362LinkageInfo
363LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
364 LVComputationKind computation) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000365 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall8823c652010-08-13 08:35:10 +0000366}
367
John McCall5f46c482013-02-21 23:42:58 +0000368static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
369 const FunctionTemplateSpecializationInfo *specInfo) {
370 // Include visibility from the template parameters and arguments
371 // only if this is not an explicit instantiation or specialization
372 // with direct explicit visibility. (Implicit instantiations won't
373 // have a direct attribute.)
374 if (!specInfo->isExplicitInstantiationOrSpecialization())
375 return true;
376
377 return !fn->hasAttr<VisibilityAttr>();
378}
379
John McCalldf25c432013-02-16 00:17:33 +0000380/// Merge in template-related linkage and visibility for the given
381/// function template specialization.
382///
383/// We don't need a computation kind here because we can assume
384/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000385///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000386/// \param[out] LV the computation to use for the parent
George Burgess IV99db3ea2017-08-09 04:02:49 +0000387void LinkageComputer::mergeTemplateLV(
388 LinkageInfo &LV, const FunctionDecl *fn,
389 const FunctionTemplateSpecializationInfo *specInfo,
390 LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000391 bool considerVisibility =
392 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000393
394 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000395 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000396 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000397 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000398 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
399
400 // Merge information from the template arguments.
401 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000402 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCalldf25c432013-02-16 00:17:33 +0000403 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000404}
405
John McCall5f46c482013-02-21 23:42:58 +0000406/// Does the given declaration have a direct visibility attribute
407/// that would match the given rules?
408static bool hasDirectVisibilityAttribute(const NamedDecl *D,
409 LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000410 if (computation.IgnoreAllVisibility)
John McCall5f46c482013-02-21 23:42:58 +0000411 return false;
Richard Smithfbe7b462017-09-22 02:22:32 +0000412
413 return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
414 D->hasAttr<VisibilityAttr>();
John McCall5f46c482013-02-21 23:42:58 +0000415}
416
John McCalld041a9b2013-02-20 01:54:26 +0000417/// Should we consider visibility associated with the template
418/// arguments and parameters of the given class template specialization?
419static bool shouldConsiderTemplateVisibility(
420 const ClassTemplateSpecializationDecl *spec,
421 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000422 // Include visibility from the template parameters and arguments
423 // only if this is not an explicit instantiation or specialization
424 // with direct explicit visibility (and note that implicit
425 // instantiations won't have a direct attribute).
426 //
427 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000428 // for an explicit specialization when computing the visibility of a
429 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000430 //
431 // This is a bit complex; let's unpack it.
432 //
433 // An explicit class specialization is an independent, top-level
434 // declaration. As such, if it or any of its members has an
435 // explicit visibility attribute, that must directly express the
436 // user's intent, and we should honor it. The same logic applies to
437 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000438
439 // Fast path: if this is not an explicit instantiation or
440 // specialization, we always want to consider template-related
441 // visibility restrictions.
442 if (!spec->isExplicitInstantiationOrSpecialization())
443 return true;
444
445 // This is the 'member thereof' check.
446 if (spec->isExplicitSpecialization() &&
447 hasExplicitVisibilityAlready(computation))
448 return false;
449
John McCall5f46c482013-02-21 23:42:58 +0000450 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000451}
452
453/// Merge in template-related linkage and visibility for the given
454/// class template specialization.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000455void LinkageComputer::mergeTemplateLV(
456 LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,
457 LVComputationKind computation) {
John McCalld041a9b2013-02-20 01:54:26 +0000458 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000459
460 // Merge information from the template parameters, but ignore
461 // visibility if we're only considering template arguments.
462
John McCalld041a9b2013-02-20 01:54:26 +0000463 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000464 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000465 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000466 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000467 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000468
469 // Merge information from the template arguments. We ignore
470 // template-argument visibility if we've got an explicit
471 // instantiation with a visibility attribute.
472 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000473 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000474 if (considerVisibility)
475 LV.mergeVisibility(argsLV);
476 LV.mergeExternalVisibility(argsLV);
John McCallb8c604a2011-06-27 23:06:04 +0000477}
478
Larisse Voufo5899e192014-07-02 23:08:34 +0000479/// Should we consider visibility associated with the template
480/// arguments and parameters of the given variable template
481/// specialization? As usual, follow class template specialization
482/// logic up to initialization.
483static bool shouldConsiderTemplateVisibility(
484 const VarTemplateSpecializationDecl *spec,
485 LVComputationKind computation) {
486 // Include visibility from the template parameters and arguments
487 // only if this is not an explicit instantiation or specialization
488 // with direct explicit visibility (and note that implicit
489 // instantiations won't have a direct attribute).
490 if (!spec->isExplicitInstantiationOrSpecialization())
491 return true;
492
493 // An explicit variable specialization is an independent, top-level
494 // declaration. As such, if it has an explicit visibility attribute,
495 // that must directly express the user's intent, and we should honor
496 // it.
497 if (spec->isExplicitSpecialization() &&
498 hasExplicitVisibilityAlready(computation))
499 return false;
500
501 return !hasDirectVisibilityAttribute(spec, computation);
502}
503
504/// Merge in template-related linkage and visibility for the given
505/// variable template specialization. As usual, follow class template
506/// specialization logic up to initialization.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000507void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
508 const VarTemplateSpecializationDecl *spec,
509 LVComputationKind computation) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000510 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
511
512 // Merge information from the template parameters, but ignore
513 // visibility if we're only considering template arguments.
514
515 VarTemplateDecl *temp = spec->getSpecializedTemplate();
516 LinkageInfo tempLV =
517 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
518 LV.mergeMaybeWithVisibility(tempLV,
519 considerVisibility && !hasExplicitVisibilityAlready(computation));
520
521 // Merge information from the template arguments. We ignore
522 // template-argument visibility if we've got an explicit
523 // instantiation with a visibility attribute.
524 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
525 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
526 if (considerVisibility)
527 LV.mergeVisibility(argsLV);
528 LV.mergeExternalVisibility(argsLV);
529}
530
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000531static bool useInlineVisibilityHidden(const NamedDecl *D) {
532 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000533 const LangOptions &Opts = D->getASTContext().getLangOpts();
534 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000535 return false;
536
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000537 const auto *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000538 if (!FD)
539 return false;
540
541 TemplateSpecializationKind TSK = TSK_Undeclared;
542 if (FunctionTemplateSpecializationInfo *spec
543 = FD->getTemplateSpecializationInfo()) {
544 TSK = spec->getTemplateSpecializationKind();
545 } else if (MemberSpecializationInfo *MSI =
546 FD->getMemberSpecializationInfo()) {
547 TSK = MSI->getTemplateSpecializationKind();
548 }
549
Craig Topper36250ad2014-05-12 05:36:57 +0000550 const FunctionDecl *Def = nullptr;
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000551 // InlineVisibilityHidden only applies to definitions, and
552 // isInlined() only gives meaningful answers on definitions
553 // anyway.
554 return TSK != TSK_ExplicitInstantiationDeclaration &&
555 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000556 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000557}
558
Rafael Espindola593537a2013-05-05 20:15:21 +0000559template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000560 const T *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +0000561 return First->isInExternCContext();
Rafael Espindolaf4187652013-02-14 01:18:37 +0000562}
563
Richard Smith03c05032014-02-17 23:34:47 +0000564static bool isSingleLineLanguageLinkage(const Decl &D) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000565 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Richard Smith03c05032014-02-17 23:34:47 +0000566 if (!SD->hasBraces())
Rafael Espindola327be3c2013-04-26 01:30:23 +0000567 return true;
568 return false;
569}
570
Richard Smith1283e982017-07-07 20:04:28 +0000571static bool isExportedFromModuleIntefaceUnit(const NamedDecl *D) {
Richard Smithbecb92d2017-10-10 22:33:17 +0000572 // FIXME: Handle isModulePrivate.
Richard Smith1283e982017-07-07 20:04:28 +0000573 switch (D->getModuleOwnershipKind()) {
574 case Decl::ModuleOwnershipKind::Unowned:
575 case Decl::ModuleOwnershipKind::ModulePrivate:
576 return false;
577 case Decl::ModuleOwnershipKind::Visible:
578 case Decl::ModuleOwnershipKind::VisibleWhenImported:
579 if (auto *M = D->getOwningModule())
580 return M->Kind == Module::ModuleInterfaceUnit;
581 }
582 llvm_unreachable("unexpected module ownership kind");
583}
584
585static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
586 // Internal linkage declarations within a module interface unit are modeled
587 // as "module-internal linkage", which means that they have internal linkage
588 // formally but can be indirectly accessed from outside the module via inline
589 // functions and templates defined within the module.
590 if (auto *M = D->getOwningModule())
591 if (M->Kind == Module::ModuleInterfaceUnit)
592 return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false);
593
594 return LinkageInfo::internal();
595}
596
597static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
598 // C++ Modules TS [basic.link]/6.8:
599 // - A name declared at namespace scope that does not have internal linkage
600 // by the previous rules and that is introduced by a non-exported
601 // declaration has module linkage.
602 if (auto *M = D->getOwningModule())
603 if (M->Kind == Module::ModuleInterfaceUnit)
Richard Smithbecb92d2017-10-10 22:33:17 +0000604 if (!isExportedFromModuleIntefaceUnit(
605 cast<NamedDecl>(D->getCanonicalDecl())))
Richard Smith1283e982017-07-07 20:04:28 +0000606 return LinkageInfo(ModuleLinkage, DefaultVisibility, false);
607
608 return LinkageInfo::external();
609}
610
George Burgess IV99db3ea2017-08-09 04:02:49 +0000611LinkageInfo
612LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +0000613 LVComputationKind computation,
614 bool IgnoreVarTypeLinkage) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000615 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000616 "Not a name having namespace scope");
617 ASTContext &Context = D->getASTContext();
618
619 // C++ [basic.link]p3:
620 // A name having namespace scope (3.3.6) has internal linkage if it
621 // is the name of
622 // - an object, reference, function or function template that is
623 // explicitly declared static; or,
624 // (This bullet corresponds to C99 6.2.2p3.)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000625 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000626 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000627 if (Var->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000628 return getInternalLinkageFor(Var);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000629
Richard Smith62f19e72016-06-25 00:15:56 +0000630 // - a non-inline, non-volatile object or reference that is explicitly
631 // declared const or constexpr and neither explicitly declared extern
632 // nor previously declared to have external linkage; or (there is no
633 // equivalent in C99)
Richard Smith1283e982017-07-07 20:04:28 +0000634 // The C++ modules TS adds "non-exported" to this list.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000635 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000636 Var->getType().isConstQualified() &&
Richard Smith62f19e72016-06-25 00:15:56 +0000637 !Var->getType().isVolatileQualified() &&
Richard Smith1283e982017-07-07 20:04:28 +0000638 !Var->isInline() &&
639 !isExportedFromModuleIntefaceUnit(Var)) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000640 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000641 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000642 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000643
644 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000645 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000646 !isSingleLineLanguageLinkage(*Var))
Richard Smith1283e982017-07-07 20:04:28 +0000647 return getInternalLinkageFor(Var);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000648 }
649
650 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
651 PrevVar = PrevVar->getPreviousDecl()) {
652 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
653 Var->getStorageClass() == SC_None)
George Burgess IV35cb4f82017-08-09 04:12:17 +0000654 return getDeclLinkageAndVisibility(PrevVar);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000655 // Explicitly declared static.
656 if (PrevVar->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000657 return getInternalLinkageFor(Var);
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000658 }
Alp Tokera2794f92014-01-22 07:29:52 +0000659 } else if (const FunctionDecl *Function = D->getAsFunction()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000660 // C++ [temp]p4:
661 // A non-member function template can have internal linkage; any
662 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000663
664 // Explicitly declared static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000665 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000666 return getInternalLinkageFor(Function);
David Majnemer18fac3b2014-12-10 22:58:14 +0000667 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
668 // - a data member of an anonymous union.
669 const VarDecl *VD = IFD->getVarDecl();
670 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
Richard Smithc95d2c52017-09-22 04:25:05 +0000671 return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000672 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000673 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000674
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000675 if (D->isInAnonymousNamespace()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000676 const auto *Var = dyn_cast<VarDecl>(D);
677 const auto *Func = dyn_cast<FunctionDecl>(D);
Richard Smithdf963a32017-09-22 22:21:44 +0000678 // FIXME: The check for extern "C" here is not justified by the standard
679 // wording, but we retain it from the pre-DR1113 model to avoid breaking
680 // code.
Richard Smith1283e982017-07-07 20:04:28 +0000681 //
682 // C++11 [basic.link]p4:
683 // An unnamed namespace or a namespace declared directly or indirectly
684 // within an unnamed namespace has internal linkage.
Rafael Espindola593537a2013-05-05 20:15:21 +0000685 if ((!Var || !isFirstInExternCContext(Var)) &&
686 (!Func || !isFirstInExternCContext(Func)))
Richard Smithdf963a32017-09-22 22:21:44 +0000687 return getInternalLinkageFor(D);
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000688 }
John McCallb7139c42010-10-28 04:18:25 +0000689
John McCall457a04e2010-10-22 21:05:15 +0000690 // Set up the defaults.
691
692 // C99 6.2.2p5:
693 // If the declaration of an identifier for an object has file
694 // scope and no storage-class specifier, its linkage is
695 // external.
Richard Smithdd8b5332017-09-04 05:37:53 +0000696 LinkageInfo LV = getExternalLinkageFor(D);
John McCallc273f242010-10-30 11:50:40 +0000697
John McCalld041a9b2013-02-20 01:54:26 +0000698 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000699 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000700 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000701 } else {
702 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000703 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000704 for (const DeclContext *DC = D->getDeclContext();
705 !isa<TranslationUnitDecl>(DC);
706 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000707 const auto *ND = dyn_cast<NamespaceDecl>(DC);
Rafael Espindola78158af2012-04-16 18:46:26 +0000708 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000709 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000710 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000711 break;
712 }
713 }
714 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000715
John McCalldf25c432013-02-16 00:17:33 +0000716 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000717 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000718 // Use global type/value visibility as appropriate.
Richard Smithfbe7b462017-09-22 02:22:32 +0000719 Visibility globalVisibility =
720 computation.isValueVisibility()
721 ? Context.getLangOpts().getValueVisibilityMode()
722 : Context.getLangOpts().getTypeVisibilityMode();
John McCallb4a99d32013-02-19 01:57:35 +0000723 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000724
725 // If we're paying attention to global visibility, apply
726 // -finline-visibility-hidden if this is an inline method.
727 if (useInlineVisibilityHidden(D))
728 LV.mergeVisibility(HiddenVisibility, true);
729 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000730 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000731
Douglas Gregorf73b2822009-11-25 22:24:25 +0000732 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000733
Douglas Gregorf73b2822009-11-25 22:24:25 +0000734 // A name having namespace scope has external linkage if it is the
735 // name of
736 //
737 // - an object or reference, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000738 if (const auto *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000739 // GCC applies the following optimization to variables and static
740 // data members, but not to functions:
741 //
John McCall457a04e2010-10-22 21:05:15 +0000742 // Modify the variable's LV by the LV of its type unless this is
743 // C or extern "C". This follows from [basic.link]p9:
744 // A type without linkage shall not be used as the type of a
745 // variable or function with external linkage unless
746 // - the entity has C language linkage, or
747 // - the entity is declared within an unnamed namespace, or
748 // - the entity is not used or is defined in the same
749 // translation unit.
750 // and [basic.link]p10:
751 // ...the types specified by all declarations referring to a
752 // given variable or function shall be identical...
753 // C does not have an equivalent rule.
754 //
John McCall5fe84122010-10-26 04:59:26 +0000755 // Ignore this if we've got an explicit attribute; the user
756 // probably knows what they're doing.
757 //
John McCall457a04e2010-10-22 21:05:15 +0000758 // Note that we don't want to make the variable non-external
759 // because of this, but unique-external linkage suits us.
Richard Smithc95d2c52017-09-22 04:25:05 +0000760 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
761 !IgnoreVarTypeLinkage) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000762 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Richard Smith405e2db2017-09-20 07:22:00 +0000763 if (!isExternallyVisible(TypeLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000764 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000765 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000766 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000767 }
768
John McCall23032652010-11-02 18:38:13 +0000769 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000770 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000771
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000772 // Note that Sema::MergeVarDecl already takes care of implementing
773 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
774 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000775
Larisse Voufo5899e192014-07-02 23:08:34 +0000776 // As per function and class template specializations (below),
777 // consider LV for the template and template arguments. We're at file
778 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000779 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000780 mergeTemplateLV(LV, spec, computation);
781 }
782
Douglas Gregorf73b2822009-11-25 22:24:25 +0000783 // - a function, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000784 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000785 // In theory, we can modify the function's LV by the LV of its
786 // type unless it has C linkage (see comment above about variables
787 // for justification). In practice, GCC doesn't do this, so it's
788 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000789
John McCall23032652010-11-02 18:38:13 +0000790 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000791 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000792
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000793 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
794 // merging storage classes and visibility attributes, so we don't have to
795 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000796
John McCallf768aa72011-02-10 06:50:24 +0000797 // In C++, then if the type of the function uses a type with
798 // unique-external linkage, it's not legally usable from outside
799 // this translation unit. However, we should use the C linkage
800 // rules instead for extern "C" declarations.
Richard Smith99f54792018-01-03 02:34:35 +0000801 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
Richard Smithc95d2c52017-09-22 04:25:05 +0000802 // Only look at the type-as-written. Otherwise, deducing the return type
803 // of a function could change its linkage.
Richard Smith50f4afc2013-05-12 23:17:59 +0000804 QualType TypeAsWritten = Function->getType();
805 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
806 TypeAsWritten = TSI->getType();
Richard Smith405e2db2017-09-20 07:22:00 +0000807 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
Richard Smith50f4afc2013-05-12 23:17:59 +0000808 return LinkageInfo::uniqueExternal();
809 }
John McCallf768aa72011-02-10 06:50:24 +0000810
John McCall5f46c482013-02-21 23:42:58 +0000811 // Consider LV from the template and the template arguments.
812 // We're at file scope, so we do not need to worry about nested
813 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000814 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000815 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000816 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000817 }
818
Douglas Gregorf73b2822009-11-25 22:24:25 +0000819 // - a named class (Clause 9), or an unnamed class defined in a
820 // typedef declaration in which the class has the typedef name
821 // for linkage purposes (7.1.3); or
822 // - a named enumeration (7.2), or an unnamed enumeration
823 // defined in a typedef declaration in which the enumeration
824 // has the typedef name for linkage purposes (7.1.3); or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000825 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000826 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000827 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000828 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000829
John McCall457a04e2010-10-22 21:05:15 +0000830 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000831 // linkage of the template and template arguments. We're at file
832 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000833 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000834 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000835 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000836
837 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000838 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000839 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000840 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000841 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000842 return LinkageInfo::none();
843 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000844
845 // - a template, unless it is a function template that has
846 // internal linkage (Clause 14);
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000847 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000848 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000849 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000850 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000851 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
852
Douglas Gregorf73b2822009-11-25 22:24:25 +0000853 // - a namespace (7.3), unless it is declared within an unnamed
854 // namespace.
Richard Smith1283e982017-07-07 20:04:28 +0000855 //
856 // We handled names in anonymous namespaces above.
857 } else if (isa<NamespaceDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000858 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000859
John McCall457a04e2010-10-22 21:05:15 +0000860 // By extension, we assign external linkage to Objective-C
861 // interfaces.
862 } else if (isa<ObjCInterfaceDecl>(D)) {
863 // fallout
864
Richard Smith97135cc2015-11-12 22:19:45 +0000865 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
866 // A typedef declaration has linkage if it gives a type a name for
867 // linkage purposes.
868 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
869 return LinkageInfo::none();
870
John McCall457a04e2010-10-22 21:05:15 +0000871 // Everything not covered here has no linkage.
872 } else {
John McCallc273f242010-10-30 11:50:40 +0000873 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000874 }
875
Richard Smithc445d5d2017-10-03 01:58:15 +0000876 // If we ended up with non-externally-visible linkage, visibility should
John McCall457a04e2010-10-22 21:05:15 +0000877 // always be default.
Richard Smithc445d5d2017-10-03 01:58:15 +0000878 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola4a5da442013-02-27 02:56:45 +0000879 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000880
John McCall457a04e2010-10-22 21:05:15 +0000881 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000882}
883
George Burgess IV99db3ea2017-08-09 04:02:49 +0000884LinkageInfo
885LinkageComputer::getLVForClassMember(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +0000886 LVComputationKind computation,
887 bool IgnoreVarTypeLinkage) {
John McCall457a04e2010-10-22 21:05:15 +0000888 // Only certain class members have linkage. Note that fields don't
889 // really have linkage, but it's convenient to say they do for the
890 // purposes of calculating linkage of pointer-to-data-member
891 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000892 //
893 // Templates also don't officially have linkage, but since we ignore
894 // the C++ standard and look at template arguments when determining
895 // linkage and visibility of a template specialization, we might hit
896 // a template template argument that way. If we do, we need to
897 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000898 if (!(isa<CXXMethodDecl>(D) ||
899 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000900 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000901 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000902 isa<TagDecl>(D) ||
903 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000904 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000905
John McCall07072662010-11-02 01:45:15 +0000906 LinkageInfo LV;
907
John McCall07072662010-11-02 01:45:15 +0000908 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000909 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000910 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000911 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000912 // If we're paying attention to global visibility, apply
913 // -finline-visibility-hidden if this is an inline method.
914 //
915 // Note that we do this before merging information about
916 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000917 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000918 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000919 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000920
921 // If this class member has an explicit visibility attribute, the only
922 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000923 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000924 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000925 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000926 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000927
John McCall5f46c482013-02-21 23:42:58 +0000928 LinkageInfo classLV =
929 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
Richard Smithcdb06f22017-09-23 04:02:17 +0000930 // The member has the same linkage as the class. If that's not externally
931 // visible, we don't need to compute anything about the linkage.
932 // FIXME: If we're only computing linkage, can we bail out here?
Rafael Espindolae6190db2013-05-28 02:22:10 +0000933 if (!isExternallyVisible(classLV.getLinkage()))
Richard Smithcdb06f22017-09-23 04:02:17 +0000934 return classLV;
Rafael Espindolae6190db2013-05-28 02:22:10 +0000935
936
John McCall5f46c482013-02-21 23:42:58 +0000937 // Otherwise, don't merge in classLV yet, because in certain cases
938 // we need to completely ignore the visibility from it.
939
940 // Specifically, if this decl exists and has an explicit attribute.
Craig Topper36250ad2014-05-12 05:36:57 +0000941 const NamedDecl *explicitSpecSuppressor = nullptr;
John McCall5f46c482013-02-21 23:42:58 +0000942
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000943 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc95d2c52017-09-22 04:25:05 +0000944 // Only look at the type-as-written. Otherwise, deducing the return type
945 // of a function could change its linkage.
946 QualType TypeAsWritten = MD->getType();
947 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
948 TypeAsWritten = TSI->getType();
949 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
950 return LinkageInfo::uniqueExternal();
951
John McCall457a04e2010-10-22 21:05:15 +0000952 // If this is a method template specialization, use the linkage for
953 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000954 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000955 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000956 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000957 if (spec->isExplicitSpecialization()) {
958 explicitSpecSuppressor = MD;
959 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
960 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
961 }
962 } else if (isExplicitMemberSpecialization(MD)) {
963 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000964 }
John McCall457a04e2010-10-22 21:05:15 +0000965
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000966 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
967 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000968 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000969 if (spec->isExplicitSpecialization()) {
970 explicitSpecSuppressor = spec;
971 } else {
972 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
973 if (isExplicitMemberSpecialization(temp)) {
974 explicitSpecSuppressor = temp->getTemplatedDecl();
975 }
976 }
977 } else if (isExplicitMemberSpecialization(RD)) {
978 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000979 }
980
John McCall37bb6c92010-10-29 22:22:43 +0000981 // Static data members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000982 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
983 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
Larisse Voufo5899e192014-07-02 23:08:34 +0000984 mergeTemplateLV(LV, spec, computation);
985
John McCall36cd5cc2010-10-30 09:18:49 +0000986 // Modify the variable's linkage by its type, but ignore the
987 // type's visibility unless it's a definition.
Richard Smithc95d2c52017-09-22 04:25:05 +0000988 if (!IgnoreVarTypeLinkage) {
989 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
990 // FIXME: If the type's linkage is not externally visible, we can
991 // give this static data member UniqueExternalLinkage.
992 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
993 LV.mergeVisibility(typeLV);
994 LV.mergeExternalVisibility(typeLV);
995 }
John McCall5f46c482013-02-21 23:42:58 +0000996
997 if (isExplicitMemberSpecialization(VD)) {
998 explicitSpecSuppressor = VD;
999 }
John McCalldf25c432013-02-16 00:17:33 +00001000
1001 // Template members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001002 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001003 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +00001004 (!LV.isVisibilityExplicit() &&
1005 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +00001006 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +00001007 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +00001008 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +00001009 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +00001010
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001011 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
John McCall5f46c482013-02-21 23:42:58 +00001012 if (isExplicitMemberSpecialization(redeclTemp)) {
1013 explicitSpecSuppressor = temp->getTemplatedDecl();
1014 }
1015 }
John McCall37bb6c92010-10-29 22:22:43 +00001016 }
1017
John McCall5f46c482013-02-21 23:42:58 +00001018 // We should never be looking for an attribute directly on a template.
1019 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1020
1021 // If this member is an explicit member specialization, and it has
1022 // an explicit attribute, ignore visibility from the parent.
1023 bool considerClassVisibility = true;
1024 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +00001025 // optimization: hasDVA() is true only with explicit visibility.
1026 LV.isVisibilityExplicit() &&
1027 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +00001028 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
1029 considerClassVisibility = false;
1030 }
1031
1032 // Finally, merge in information from the class.
1033 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +00001034 return LV;
John McCall8823c652010-08-13 08:35:10 +00001035}
1036
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001037void NamedDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00001038
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001039bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001040 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001041 return true;
John McCalld396b972011-02-08 19:01:05 +00001042
Richard Smithfbe7b462017-09-22 02:22:32 +00001043 Linkage L = LinkageComputer{}
1044 .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
1045 .getLinkage();
George Burgess IV99db3ea2017-08-09 04:02:49 +00001046 return L == getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +00001047}
1048
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001049ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1050 StringRef name = getName();
1051 if (name.empty()) return SFF_None;
1052
1053 if (name.front() == 'C')
1054 if (name == "CFStringCreateWithFormat" ||
1055 name == "CFStringCreateWithFormatAndArguments" ||
1056 name == "CFStringAppendFormat" ||
1057 name == "CFStringAppendFormatAndArguments")
1058 return SFF_CFString;
1059 return SFF_None;
1060}
1061
Rafael Espindola3ae00052013-05-13 00:12:11 +00001062Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +00001063 // We don't care about visibility here, so ask for the cheapest
1064 // possible visibility analysis.
Richard Smithfbe7b462017-09-22 02:22:32 +00001065 return LinkageComputer{}
1066 .getLVForDecl(this, LVComputationKind::forLinkageOnly())
1067 .getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001068}
1069
John McCallc273f242010-10-30 11:50:40 +00001070LinkageInfo NamedDecl::getLinkageAndVisibility() const {
George Burgess IV99db3ea2017-08-09 04:02:49 +00001071 return LinkageComputer{}.getDeclLinkageAndVisibility(this);
John McCall033caa52010-10-29 00:29:13 +00001072}
Ted Kremenek926d8602010-04-20 23:15:35 +00001073
Rafael Espindola9ad61122013-11-26 16:09:08 +00001074static Optional<Visibility>
1075getExplicitVisibilityAux(const NamedDecl *ND,
1076 NamedDecl::ExplicitVisibilityKind kind,
1077 bool IsMostRecent) {
1078 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1079
Rafael Espindola3a52c442013-02-26 19:33:14 +00001080 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001081 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001082 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001083
Rafael Espindola3a52c442013-02-26 19:33:14 +00001084 // If this is a member class of a specialization of a class template
1085 // and the corresponding decl has explicit visibility, use that.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001086 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +00001087 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1088 if (InstantiatedFrom)
1089 return getVisibilityOf(InstantiatedFrom, kind);
1090 }
1091
1092 // If there wasn't explicit visibility there, and this is a
1093 // specialization of a class template, check for visibility
1094 // on the pattern.
Steven Wu79cbd112018-04-19 15:46:43 +00001095 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
1096 // Walk all the template decl till this point to see if there are
1097 // explicit visibility attributes.
1098 const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();
1099 while (TD != nullptr) {
1100 auto Vis = getVisibilityOf(TD, kind);
1101 if (Vis != None)
1102 return Vis;
1103 TD = TD->getPreviousDecl();
1104 }
1105 return None;
1106 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001107
1108 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +00001109 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +00001110 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1111 if (MostRecent != ND)
1112 return getExplicitVisibilityAux(MostRecent, kind, true);
1113 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001114
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001115 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +00001116 if (Var->isStaticDataMember()) {
1117 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1118 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001119 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +00001120 }
1121
David Majnemer35b02bc2014-04-29 07:32:26 +00001122 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1123 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1124 kind);
1125
David Blaikie7a30dc52013-02-21 01:47:18 +00001126 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +00001127 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001128 // Also handle function template specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001129 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001130 // If the function is a specialization of a template with an
1131 // explicit visibility attribute, use that.
1132 if (FunctionTemplateSpecializationInfo *templateInfo
1133 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +00001134 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1135 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001136
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001137 // If the function is a member of a specialization of a class template
1138 // and the corresponding decl has explicit visibility, use that.
1139 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1140 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001141 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001142
David Blaikie7a30dc52013-02-21 01:47:18 +00001143 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001144 }
1145
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001146 // The visibility of a template is stored in the templated decl.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001147 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001148 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001149
David Blaikie7a30dc52013-02-21 01:47:18 +00001150 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001151}
1152
Rafael Espindola9ad61122013-11-26 16:09:08 +00001153Optional<Visibility>
1154NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1155 return getExplicitVisibilityAux(this, kind, false);
1156}
1157
George Burgess IV99db3ea2017-08-09 04:02:49 +00001158LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1159 Decl *ContextDecl,
1160 LVComputationKind computation) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001161 // This lambda has its linkage/visibility determined by its owner.
Richard Smithc95d2c52017-09-22 04:25:05 +00001162 const NamedDecl *Owner;
1163 if (!ContextDecl)
1164 Owner = dyn_cast<NamedDecl>(DC);
1165 else if (isa<ParmVarDecl>(ContextDecl))
1166 Owner =
1167 dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1168 else
1169 Owner = cast<NamedDecl>(ContextDecl);
1170
Richard Smithc95d2c52017-09-22 04:25:05 +00001171 if (!Owner)
Richard Smith7ff83042017-09-22 04:33:20 +00001172 return LinkageInfo::none();
Richard Smithc95d2c52017-09-22 04:25:05 +00001173
1174 // If the owner has a deduced type, we need to skip querying the linkage and
1175 // visibility of that type, because it might involve this closure type. The
1176 // only effect of this is that we might give a lambda VisibleNoLinkage rather
1177 // than NoLinkage when we don't strictly need to, which is benign.
1178 auto *VD = dyn_cast<VarDecl>(Owner);
Richard Smith7ff83042017-09-22 04:33:20 +00001179 LinkageInfo OwnerLV =
Richard Smithc95d2c52017-09-22 04:25:05 +00001180 VD && VD->getType()->getContainedDeducedType()
1181 ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1182 : getLVForDecl(Owner, computation);
1183
Richard Smith7ff83042017-09-22 04:33:20 +00001184 // A lambda never formally has linkage. But if the owner is externally
1185 // visible, then the lambda is too. We apply the same rules to blocks.
1186 if (!isExternallyVisible(OwnerLV.getLinkage()))
1187 return LinkageInfo::none();
1188 return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
1189 OwnerLV.isVisibilityExplicit());
Eli Friedman7e346a82013-07-01 20:22:57 +00001190}
1191
George Burgess IV99db3ea2017-08-09 04:02:49 +00001192LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1193 LVComputationKind computation) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001194 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001195 if (Function->isInAnonymousNamespace() &&
Richard Smith99f54792018-01-03 02:34:35 +00001196 !isFirstInExternCContext(Function))
Richard Smithdf963a32017-09-22 22:21:44 +00001197 return getInternalLinkageFor(Function);
John McCalldf25c432013-02-16 00:17:33 +00001198
1199 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001200 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +00001201 return getInternalLinkageFor(Function);
John McCalldf25c432013-02-16 00:17:33 +00001202
1203 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001204 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001205 if (Optional<Visibility> Vis =
1206 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001207 LV.mergeVisibility(*Vis, true);
1208 }
1209
1210 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1211 // merging storage classes and visibility attributes, so we don't have to
1212 // look at previous decls in here.
1213
1214 return LV;
1215 }
1216
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001217 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001218 if (Var->hasExternalStorage()) {
Richard Smith99f54792018-01-03 02:34:35 +00001219 if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
Richard Smithdf963a32017-09-22 22:21:44 +00001220 return getInternalLinkageFor(Var);
John McCalldf25c432013-02-16 00:17:33 +00001221
John McCalldf25c432013-02-16 00:17:33 +00001222 LinkageInfo LV;
1223 if (Var->getStorageClass() == SC_PrivateExtern)
1224 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001225 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001226 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001227 LV.mergeVisibility(*Vis, true);
1228 }
1229
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001230 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1231 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1232 if (PrevLV.getLinkage())
1233 LV.setLinkage(PrevLV.getLinkage());
1234 LV.mergeVisibility(PrevLV);
1235 }
1236
John McCalldf25c432013-02-16 00:17:33 +00001237 return LV;
1238 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001239
1240 if (!Var->isStaticLocal())
1241 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001242 }
1243
Rafael Espindolaa4184182013-06-17 20:04:51 +00001244 ASTContext &Context = D->getASTContext();
1245 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001246 return LinkageInfo::none();
1247
Eli Friedman7e346a82013-07-01 20:22:57 +00001248 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
Alexey Bataev0a47e652016-01-12 09:01:25 +00001249 if (!OuterD || OuterD->isInvalidDecl())
Rafael Espindola50df3a02013-05-25 17:16:20 +00001250 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001251
Eli Friedman7e346a82013-07-01 20:22:57 +00001252 LinkageInfo LV;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001253 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001254 if (!BD->getBlockManglingNumber())
1255 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001256
Eli Friedman7e346a82013-07-01 20:22:57 +00001257 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1258 BD->getBlockManglingContextDecl(), computation);
1259 } else {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001260 const auto *FD = cast<FunctionDecl>(OuterD);
Eli Friedman7e346a82013-07-01 20:22:57 +00001261 if (!FD->isInlined() &&
David Majnemer9963ade2014-12-16 04:52:14 +00001262 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
Eli Friedman7e346a82013-07-01 20:22:57 +00001263 return LinkageInfo::none();
1264
1265 LV = getLVForDecl(FD, computation);
1266 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001267 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001268 return LinkageInfo::none();
1269 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1270 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001271}
1272
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001273static inline const CXXRecordDecl*
1274getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1275 const CXXRecordDecl *Ret = Record;
1276 while (Record && Record->isLambda()) {
1277 Ret = Record;
1278 if (!Record->getParent()) break;
1279 // Get the Containing Class of this Lambda Class
1280 Record = dyn_cast_or_null<CXXRecordDecl>(
1281 Record->getParent()->getParent());
1282 }
1283 return Ret;
1284}
1285
George Burgess IV99db3ea2017-08-09 04:02:49 +00001286LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +00001287 LVComputationKind computation,
1288 bool IgnoreVarTypeLinkage) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001289 // Internal_linkage attribute overrides other considerations.
1290 if (D->hasAttr<InternalLinkageAttr>())
Richard Smith1283e982017-07-07 20:04:28 +00001291 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001292
Ted Kremenek926d8602010-04-20 23:15:35 +00001293 // Objective-C: treat all Objective-C declarations as having external
1294 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001295 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001296 default:
1297 break;
Richard Smith97135cc2015-11-12 22:19:45 +00001298
1299 // Per C++ [basic.link]p2, only the names of objects, references,
1300 // functions, types, templates, namespaces, and values ever have linkage.
1301 //
1302 // Note that the name of a typedef, namespace alias, using declaration,
1303 // and so on are not the name of the corresponding type, namespace, or
1304 // declaration, so they do *not* have linkage.
Richard Smith97135cc2015-11-12 22:19:45 +00001305 case Decl::ImplicitParam:
1306 case Decl::Label:
1307 case Decl::NamespaceAlias:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001308 case Decl::ParmVar:
Richard Smith97135cc2015-11-12 22:19:45 +00001309 case Decl::Using:
1310 case Decl::UsingShadow:
1311 case Decl::UsingDirective:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001312 return LinkageInfo::none();
Richard Smith97135cc2015-11-12 22:19:45 +00001313
Richard Smith26210db2015-11-13 03:52:13 +00001314 case Decl::EnumConstant:
1315 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
Bruno Cardoso Lopes057c82c2017-07-01 00:06:27 +00001316 if (D->getASTContext().getLangOpts().CPlusPlus)
1317 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1318 return LinkageInfo::visible_none();
Richard Smith26210db2015-11-13 03:52:13 +00001319
Richard Smith97135cc2015-11-12 22:19:45 +00001320 case Decl::Typedef:
1321 case Decl::TypeAlias:
1322 // A typedef declaration has linkage if it gives a type a name for
1323 // linkage purposes.
Vassil Vassilevb00ea082017-07-01 20:44:49 +00001324 if (!cast<TypedefNameDecl>(D)
Richard Smith97135cc2015-11-12 22:19:45 +00001325 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1326 return LinkageInfo::none();
1327 break;
1328
John McCall457a04e2010-10-22 21:05:15 +00001329 case Decl::TemplateTemplateParm: // count these as external
1330 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001331 case Decl::ObjCAtDefsField:
1332 case Decl::ObjCCategory:
1333 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001334 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001335 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001336 case Decl::ObjCMethod:
1337 case Decl::ObjCProperty:
1338 case Decl::ObjCPropertyImpl:
1339 case Decl::ObjCProtocol:
Richard Smith1283e982017-07-07 20:04:28 +00001340 return getExternalLinkageFor(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001341
1342 case Decl::CXXRecord: {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001343 const auto *Record = cast<CXXRecordDecl>(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001344 if (Record->isLambda()) {
1345 if (!Record->getLambdaManglingNumber()) {
1346 // This lambda has no mangling number, so it's internal.
Richard Smith1283e982017-07-07 20:04:28 +00001347 return getInternalLinkageFor(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001348 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001349
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001350 // This lambda has its linkage/visibility determined:
1351 // - either by the outermost lambda if that lambda has no mangling
1352 // number.
1353 // - or by the parent of the outer most lambda
1354 // This prevents infinite recursion in settings such as nested lambdas
1355 // used in NSDMI's, for e.g.
1356 // struct L {
1357 // int t{};
1358 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1359 // };
1360 const CXXRecordDecl *OuterMostLambda =
1361 getOutermostEnclosingLambda(Record);
1362 if (!OuterMostLambda->getLambdaManglingNumber())
Richard Smith1283e982017-07-07 20:04:28 +00001363 return getInternalLinkageFor(D);
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001364
1365 return getLVForClosure(
1366 OuterMostLambda->getDeclContext()->getRedeclContext(),
1367 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001368 }
1369
1370 break;
1371 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001372 }
1373
Douglas Gregorf73b2822009-11-25 22:24:25 +00001374 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001375 if (D->getDeclContext()->getRedeclContext()->isFileContext())
Richard Smithc95d2c52017-09-22 04:25:05 +00001376 return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001377
1378 // C++ [basic.link]p5:
1379 // In addition, a member function, static data member, a named
1380 // class or enumeration of class scope, or an unnamed class or
1381 // enumeration defined in a class-scope typedef declaration such
1382 // that the class or enumeration has the typedef name for linkage
1383 // purposes (7.1.3), has external linkage if the name of the class
1384 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001385 if (D->getDeclContext()->isRecord())
Richard Smithc95d2c52017-09-22 04:25:05 +00001386 return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001387
1388 // C++ [basic.link]p6:
1389 // The name of a function declared in block scope and the name of
1390 // an object declared by a block scope extern declaration have
1391 // linkage. If there is a visible declaration of an entity with
1392 // linkage having the same name and type, ignoring entities
1393 // declared outside the innermost enclosing namespace scope, the
1394 // block scope declaration declares that same entity and receives
1395 // the linkage of the previous declaration. If there is more than
1396 // one such matching entity, the program is ill-formed. Otherwise,
1397 // if no matching entity is found, the block scope entity receives
1398 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001399 if (D->getDeclContext()->isFunctionOrMethod())
1400 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001401
1402 // C++ [basic.link]p6:
1403 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001404 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001405}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001406
George Burgess IV99db3ea2017-08-09 04:02:49 +00001407/// getLVForDecl - Get the linkage and visibility for the given declaration.
1408LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1409 LVComputationKind computation) {
1410 // Internal_linkage attribute overrides other considerations.
1411 if (D->hasAttr<InternalLinkageAttr>())
1412 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001413
Richard Smithfbe7b462017-09-22 02:22:32 +00001414 if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
George Burgess IV99db3ea2017-08-09 04:02:49 +00001415 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001416
George Burgess IV35cb4f82017-08-09 04:12:17 +00001417 if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
1418 return *LI;
1419
George Burgess IV99db3ea2017-08-09 04:02:49 +00001420 LinkageInfo LV = computeLVForDecl(D, computation);
1421 if (D->hasCachedLinkage())
1422 assert(D->getCachedLinkage() == LV.getLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001423
George Burgess IV99db3ea2017-08-09 04:02:49 +00001424 D->setCachedLinkage(LV.getLinkage());
George Burgess IV35cb4f82017-08-09 04:12:17 +00001425 cache(D, computation, LV);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001426
1427#ifndef NDEBUG
George Burgess IV99db3ea2017-08-09 04:02:49 +00001428 // In C (because of gnu inline) and in c++ with microsoft extensions an
1429 // static can follow an extern, so we can have two decls with different
1430 // linkages.
1431 const LangOptions &Opts = D->getASTContext().getLangOpts();
1432 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1433 return LV;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001434
George Burgess IV99db3ea2017-08-09 04:02:49 +00001435 // We have just computed the linkage for this decl. By induction we know
1436 // that all other computed linkages match, check that the one we just
1437 // computed also does.
1438 NamedDecl *Old = nullptr;
1439 for (auto I : D->redecls()) {
1440 auto *T = cast<NamedDecl>(I);
1441 if (T == D)
1442 continue;
1443 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1444 Old = T;
1445 break;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001446 }
George Burgess IV99db3ea2017-08-09 04:02:49 +00001447 }
1448 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001449#endif
1450
George Burgess IV99db3ea2017-08-09 04:02:49 +00001451 return LV;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001452}
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001453
George Burgess IV99db3ea2017-08-09 04:02:49 +00001454LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
Richard Smithfbe7b462017-09-22 02:22:32 +00001455 return getLVForDecl(D,
1456 LVComputationKind(usesTypeVisibility(D)
1457 ? NamedDecl::VisibilityForType
1458 : NamedDecl::VisibilityForValue));
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001459}
1460
Richard Smithbecb92d2017-10-10 22:33:17 +00001461Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
Richard Smithdd8b5332017-09-04 05:37:53 +00001462 Module *M = getOwningModule();
1463 if (!M)
1464 return nullptr;
1465
1466 switch (M->Kind) {
1467 case Module::ModuleMapModule:
1468 // Module map modules have no special linkage semantics.
1469 return nullptr;
1470
1471 case Module::ModuleInterfaceUnit:
1472 return M;
1473
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001474 case Module::GlobalModuleFragment: {
Richard Smithdd8b5332017-09-04 05:37:53 +00001475 // External linkage declarations in the global module have no owning module
1476 // for linkage purposes. But internal linkage declarations in the global
1477 // module fragment of a particular module are owned by that module for
1478 // linkage purposes.
Richard Smithbecb92d2017-10-10 22:33:17 +00001479 if (IgnoreLinkage)
1480 return nullptr;
1481 bool InternalLinkage;
1482 if (auto *ND = dyn_cast<NamedDecl>(this))
1483 InternalLinkage = !ND->hasExternalFormalLinkage();
1484 else {
1485 auto *NSD = dyn_cast<NamespaceDecl>(this);
1486 InternalLinkage = (NSD && NSD->isAnonymousNamespace()) ||
1487 isInAnonymousNamespace();
1488 }
1489 return InternalLinkage ? M->Parent : nullptr;
Richard Smithdd8b5332017-09-04 05:37:53 +00001490 }
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001491 }
Richard Smithdd8b5332017-09-04 05:37:53 +00001492
1493 llvm_unreachable("unknown module kind");
1494}
1495
Richard Smith7873de02016-08-11 22:25:46 +00001496void NamedDecl::printName(raw_ostream &os) const {
1497 os << Name;
1498}
1499
Douglas Gregor2ada0482009-02-04 17:27:36 +00001500std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001501 std::string QualName;
1502 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001503 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001504 return OS.str();
1505}
1506
1507void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1508 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1509}
1510
1511void NamedDecl::printQualifiedName(raw_ostream &OS,
1512 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001513 const DeclContext *Ctx = getDeclContext();
1514
Argyrios Kyrtzidisa166a2b2017-03-07 09:26:07 +00001515 // For ObjC methods, look through categories and use the interface as context.
1516 if (auto *MD = dyn_cast<ObjCMethodDecl>(this))
1517 if (auto *ID = MD->getClassInterface())
1518 Ctx = ID;
1519
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001520 if (Ctx->isFunctionOrMethod()) {
1521 printName(OS);
1522 return;
1523 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001524
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001525 using ContextsTy = SmallVector<const DeclContext *, 8>;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001526 ContextsTy Contexts;
1527
Sam McCall34f9d3f2018-02-02 13:34:47 +00001528 // Collect named contexts.
1529 while (Ctx) {
1530 if (isa<NamedDecl>(Ctx))
1531 Contexts.push_back(Ctx);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001532 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001533 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001534
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001535 for (const DeclContext *DC : llvm::reverse(Contexts)) {
David Majnemerf7e36092016-06-23 00:15:04 +00001536 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001537 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001538 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Serge Pavlov03e672c2017-11-28 16:14:14 +00001539 printTemplateArgumentList(OS, TemplateArgs.asArray(), P);
David Majnemerf7e36092016-06-23 00:15:04 +00001540 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
Richard Smith46dd5bb2014-05-30 22:16:51 +00001541 if (P.SuppressUnwrittenScope &&
1542 (ND->isAnonymousNamespace() || ND->isInline()))
1543 continue;
Reid Kleckner60103382015-12-16 02:04:40 +00001544 if (ND->isAnonymousNamespace()) {
1545 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1546 : "(anonymous namespace)");
1547 }
Sam Weinig07d211e2009-12-24 23:15:03 +00001548 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001549 OS << *ND;
David Majnemerf7e36092016-06-23 00:15:04 +00001550 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001551 if (!RD->getIdentifier())
David Blaikieabe1a392014-04-02 05:58:29 +00001552 OS << "(anonymous " << RD->getKindName() << ')';
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001553 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001554 OS << *RD;
David Majnemerf7e36092016-06-23 00:15:04 +00001555 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
Craig Topper36250ad2014-05-12 05:36:57 +00001556 const FunctionProtoType *FT = nullptr;
Sam Weinigb999f682009-12-28 03:19:38 +00001557 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001558 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001559
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001560 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001561 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001562 unsigned NumParams = FD->getNumParams();
1563 for (unsigned i = 0; i < NumParams; ++i) {
1564 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001565 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001566 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001567 }
1568
1569 if (FT->isVariadic()) {
1570 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001571 OS << ", ";
1572 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001573 }
1574 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001575 OS << ')';
David Majnemerf7e36092016-06-23 00:15:04 +00001576 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
Alexander Kornienko4f355322015-11-09 16:45:17 +00001577 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1578 // enumerator is declared in the scope that immediately contains
1579 // the enum-specifier. Each scoped enumerator is declared in the
1580 // scope of the enumeration.
Paul Robinsonf1838482017-12-21 21:47:22 +00001581 // For the case of unscoped enumerator, do not include in the qualified
Paul Robinsond1c3dd82017-12-26 18:01:19 +00001582 // name any information about its enum enclosing scope, as its visibility
Paul Robinsonf1838482017-12-21 21:47:22 +00001583 // is global.
1584 if (ED->isScoped())
Alexander Kornienko4f355322015-11-09 16:45:17 +00001585 OS << *ED;
1586 else
1587 continue;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001588 } else {
David Majnemerf7e36092016-06-23 00:15:04 +00001589 OS << *cast<NamedDecl>(DC);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001590 }
1591 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001592 }
1593
Richard Smith7873de02016-08-11 22:25:46 +00001594 if (getDeclName() || isa<DecompositionDecl>(this))
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001595 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001596 else
David Blaikieabe1a392014-04-02 05:58:29 +00001597 OS << "(anonymous)";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001598}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001599
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001600void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1601 const PrintingPolicy &Policy,
1602 bool Qualified) const {
1603 if (Qualified)
1604 printQualifiedName(OS, Policy);
1605 else
1606 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001607}
1608
Richard Smithe8292b12015-02-10 03:28:10 +00001609template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1610 return true;
1611}
1612static bool isRedeclarableImpl(...) { return false; }
1613static bool isRedeclarable(Decl::Kind K) {
1614 switch (K) {
1615#define DECL(Type, Base) \
1616 case Decl::Type: \
1617 return isRedeclarableImpl((Type##Decl *)nullptr);
1618#define ABSTRACT_DECL(DECL)
1619#include "clang/AST/DeclNodes.inc"
1620 }
1621 llvm_unreachable("unknown decl kind");
1622}
1623
1624bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001625 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1626
Richard Smithfe620d22015-03-05 23:24:12 +00001627 // Never replace one imported declaration with another; we need both results
1628 // when re-exporting.
1629 if (OldD->isFromASTFile() && isFromASTFile())
1630 return false;
1631
Richard Smith5cd86f82015-11-03 03:13:11 +00001632 // A kind mismatch implies that the declaration is not replaced.
1633 if (OldD->getKind() != getKind())
Richard Smithe8292b12015-02-10 03:28:10 +00001634 return false;
1635
Richard Smith5cd86f82015-11-03 03:13:11 +00001636 // For method declarations, we never replace. (Why?)
1637 if (isa<ObjCMethodDecl>(this))
1638 return false;
1639
1640 // For parameters, pick the newer one. This is either an error or (in
1641 // Objective-C) permitted as an extension.
1642 if (isa<ParmVarDecl>(this))
1643 return true;
1644
Richard Smithe8292b12015-02-10 03:28:10 +00001645 // Inline namespaces can give us two declarations with the same
1646 // name and kind in the same scope but different contexts; we should
1647 // keep both declarations in this case.
1648 if (!this->getDeclContext()->getRedeclContext()->Equals(
1649 OldD->getDeclContext()->getRedeclContext()))
1650 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001651
Richard Smith5cd86f82015-11-03 03:13:11 +00001652 // Using declarations can be replaced if they import the same name from the
1653 // same context.
Richard Smithe8292b12015-02-10 03:28:10 +00001654 if (auto *UD = dyn_cast<UsingDecl>(this)) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001655 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001656 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001657 Context.getCanonicalNestedNameSpecifier(
Richard Smithe8292b12015-02-10 03:28:10 +00001658 cast<UsingDecl>(OldD)->getQualifier());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001659 }
Richard Smithe8292b12015-02-10 03:28:10 +00001660 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001661 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001662 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001663 Context.getCanonicalNestedNameSpecifier(
1664 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1665 }
1666
Richard Smith5cd86f82015-11-03 03:13:11 +00001667 if (isRedeclarable(getKind())) {
1668 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1669 return false;
1670
1671 if (IsKnownNewer)
1672 return true;
1673
Richard Smithe8292b12015-02-10 03:28:10 +00001674 // Check whether this is actually newer than OldD. We want to keep the
1675 // newer declaration. This loop will usually only iterate once, because
1676 // OldD is usually the previous declaration.
1677 for (auto D : redecls()) {
1678 if (D == OldD)
1679 break;
1680
1681 // If we reach the canonical declaration, then OldD is not actually older
1682 // than this one.
1683 //
1684 // FIXME: In this case, we should not add this decl to the lookup table.
1685 if (D->isCanonicalDecl())
1686 return false;
1687 }
Richard Smith5cd86f82015-11-03 03:13:11 +00001688
1689 // It's a newer declaration of the same kind of declaration in the same
1690 // scope: we want this decl instead of the existing one.
1691 return true;
Richard Smithe8292b12015-02-10 03:28:10 +00001692 }
1693
Richard Smith5cd86f82015-11-03 03:13:11 +00001694 // In all other cases, we need to keep both declarations in case they have
1695 // different visibility. Any attempt to use the name will result in an
1696 // ambiguity if more than one is visible.
1697 return false;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001698}
1699
Douglas Gregoreddf4332009-02-24 20:03:32 +00001700bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001701 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001702}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001703
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001704NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001705 NamedDecl *ND = this;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001706 while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001707 ND = UD->getTargetDecl();
1708
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001709 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001710 return AD->getClassInterface();
1711
Richard Smithf2005d32015-12-29 23:34:32 +00001712 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1713 return AD->getNamespace();
1714
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001715 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001716}
1717
John McCalla8ae2222010-04-06 21:38:20 +00001718bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001719 if (!isCXXClassMember())
1720 return false;
1721
John McCalla8ae2222010-04-06 21:38:20 +00001722 const NamedDecl *D = this;
1723 if (isa<UsingShadowDecl>(D))
1724 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1725
John McCall5e77d762013-04-16 07:28:30 +00001726 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001727 return true;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001728 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
Alp Tokera2794f92014-01-22 07:29:52 +00001729 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001730 return false;
1731}
1732
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001733//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001734// DeclaratorDecl Implementation
1735//===----------------------------------------------------------------------===//
1736
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001737template <typename DeclT>
1738static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1739 if (decl->getNumTemplateParameterLists() > 0)
1740 return decl->getTemplateParameterList(0)->getTemplateLoc();
1741 else
1742 return decl->getInnerLocStart();
1743}
1744
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001745SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001746 TypeSourceInfo *TSI = getTypeSourceInfo();
1747 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001748 return SourceLocation();
1749}
1750
Douglas Gregor14454802011-02-25 02:25:35 +00001751void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1752 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001753 // Make sure the extended decl info is allocated.
1754 if (!hasExtInfo()) {
1755 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001756 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
John McCall3e11ebe2010-03-15 10:12:16 +00001757 // Allocate external info struct.
1758 DeclInfo = new (getASTContext()) ExtInfo;
1759 // Restore savedTInfo into (extended) decl info.
1760 getExtInfo()->TInfo = savedTInfo;
1761 }
1762 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001763 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001764 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001765 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001766 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001767 if (getExtInfo()->NumTemplParamLists == 0) {
1768 // Save type source info pointer.
1769 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1770 // Deallocate the extended decl info.
1771 getASTContext().Deallocate(getExtInfo());
1772 // Restore savedTInfo into (non-extended) decl info.
1773 DeclInfo = savedTInfo;
1774 }
1775 else
1776 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001777 }
1778 }
1779}
1780
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001781void DeclaratorDecl::setTemplateParameterListsInfo(
1782 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1783 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00001784 // Make sure the extended decl info is allocated.
1785 if (!hasExtInfo()) {
1786 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001787 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
Abramo Bagnara60804e12011-03-18 15:16:37 +00001788 // Allocate external info struct.
1789 DeclInfo = new (getASTContext()) ExtInfo;
1790 // Restore savedTInfo into (extended) decl info.
1791 getExtInfo()->TInfo = savedTInfo;
1792 }
1793 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001794 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00001795}
1796
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001797SourceLocation DeclaratorDecl::getOuterLocStart() const {
1798 return getTemplateOrInnerLocStart(this);
1799}
1800
Abramo Bagnaraea947882011-03-08 16:41:52 +00001801// Helper function: returns true if QT is or contains a type
1802// having a postfix component.
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001803static bool typeIsPostfix(QualType QT) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00001804 while (true) {
1805 const Type* T = QT.getTypePtr();
1806 switch (T->getTypeClass()) {
1807 default:
1808 return false;
1809 case Type::Pointer:
1810 QT = cast<PointerType>(T)->getPointeeType();
1811 break;
1812 case Type::BlockPointer:
1813 QT = cast<BlockPointerType>(T)->getPointeeType();
1814 break;
1815 case Type::MemberPointer:
1816 QT = cast<MemberPointerType>(T)->getPointeeType();
1817 break;
1818 case Type::LValueReference:
1819 case Type::RValueReference:
1820 QT = cast<ReferenceType>(T)->getPointeeType();
1821 break;
1822 case Type::PackExpansion:
1823 QT = cast<PackExpansionType>(T)->getPattern();
1824 break;
1825 case Type::Paren:
1826 case Type::ConstantArray:
1827 case Type::DependentSizedArray:
1828 case Type::IncompleteArray:
1829 case Type::VariableArray:
1830 case Type::FunctionProto:
1831 case Type::FunctionNoProto:
1832 return true;
1833 }
1834 }
1835}
1836
Abramo Bagnaraea947882011-03-08 16:41:52 +00001837SourceRange DeclaratorDecl::getSourceRange() const {
1838 SourceLocation RangeEnd = getLocation();
1839 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001840 // If the declaration has no name or the type extends past the name take the
1841 // end location of the type.
1842 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001843 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1844 }
1845 return SourceRange(getOuterLocStart(), RangeEnd);
1846}
1847
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001848void QualifierInfo::setTemplateParameterListsInfo(
1849 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001850 // Free previous template parameters (if any).
1851 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001852 Context.Deallocate(TemplParamLists);
Craig Topper36250ad2014-05-12 05:36:57 +00001853 TemplParamLists = nullptr;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001854 NumTemplParamLists = 0;
1855 }
1856 // Set info on matched template parameter lists (if any).
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001857 if (!TPLists.empty()) {
1858 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1859 NumTemplParamLists = TPLists.size();
1860 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001861 }
1862}
1863
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001864//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001865// VarDecl Implementation
1866//===----------------------------------------------------------------------===//
1867
Sebastian Redl833ef452010-01-26 22:01:41 +00001868const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1869 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001870 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001871 case SC_Auto: return "auto";
1872 case SC_Extern: return "extern";
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001873 case SC_PrivateExtern: return "__private_extern__";
1874 case SC_Register: return "register";
1875 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001876 }
1877
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001878 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001879}
1880
Richard Smith053f6c62014-05-16 23:01:30 +00001881VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1882 SourceLocation StartLoc, SourceLocation IdLoc,
1883 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1884 StorageClass SC)
1885 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001886 redeclarable_base(C) {
Benjamin Kramera939c232014-03-15 18:54:13 +00001887 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1888 "VarDeclBitfields too large!");
1889 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1890 "ParmVarDeclBitfields too large!");
David Majnemerfa7bc782015-05-19 00:57:16 +00001891 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1892 "NonParmVarDeclBitfields too large!");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001893 AllBits = 0;
1894 VarDeclBits.SClass = SC;
1895 // Everything else is implicitly initialized to false.
1896}
1897
Abramo Bagnaradff19302011-03-08 08:55:46 +00001898VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1899 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001900 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001901 StorageClass S) {
Richard Smith053f6c62014-05-16 23:01:30 +00001902 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001903}
1904
Douglas Gregor72172e92012-01-05 21:55:30 +00001905VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00001906 return new (C, ID)
1907 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1908 QualType(), nullptr, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001909}
1910
Douglas Gregorbf62d642010-12-06 18:36:25 +00001911void VarDecl::setStorageClass(StorageClass SC) {
1912 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001913 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001914}
1915
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001916VarDecl::TLSKind VarDecl::getTLSKind() const {
1917 switch (VarDeclBits.TSCSpec) {
1918 case TSCS_unspecified:
Samuel Antaof8b50122015-07-13 22:54:53 +00001919 if (!hasAttr<ThreadAttr>() &&
1920 !(getASTContext().getLangOpts().OpenMPUseTLS &&
1921 getASTContext().getTargetInfo().isTLSSupported() &&
1922 hasAttr<OMPThreadPrivateDeclAttr>()))
David Majnemer1b5baff2015-05-14 05:19:23 +00001923 return TLS_None;
Samuel Antaof8b50122015-07-13 22:54:53 +00001924 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1925 LangOptions::MSVC2015)) ||
1926 hasAttr<OMPThreadPrivateDeclAttr>())
David Majnemer1b5baff2015-05-14 05:19:23 +00001927 ? TLS_Dynamic
1928 : TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001929 case TSCS___thread: // Fall through.
1930 case TSCS__Thread_local:
Samuel Antaof8b50122015-07-13 22:54:53 +00001931 return TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001932 case TSCS_thread_local:
1933 return TLS_Dynamic;
1934 }
1935 llvm_unreachable("Unknown thread storage class specifier!");
1936}
1937
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001938SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001939 if (const Expr *Init = getInit()) {
1940 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001941 // If Init is implicit, ignore its source range and fallback on
1942 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1943 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001944 return SourceRange(getOuterLocStart(), InitEnd);
1945 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001946 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001947}
1948
Rafael Espindola88510672013-01-04 21:18:45 +00001949template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001950static LanguageLinkage getDeclLanguageLinkage(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001951 // C++ [dcl.link]p1: All function types, function names with external linkage,
1952 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001953 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001954 return NoLanguageLinkage;
1955
1956 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001957 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001958 ASTContext &Context = D.getASTContext();
1959 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001960 return CLanguageLinkage;
1961
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001962 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1963 // language linkage of the names of class members and the function type of
1964 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001965 const DeclContext *DC = D.getDeclContext();
1966 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001967 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001968
1969 // If the first decl is in an extern "C" context, any other redeclaration
1970 // will have C language linkage. If the first one is not in an extern "C"
1971 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00001972 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00001973 return CLanguageLinkage;
1974 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001975}
1976
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001977template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001978static bool isDeclExternC(const T &D) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001979 // Since the context is ignored for class members, they can only have C++
1980 // language linkage or no language linkage.
1981 const DeclContext *DC = D.getDeclContext();
1982 if (DC->isRecord()) {
1983 assert(D.getASTContext().getLangOpts().CPlusPlus);
1984 return false;
1985 }
1986
1987 return D.getLanguageLinkage() == CLanguageLinkage;
1988}
1989
Rafael Espindolaf4187652013-02-14 01:18:37 +00001990LanguageLinkage VarDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00001991 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001992}
1993
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001994bool VarDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00001995 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001996}
1997
Rafael Espindola593537a2013-05-05 20:15:21 +00001998bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001999 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002000}
2001
2002bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002003 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002004}
2005
Rafael Espindola8db352d2013-10-17 15:37:26 +00002006VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002007
Nico Weber7f5015a2015-04-15 21:53:00 +00002008VarDecl::DefinitionKind
2009VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
Richard Smitha22d9a52017-12-02 00:55:48 +00002010 if (isThisDeclarationADemotedDefinition())
2011 return DeclarationOnly;
2012
Sebastian Redl35351a92010-01-31 22:27:38 +00002013 // C++ [basic.def]p2:
2014 // A declaration is a definition unless [...] it contains the 'extern'
2015 // specifier or a linkage-specification and neither an initializer [...],
Richard Smith62f19e72016-06-25 00:15:56 +00002016 // it declares a non-inline static data member in a class declaration [...],
2017 // it declares a static data member outside a class definition and the variable
2018 // was defined within the class with the constexpr specifier [...],
Richard Smith8809a0c2013-09-27 20:14:12 +00002019 // C++1y [temp.expl.spec]p15:
2020 // An explicit specialization of a static data member or an explicit
2021 // specialization of a static data member template is a definition if the
2022 // declaration includes an initializer; otherwise, it is a declaration.
2023 //
2024 // FIXME: How do you declare (but not define) a partial specialization of
2025 // a static data member template outside the containing class?
Sebastian Redl35351a92010-01-31 22:27:38 +00002026 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002027 if (isOutOfLine() &&
Richard Smith62f19e72016-06-25 00:15:56 +00002028 !(getCanonicalDecl()->isInline() &&
2029 getCanonicalDecl()->isConstexpr()) &&
Richard Smith8809a0c2013-09-27 20:14:12 +00002030 (hasInit() ||
2031 // If the first declaration is out-of-line, this may be an
2032 // instantiation of an out-of-line partial specialization of a variable
2033 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00002034 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00002035 ? getTemplateSpecializationKind() == TSK_Undeclared
2036 : getTemplateSpecializationKind() !=
2037 TSK_ExplicitSpecialization) ||
2038 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00002039 return Definition;
Richard Smith62f19e72016-06-25 00:15:56 +00002040 else if (!isOutOfLine() && isInline())
2041 return Definition;
Sebastian Redl35351a92010-01-31 22:27:38 +00002042 else
2043 return DeclarationOnly;
2044 }
2045 // C99 6.7p5:
2046 // A definition of an identifier is a declaration for that identifier that
2047 // [...] causes storage to be reserved for that object.
2048 // Note: that applies for all non-file-scope objects.
2049 // C99 6.9.2p1:
2050 // If the declaration of an identifier for an object has file scope and an
2051 // initializer, the declaration is an external definition for the identifier
2052 if (hasInit())
2053 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00002054
Dmitry Polukhin85eda122016-04-11 07:48:59 +00002055 if (hasDefiningAttr())
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002056 return Definition;
2057
David Majnemerdd0bed12015-05-14 05:19:20 +00002058 if (const auto *SAA = getAttr<SelectAnyAttr>())
2059 if (!SAA->isInherited())
2060 return Definition;
2061
Richard Smith8809a0c2013-09-27 20:14:12 +00002062 // A variable template specialization (other than a static data member
2063 // template or an explicit specialization) is a declaration until we
2064 // instantiate its initializer.
Richard Smith435e6472017-12-02 02:48:42 +00002065 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2066 if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2067 !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2068 !VTSD->IsCompleteDefinition)
2069 return DeclarationOnly;
2070 }
Richard Smith8809a0c2013-09-27 20:14:12 +00002071
Nico Weber608e7682015-04-15 23:04:24 +00002072 if (hasExternalStorage())
Sebastian Redl35351a92010-01-31 22:27:38 +00002073 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00002074
Rafael Espindolabff59562013-04-25 12:11:36 +00002075 // [dcl.link] p7:
2076 // A declaration directly contained in a linkage-specification is treated
2077 // as if it contains the extern specifier for the purpose of determining
2078 // the linkage of the declared name and whether it is a definition.
Nico Weber608e7682015-04-15 23:04:24 +00002079 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00002080 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00002081
Sebastian Redl35351a92010-01-31 22:27:38 +00002082 // C99 6.9.2p2:
2083 // A declaration of an object that has file scope without an initializer,
2084 // and without a storage class specifier or the scs 'static', constitutes
2085 // a tentative definition.
2086 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002087 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00002088 return TentativeDefinition;
2089
2090 // What's left is (in C, block-scope) declarations without initializers or
2091 // external storage. These are definitions.
2092 return Definition;
2093}
2094
Sebastian Redl35351a92010-01-31 22:27:38 +00002095VarDecl *VarDecl::getActingDefinition() {
2096 DefinitionKind Kind = isThisDeclarationADefinition();
2097 if (Kind != TentativeDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00002098 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002099
Craig Topper36250ad2014-05-12 05:36:57 +00002100 VarDecl *LastTentative = nullptr;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002101 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002102 for (auto I : First->redecls()) {
2103 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00002104 if (Kind == Definition)
Craig Topper36250ad2014-05-12 05:36:57 +00002105 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002106 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00002107 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00002108 }
2109 return LastTentative;
2110}
2111
Daniel Dunbar9d355812012-03-09 01:51:51 +00002112VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002113 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002114 for (auto I : First->redecls()) {
2115 if (I->isThisDeclarationADefinition(C) == Definition)
2116 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002117 }
Craig Topper36250ad2014-05-12 05:36:57 +00002118 return nullptr;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002119}
2120
Daniel Dunbar9d355812012-03-09 01:51:51 +00002121VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00002122 DefinitionKind Kind = DeclarationOnly;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002123
Rafael Espindola8db352d2013-10-17 15:37:26 +00002124 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002125 for (auto I : First->redecls()) {
2126 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00002127 if (Kind == Definition)
2128 break;
2129 }
John McCall37bb6c92010-10-29 22:22:43 +00002130
2131 return Kind;
2132}
2133
Sebastian Redl5ca79842010-02-01 20:16:42 +00002134const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002135 for (auto I : redecls()) {
2136 if (auto Expr = I->getInit()) {
2137 D = I;
2138 return Expr;
2139 }
Sebastian Redl833ef452010-01-26 22:01:41 +00002140 }
Craig Topper36250ad2014-05-12 05:36:57 +00002141 return nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002142}
2143
Chandler Carruth813faed2015-12-30 02:51:00 +00002144bool VarDecl::hasInit() const {
2145 if (auto *P = dyn_cast<ParmVarDecl>(this))
2146 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2147 return false;
2148
2149 return !Init.isNull();
2150}
2151
2152Expr *VarDecl::getInit() {
2153 if (!hasInit())
2154 return nullptr;
2155
2156 if (auto *S = Init.dyn_cast<Stmt *>())
2157 return cast<Expr>(S);
2158
2159 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2160}
2161
2162Stmt **VarDecl::getInitAddress() {
2163 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2164 return &ES->Value;
2165
2166 return Init.getAddrOfPtr1();
2167}
2168
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002169bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002170 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002171 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00002172
2173 if (!isStaticDataMember())
2174 return false;
2175
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002176 // If this static data member was instantiated from a static data member of
2177 // a class template, check whether that static data member was defined
2178 // out-of-line.
2179 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2180 return VD->isOutOfLine();
2181
2182 return false;
2183}
2184
Douglas Gregord5058122010-02-11 01:19:42 +00002185void VarDecl::setInit(Expr *I) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002186 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
Sebastian Redl833ef452010-01-26 22:01:41 +00002187 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00002188 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00002189 }
2190
2191 Init = I;
2192}
2193
Daniel Dunbar9d355812012-03-09 01:51:51 +00002194bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002195 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00002196
Richard Smith35ecb362012-03-02 04:14:40 +00002197 if (!Lang.CPlusPlus)
2198 return false;
2199
2200 // In C++11, any variable of reference type can be used in a constant
2201 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002202 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00002203 return true;
2204
2205 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00002206 // not require the variable to be non-volatile, but we consider this to be a
2207 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00002208 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00002209 return false;
2210
2211 // In C++, const, non-volatile variables of integral or enumeration types
2212 // can be used in constant expressions.
2213 if (getType()->isIntegralOrEnumerationType())
2214 return true;
2215
Richard Smith35ecb362012-03-02 04:14:40 +00002216 // Additionally, in C++11, non-volatile constexpr variables can be used in
2217 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002218 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00002219}
2220
Richard Smithd0b4dd62011-12-19 06:19:21 +00002221/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2222/// form, which contains extra information on the evaluated value of the
2223/// initializer.
2224EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002225 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002226 if (!Eval) {
Manuel Klimeka7328992013-06-03 13:51:33 +00002227 // Note: EvaluatedStmt contains an APValue, which usually holds
2228 // resources not allocated from the ASTContext. We need to do some
2229 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2230 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002231 Eval = new (getASTContext()) EvaluatedStmt;
Chandler Carruth813faed2015-12-30 02:51:00 +00002232 Eval->Value = Init.get<Stmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002233 Init = Eval;
2234 }
2235 return Eval;
2236}
2237
Richard Smithdafff942012-01-14 04:30:29 +00002238APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002239 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00002240 return evaluateValue(Notes);
2241}
2242
2243APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002244 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002245 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2246
2247 // We only produce notes indicating why an initializer is non-constant the
2248 // first time it is evaluated. FIXME: The notes won't always be emitted the
2249 // first time we try evaluation, so might not be produced at all.
2250 if (Eval->WasEvaluated)
Craig Topper36250ad2014-05-12 05:36:57 +00002251 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002252
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002253 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002254 assert(!Init->isValueDependent());
2255
2256 if (Eval->IsEvaluating) {
2257 // FIXME: Produce a diagnostic for self-initialization.
2258 Eval->CheckedICE = true;
2259 Eval->IsICE = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002260 return nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002261 }
2262
2263 Eval->IsEvaluating = true;
2264
2265 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2266 this, Notes);
2267
Manuel Klimeka7328992013-06-03 13:51:33 +00002268 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2269 // or that it's empty (so that there's nothing to clean up) if evaluation
2270 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002271 if (!Result)
2272 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00002273 else if (Eval->Evaluated.needsCleanup())
George Burgess IVb61bfbd2017-02-14 05:37:36 +00002274 getASTContext().addDestruction(&Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002275
2276 Eval->IsEvaluating = false;
2277 Eval->WasEvaluated = true;
2278
2279 // In C++11, we have determined whether the initializer was a constant
2280 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002281 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002282 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00002283 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002284 }
2285
Craig Topper36250ad2014-05-12 05:36:57 +00002286 return Result ? &Eval->Evaluated : nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002287}
2288
Chandler Carruth813faed2015-12-30 02:51:00 +00002289APValue *VarDecl::getEvaluatedValue() const {
2290 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2291 if (Eval->WasEvaluated)
2292 return &Eval->Evaluated;
2293
2294 return nullptr;
2295}
2296
2297bool VarDecl::isInitKnownICE() const {
2298 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2299 return Eval->CheckedICE;
2300
2301 return false;
2302}
2303
2304bool VarDecl::isInitICE() const {
2305 assert(isInitKnownICE() &&
2306 "Check whether we already know that the initializer is an ICE");
2307 return Init.get<EvaluatedStmt *>()->IsICE;
2308}
2309
Richard Smithd0b4dd62011-12-19 06:19:21 +00002310bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00002311 // Initializers of weak variables are never ICEs.
2312 if (isWeak())
2313 return false;
2314
Richard Smithd0b4dd62011-12-19 06:19:21 +00002315 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2316 if (Eval->CheckedICE)
2317 // We have already checked whether this subexpression is an
2318 // integral constant expression.
2319 return Eval->IsICE;
2320
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002321 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002322 assert(!Init->isValueDependent());
2323
2324 // In C++11, evaluate the initializer to check whether it's a constant
2325 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002326 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002327 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002328 evaluateValue(Notes);
2329 return Eval->IsICE;
2330 }
2331
2332 // It's an ICE whether or not the definition we found is
2333 // out-of-line. See DR 721 and the discussion in Clang PR
2334 // 6206 for details.
2335
2336 if (Eval->CheckingICE)
2337 return false;
2338 Eval->CheckingICE = true;
2339
2340 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2341 Eval->CheckingICE = false;
2342 Eval->CheckedICE = true;
2343 return Eval->IsICE;
2344}
2345
Richard Smith2195ec92017-04-21 01:15:13 +00002346template<typename DeclT>
2347static DeclT *getDefinitionOrSelf(DeclT *D) {
2348 assert(D);
2349 if (auto *Def = D->getDefinition())
2350 return Def;
2351 return D;
2352}
2353
Richard Smithedbc6e92016-10-14 21:41:24 +00002354VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2355 // If it's a variable template specialization, find the template or partial
2356 // specialization from which it was instantiated.
2357 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2358 auto From = VDTemplSpec->getInstantiatedFrom();
2359 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2360 while (auto *NewVTD = VTD->getInstantiatedFromMemberTemplate()) {
2361 if (NewVTD->isMemberSpecialization())
2362 break;
2363 VTD = NewVTD;
2364 }
Richard Smith2195ec92017-04-21 01:15:13 +00002365 return getDefinitionOrSelf(VTD->getTemplatedDecl());
Richard Smithedbc6e92016-10-14 21:41:24 +00002366 }
2367 if (auto *VTPSD =
2368 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2369 while (auto *NewVTPSD = VTPSD->getInstantiatedFromMember()) {
2370 if (NewVTPSD->isMemberSpecialization())
2371 break;
2372 VTPSD = NewVTPSD;
2373 }
Richard Smith2195ec92017-04-21 01:15:13 +00002374 return getDefinitionOrSelf<VarDecl>(VTPSD);
Richard Smithedbc6e92016-10-14 21:41:24 +00002375 }
2376 }
2377
2378 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
2379 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2380 VarDecl *VD = getInstantiatedFromStaticDataMember();
2381 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2382 VD = NewVD;
Richard Smith2195ec92017-04-21 01:15:13 +00002383 return getDefinitionOrSelf(VD);
Richard Smithedbc6e92016-10-14 21:41:24 +00002384 }
2385 }
2386
2387 if (VarTemplateDecl *VarTemplate = getDescribedVarTemplate()) {
Richard Smithedbc6e92016-10-14 21:41:24 +00002388 while (VarTemplate->getInstantiatedFromMemberTemplate()) {
2389 if (VarTemplate->isMemberSpecialization())
2390 break;
2391 VarTemplate = VarTemplate->getInstantiatedFromMemberTemplate();
2392 }
2393
Richard Smith2195ec92017-04-21 01:15:13 +00002394 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
Richard Smithedbc6e92016-10-14 21:41:24 +00002395 }
2396 return nullptr;
2397}
2398
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002399VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002400 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002401 return cast<VarDecl>(MSI->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002402
2403 return nullptr;
Douglas Gregor86d142a2009-10-08 07:24:58 +00002404}
2405
Douglas Gregor3c74d412009-10-14 20:14:33 +00002406TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002407 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002408 return Spec->getSpecializationKind();
2409
Sebastian Redl35351a92010-01-31 22:27:38 +00002410 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002411 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002412
Douglas Gregor86d142a2009-10-08 07:24:58 +00002413 return TSK_Undeclared;
2414}
2415
Richard Smith8809a0c2013-09-27 20:14:12 +00002416SourceLocation VarDecl::getPointOfInstantiation() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002417 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Richard Smith8809a0c2013-09-27 20:14:12 +00002418 return Spec->getPointOfInstantiation();
2419
2420 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2421 return MSI->getPointOfInstantiation();
2422
2423 return SourceLocation();
2424}
2425
Larisse Voufo39a1e502013-08-06 01:03:05 +00002426VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2427 return getASTContext().getTemplateOrSpecializationInfo(this)
2428 .dyn_cast<VarTemplateDecl *>();
2429}
2430
2431void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2432 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2433}
2434
Justin Lebar5489f852018-05-17 16:15:07 +00002435bool VarDecl::isKnownToBeDefined() const {
2436 const auto &LangOpts = getASTContext().getLangOpts();
2437 // In CUDA mode without relocatable device code, variables of form 'extern
2438 // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2439 // memory pool. These are never undefined variables, even if they appear
2440 // inside of an anon namespace or static function.
2441 //
2442 // With CUDA relocatable device code enabled, these variables don't get
2443 // special handling; they're treated like regular extern variables.
2444 if (LangOpts.CUDA && !LangOpts.CUDARelocatableDeviceCode &&
2445 hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
2446 isa<IncompleteArrayType>(getType()))
2447 return true;
2448
2449 return hasDefinition();
2450}
2451
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002452MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002453 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002454 // FIXME: Remove ?
2455 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2456 return getASTContext().getTemplateOrSpecializationInfo(this)
2457 .dyn_cast<MemberSpecializationInfo *>();
Craig Topper36250ad2014-05-12 05:36:57 +00002458 return nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002459}
2460
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002461void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2462 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002463 assert((isa<VarTemplateSpecializationDecl>(this) ||
2464 getMemberSpecializationInfo()) &&
2465 "not a variable or static data member template specialization");
2466
Larisse Voufo39a1e502013-08-06 01:03:05 +00002467 if (VarTemplateSpecializationDecl *Spec =
2468 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2469 Spec->setSpecializationKind(TSK);
2470 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00002471 Spec->getPointOfInstantiation().isInvalid()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002472 Spec->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00002473 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2474 L->InstantiationRequested(this);
2475 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002476 }
2477
2478 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2479 MSI->setTemplateSpecializationKind(TSK);
2480 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00002481 MSI->getPointOfInstantiation().isInvalid()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002482 MSI->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00002483 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2484 L->InstantiationRequested(this);
2485 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002486 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002487}
2488
2489void
2490VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2491 TemplateSpecializationKind TSK) {
2492 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2493 "Previous template or instantiation?");
2494 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002495}
2496
Sebastian Redl833ef452010-01-26 22:01:41 +00002497//===----------------------------------------------------------------------===//
2498// ParmVarDecl Implementation
2499//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002500
Sebastian Redl833ef452010-01-26 22:01:41 +00002501ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002502 SourceLocation StartLoc,
2503 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002504 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002505 StorageClass S, Expr *DefArg) {
Richard Smith053f6c62014-05-16 23:01:30 +00002506 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smithf7981722013-11-22 09:01:48 +00002507 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002508}
2509
Reid Kleckner8a365022013-06-24 17:51:48 +00002510QualType ParmVarDecl::getOriginalType() const {
2511 TypeSourceInfo *TSI = getTypeSourceInfo();
2512 QualType T = TSI ? TSI->getType() : getType();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002513 if (const auto *DT = dyn_cast<DecayedType>(T))
Reid Kleckner8a365022013-06-24 17:51:48 +00002514 return DT->getOriginalType();
2515 return T;
2516}
2517
Douglas Gregor72172e92012-01-05 21:55:30 +00002518ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00002519 return new (C, ID)
2520 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2521 nullptr, QualType(), nullptr, SC_None, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00002522}
2523
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002524SourceRange ParmVarDecl::getSourceRange() const {
2525 if (!hasInheritedDefaultArg()) {
2526 SourceRange ArgRange = getDefaultArgRange();
2527 if (ArgRange.isValid())
2528 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2529 }
2530
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002531 // DeclaratorDecl considers the range of postfix types as overlapping with the
2532 // declaration name, but this is not the case with parameters in ObjC methods.
2533 if (isa<ObjCMethodDecl>(getDeclContext()))
2534 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2535
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002536 return DeclaratorDecl::getSourceRange();
2537}
2538
Sebastian Redl833ef452010-01-26 22:01:41 +00002539Expr *ParmVarDecl::getDefaultArg() {
2540 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2541 assert(!hasUninstantiatedDefaultArg() &&
2542 "Default argument is not yet instantiated!");
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002543
Sebastian Redl833ef452010-01-26 22:01:41 +00002544 Expr *Arg = getInit();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002545 if (auto *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002546 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002547
Sebastian Redl833ef452010-01-26 22:01:41 +00002548 return Arg;
2549}
2550
Chandler Carruth813faed2015-12-30 02:51:00 +00002551void ParmVarDecl::setDefaultArg(Expr *defarg) {
2552 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2553 Init = defarg;
2554}
Sebastian Redl833ef452010-01-26 22:01:41 +00002555
Chandler Carruth813faed2015-12-30 02:51:00 +00002556SourceRange ParmVarDecl::getDefaultArgRange() const {
2557 switch (ParmVarDeclBits.DefaultArgKind) {
2558 case DAK_None:
2559 case DAK_Unparsed:
2560 // Nothing we can do here.
2561 return SourceRange();
2562
2563 case DAK_Uninstantiated:
Sebastian Redl833ef452010-01-26 22:01:41 +00002564 return getUninstantiatedDefaultArg()->getSourceRange();
2565
Chandler Carruth813faed2015-12-30 02:51:00 +00002566 case DAK_Normal:
2567 if (const Expr *E = getInit())
2568 return E->getSourceRange();
2569
2570 // Missing an actual expression, may be invalid.
2571 return SourceRange();
2572 }
2573 llvm_unreachable("Invalid default argument kind.");
2574}
2575
2576void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2577 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2578 Init = arg;
2579}
2580
2581Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2582 assert(hasUninstantiatedDefaultArg() &&
2583 "Wrong kind of initialization expression!");
2584 return cast_or_null<Expr>(Init.get<Stmt *>());
2585}
2586
2587bool ParmVarDecl::hasDefaultArg() const {
2588 // FIXME: We should just return false for DAK_None here once callers are
2589 // prepared for the case that we encountered an invalid default argument and
2590 // were unable to even build an invalid expression.
2591 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2592 !Init.isNull();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002593}
2594
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00002595bool ParmVarDecl::isParameterPack() const {
2596 return isa<PackExpansionType>(getType());
2597}
2598
Ted Kremenek540017e2011-10-06 05:00:56 +00002599void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2600 getASTContext().setParameterIndex(this, parameterIndex);
2601 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2602}
2603
2604unsigned ParmVarDecl::getParameterIndexLarge() const {
2605 return getASTContext().getParameterIndex(this);
2606}
2607
Nuno Lopes394ec982008-12-17 23:39:55 +00002608//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002609// FunctionDecl Implementation
2610//===----------------------------------------------------------------------===//
2611
Benjamin Kramer9170e912013-02-22 15:46:01 +00002612void FunctionDecl::getNameForDiagnostic(
2613 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2614 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002615 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2616 if (TemplateArgs)
Serge Pavlov03e672c2017-11-28 16:14:14 +00002617 printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002618}
2619
Ted Kremenek186a0742010-04-29 16:49:01 +00002620bool FunctionDecl::isVariadic() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002621 if (const auto *FT = getType()->getAs<FunctionProtoType>())
Ted Kremenek186a0742010-04-29 16:49:01 +00002622 return FT->isVariadic();
2623 return false;
2624}
2625
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002626bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002627 for (auto I : redecls()) {
Serge Pavlov9a618e12017-02-15 12:30:35 +00002628 if (I->doesThisDeclarationHaveABody()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002629 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002630 return true;
2631 }
2632 }
2633
2634 return false;
2635}
2636
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002637bool FunctionDecl::hasTrivialBody() const
2638{
2639 Stmt *S = getBody();
2640 if (!S) {
2641 // Since we don't have a body for this function, we don't know if it's
2642 // trivial or not.
2643 return false;
2644 }
2645
2646 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2647 return true;
2648 return false;
2649}
2650
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002651bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002652 for (auto I : redecls()) {
Serge Pavlov10673c92017-06-04 12:53:12 +00002653 if (I->isThisDeclarationADefinition()) {
2654 Definition = I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002655 return true;
2656 }
2657 }
2658
2659 return false;
2660}
2661
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002662Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002663 if (!hasBody(Definition))
Craig Topper36250ad2014-05-12 05:36:57 +00002664 return nullptr;
Rafael Espindola44503012013-10-19 01:37:17 +00002665
2666 if (Definition->Body)
2667 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002668
Craig Topper36250ad2014-05-12 05:36:57 +00002669 return nullptr;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002670}
2671
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002672void FunctionDecl::setBody(Stmt *B) {
2673 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002674 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002675 EndRangeLoc = B->getLocEnd();
2676}
2677
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002678void FunctionDecl::setPure(bool P) {
2679 IsPure = P;
2680 if (P)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002681 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002682 Parent->markedVirtualFunctionPure();
2683}
2684
Richard Smith8d0dc312013-07-21 23:12:18 +00002685template<std::size_t Len>
2686static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2687 IdentifierInfo *II = ND->getIdentifier();
2688 return II && II->isStr(Str);
2689}
2690
Douglas Gregor16618f22009-09-12 00:17:51 +00002691bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002692 const TranslationUnitDecl *tunit =
2693 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2694 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002695 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002696 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002697}
2698
David Majnemerc729b0b2013-09-16 22:44:20 +00002699bool FunctionDecl::isMSVCRTEntryPoint() const {
2700 const TranslationUnitDecl *TUnit =
2701 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2702 if (!TUnit)
2703 return false;
2704
2705 // Even though we aren't really targeting MSVCRT if we are freestanding,
2706 // semantic analysis for these functions remains the same.
2707
2708 // MSVCRT entry points only exist on MSVCRT targets.
2709 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2710 return false;
2711
2712 // Nameless functions like constructors cannot be entry points.
2713 if (!getIdentifier())
2714 return false;
2715
2716 return llvm::StringSwitch<bool>(getName())
2717 .Cases("main", // an ANSI console app
2718 "wmain", // a Unicode console App
2719 "WinMain", // an ANSI GUI app
2720 "wWinMain", // a Unicode GUI app
2721 "DllMain", // a DLL
2722 true)
2723 .Default(false);
2724}
2725
John McCall53ffd372011-05-15 17:49:20 +00002726bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2727 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2728 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2729 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2730 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2731 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2732
Richard Smithf6004412014-01-19 23:25:37 +00002733 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2734 return false;
John McCall53ffd372011-05-15 17:49:20 +00002735
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002736 const auto *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002737 if (proto->getNumParams() != 2 || proto->isVariadic())
2738 return false;
John McCall53ffd372011-05-15 17:49:20 +00002739
2740 ASTContext &Context =
2741 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2742 ->getASTContext();
2743
2744 // The result type and first argument type are constant across all
2745 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002746 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002747}
2748
Akira Hatanakacae83f72017-06-29 18:48:40 +00002749bool FunctionDecl::isReplaceableGlobalAllocationFunction(bool *IsAligned) const {
Richard Smith8d0dc312013-07-21 23:12:18 +00002750 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2751 return false;
2752 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2753 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2754 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2755 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2756 return false;
2757
2758 if (isa<CXXRecordDecl>(getDeclContext()))
2759 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002760
2761 // This can only fail for an invalid 'operator new' declaration.
2762 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2763 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002764
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002765 const auto *FPT = getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00002766 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002767 return false;
2768
2769 // If this is a single-parameter function, it must be a replaceable global
2770 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002771 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002772 return true;
2773
Richard Smithb2f0f052016-10-10 18:54:32 +00002774 unsigned Params = 1;
2775 QualType Ty = FPT->getParamType(Params);
Richard Smith1cdec012013-09-29 04:40:38 +00002776 ASTContext &Ctx = getASTContext();
Richard Smithb2f0f052016-10-10 18:54:32 +00002777
2778 auto Consume = [&] {
2779 ++Params;
2780 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
2781 };
2782
2783 // In C++14, the next parameter can be a 'std::size_t' for sized delete.
2784 bool IsSizedDelete = false;
Richard Smithb47c36f2013-11-05 09:12:18 +00002785 if (Ctx.getLangOpts().SizedDeallocation &&
Richard Smithb2f0f052016-10-10 18:54:32 +00002786 (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2787 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
2788 Ctx.hasSameType(Ty, Ctx.getSizeType())) {
2789 IsSizedDelete = true;
2790 Consume();
2791 }
2792
2793 // In C++17, the next parameter can be a 'std::align_val_t' for aligned
2794 // new/delete.
Akira Hatanakacae83f72017-06-29 18:48:40 +00002795 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
2796 if (IsAligned)
2797 *IsAligned = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00002798 Consume();
Akira Hatanakacae83f72017-06-29 18:48:40 +00002799 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002800
2801 // Finally, if this is not a sized delete, the final parameter can
2802 // be a 'const std::nothrow_t&'.
2803 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
2804 Ty = Ty->getPointeeType();
2805 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2806 return false;
2807 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2808 if (RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace())
2809 Consume();
2810 }
2811
2812 return Params == FPT->getNumParams();
Richard Smith8d0dc312013-07-21 23:12:18 +00002813}
2814
Richard Smith5b349582017-10-13 01:55:36 +00002815bool FunctionDecl::isDestroyingOperatorDelete() const {
2816 // C++ P0722:
2817 // Within a class C, a single object deallocation function with signature
2818 // (T, std::destroying_delete_t, <more params>)
2819 // is a destroying operator delete.
2820 if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
2821 getNumParams() < 2)
2822 return false;
2823
2824 auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
2825 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
2826 RD->getIdentifier()->isStr("destroying_delete_t");
2827}
2828
Rafael Espindolaf4187652013-02-14 01:18:37 +00002829LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00002830 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002831}
2832
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002833bool FunctionDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00002834 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002835}
2836
Rafael Espindola593537a2013-05-05 20:15:21 +00002837bool FunctionDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002838 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002839}
2840
2841bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002842 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002843}
2844
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002845bool FunctionDecl::isGlobal() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002846 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002847 return Method->isStatic();
2848
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002849 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002850 return false;
2851
Mike Stump11289f42009-09-09 15:08:12 +00002852 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002853 DC->isNamespace();
2854 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002855 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002856 if (!Namespace->getDeclName())
2857 return false;
2858 break;
2859 }
2860 }
2861
2862 return true;
2863}
2864
Richard Smith10876ef2013-01-17 01:30:42 +00002865bool FunctionDecl::isNoReturn() const {
Adrian Prantl721c7cb2016-08-17 16:42:15 +00002866 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2867 hasAttr<C11NoReturnAttr>())
2868 return true;
2869
2870 if (auto *FnTy = getType()->getAs<FunctionType>())
2871 return FnTy->getNoReturnAttr();
2872
2873 return false;
Richard Smith10876ef2013-01-17 01:30:42 +00002874}
2875
Erich Keane3efe0022018-07-20 14:13:28 +00002876bool FunctionDecl::isCPUDispatchMultiVersion() const {
2877 return isMultiVersion() && hasAttr<CPUDispatchAttr>();
2878}
2879
2880bool FunctionDecl::isCPUSpecificMultiVersion() const {
2881 return isMultiVersion() && hasAttr<CPUSpecificAttr>();
2882}
2883
Sebastian Redl833ef452010-01-26 22:01:41 +00002884void
2885FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002886 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002887
2888 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2889 FunctionTemplateDecl *PrevFunTmpl
Craig Topper36250ad2014-05-12 05:36:57 +00002890 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002891 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00002892 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002893 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002894
Axel Naumannfbc7b982011-11-08 18:21:06 +00002895 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002896 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002897}
2898
Rafael Espindola8db352d2013-10-17 15:37:26 +00002899FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002900
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002901/// Returns a value indicating whether this function
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002902/// corresponds to a builtin function.
2903///
2904/// The function corresponds to a built-in function if it is
2905/// declared at translation scope or within an extern "C" block and
2906/// its name matches with the name of a builtin. The returned value
2907/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002908/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002909/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002910unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002911 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002912 return 0;
2913
2914 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002915 if (!BuiltinID)
2916 return 0;
2917
2918 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00002919 if (Context.getLangOpts().CPlusPlus) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002920 const auto *LinkageDecl =
2921 dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
Warren Hunt445d83e2013-11-01 23:46:51 +00002922 // In C++, the first declaration of a builtin is always inside an implicit
2923 // extern "C".
2924 // FIXME: A recognised library function may not be directly in an extern "C"
2925 // declaration, for instance "extern "C" { namespace std { decl } }".
David Majnemerba3e5ec2015-03-13 18:26:17 +00002926 if (!LinkageDecl) {
2927 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
David Majnemer145abde2016-01-26 01:12:17 +00002928 Context.getTargetInfo().getCXXABI().isMicrosoft())
David Majnemerba3e5ec2015-03-13 18:26:17 +00002929 return Builtin::BI__GetExceptionInfo;
2930 return 0;
2931 }
2932 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
Warren Hunt445d83e2013-11-01 23:46:51 +00002933 return 0;
2934 }
2935
2936 // If the function is marked "overloadable", it has a different mangled name
2937 // and is not the C library function.
Aaron Ballman9ead1242013-12-19 02:39:40 +00002938 if (hasAttr<OverloadableAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00002939 return 0;
2940
Douglas Gregore711f702009-02-14 18:57:46 +00002941 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2942 return BuiltinID;
2943
2944 // This function has the name of a known C library
2945 // function. Determine whether it actually refers to the C library
2946 // function or whether it just has the same name.
2947
Douglas Gregora908e7f2009-02-17 03:23:10 +00002948 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002949 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002950 return 0;
2951
Anastasia Stulova1202de32016-02-12 12:07:04 +00002952 // OpenCL v1.2 s6.9.f - The library functions defined in
2953 // the C99 standard headers are not available.
2954 if (Context.getLangOpts().OpenCL &&
2955 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2956 return 0;
2957
Artem Belevich5ecdb942018-01-23 19:08:18 +00002958 // CUDA does not have device-side standard library. printf and malloc are the
2959 // only special cases that are supported by device-side runtime.
2960 if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
2961 !hasAttr<CUDAHostAttr>() &&
2962 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
2963 return 0;
2964
Warren Hunt445d83e2013-11-01 23:46:51 +00002965 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002966}
2967
Chris Lattner47c0d002009-04-25 06:03:53 +00002968/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002969/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002970/// after it has been created.
2971unsigned FunctionDecl::getNumParams() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002972 const auto *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002973 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002974}
2975
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002976void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002977 ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00002978 assert(!ParamInfo && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002979 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002980
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002981 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002982 if (!NewParamInfo.empty()) {
2983 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2984 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002985 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002986}
Chris Lattner41943152007-01-25 04:52:46 +00002987
Chris Lattner58258242008-04-10 02:22:51 +00002988/// getMinRequiredArguments - Returns the minimum number of arguments
2989/// needed to call this function. This may be fewer than the number of
2990/// function parameters, if some of the parameters have default
Richard Smith91151782014-04-01 19:18:16 +00002991/// arguments (in C++) or are parameter packs (C++11).
Chris Lattner58258242008-04-10 02:22:51 +00002992unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002993 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002994 return getNumParams();
Chris Lattner58258242008-04-10 02:22:51 +00002995
Richard Smith91151782014-04-01 19:18:16 +00002996 unsigned NumRequiredArgs = 0;
David Majnemer59f77922016-06-24 04:05:48 +00002997 for (auto *Param : parameters())
Richard Smith91151782014-04-01 19:18:16 +00002998 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2999 ++NumRequiredArgs;
Chris Lattner58258242008-04-10 02:22:51 +00003000 return NumRequiredArgs;
3001}
3002
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003003/// The combination of the extern and inline keywords under MSVC forces
David Majnemer54e3ba52014-04-02 23:17:29 +00003004/// the function to be required.
3005///
3006/// Note: This function assumes that we will only get called when isInlined()
3007/// would return true for this FunctionDecl.
3008bool FunctionDecl::isMSExternInline() const {
3009 assert(isInlined() && "expected to get called on an inlined function!");
3010
3011 const ASTContext &Context = getASTContext();
David Majnemer3f021502015-10-08 04:53:31 +00003012 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3013 !hasAttr<DLLExportAttr>())
David Majnemer54e3ba52014-04-02 23:17:29 +00003014 return false;
3015
David Majnemer73768702015-03-20 00:02:27 +00003016 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
3017 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00003018 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00003019 return true;
3020
3021 return false;
3022}
3023
3024static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3025 if (Redecl->getStorageClass() != SC_Extern)
3026 return false;
3027
3028 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
3029 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00003030 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00003031 return false;
3032
3033 return true;
3034}
3035
Eli Friedman1b125c32012-02-07 03:50:18 +00003036static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3037 // Only consider file-scope declarations in this test.
3038 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3039 return false;
3040
3041 // Only consider explicit declarations; the presence of a builtin for a
3042 // libcall shouldn't affect whether a definition is externally visible.
3043 if (Redecl->isImplicit())
3044 return false;
3045
3046 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
3047 return true; // Not an inline definition
3048
3049 return false;
3050}
3051
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003052/// For a function declaration in C or C++, determine whether this
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003053/// declaration causes the definition to be externally visible.
3054///
David Majnemer54e3ba52014-04-02 23:17:29 +00003055/// For instance, this determines if adding the current declaration to the set
Eli Friedman1b125c32012-02-07 03:50:18 +00003056/// of redeclarations of the given functions causes
3057/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003058bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
Justin Lebar0241c962016-10-28 16:46:39 +00003059 assert(!doesThisDeclarationHaveABody() &&
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003060 "Must have a declaration without a body.");
3061
3062 ASTContext &Context = getASTContext();
3063
David Majnemer54e3ba52014-04-02 23:17:29 +00003064 if (Context.getLangOpts().MSVCCompat) {
3065 const FunctionDecl *Definition;
3066 if (hasBody(Definition) && Definition->isInlined() &&
3067 redeclForcesDefMSVC(this))
3068 return true;
3069 }
3070
David Blaikiebbafb8a2012-03-11 07:00:24 +00003071 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003072 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3073 // an externally visible definition.
3074 //
3075 // FIXME: What happens if gnu_inline gets added on after the first
3076 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003077 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00003078 return false;
3079
3080 const FunctionDecl *Prev = this;
3081 bool FoundBody = false;
3082 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00003083 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00003084
3085 if (Prev->Body) {
3086 // If it's not the case that both 'inline' and 'extern' are
3087 // specified on the definition, then it is always externally visible.
3088 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003089 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00003090 return false;
3091 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003092 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003093 return false;
3094 }
3095 }
3096 return FoundBody;
3097 }
3098
David Blaikiebbafb8a2012-03-11 07:00:24 +00003099 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003100 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00003101
3102 // C99 6.7.4p6:
3103 // [...] If all of the file scope declarations for a function in a
3104 // translation unit include the inline function specifier without extern,
3105 // then the definition in that translation unit is an inline definition.
3106 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003107 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00003108 const FunctionDecl *Prev = this;
3109 bool FoundBody = false;
3110 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00003111 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00003112 if (RedeclForcesDefC99(Prev))
3113 return false;
3114 }
3115 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003116}
3117
Alp Tokerd0787eb2014-07-02 01:47:15 +00003118SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3119 const TypeSourceInfo *TSI = getTypeSourceInfo();
3120 if (!TSI)
3121 return SourceRange();
Alp Tokerf5b10792014-07-02 12:55:58 +00003122 FunctionTypeLoc FTL =
3123 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
3124 if (!FTL)
Alp Tokerd0787eb2014-07-02 01:47:15 +00003125 return SourceRange();
3126
Alp Tokerf5b10792014-07-02 12:55:58 +00003127 // Skip self-referential return types.
3128 const SourceManager &SM = getASTContext().getSourceManager();
3129 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3130 SourceLocation Boundary = getNameInfo().getLocStart();
3131 if (RTRange.isInvalid() || Boundary.isInvalid() ||
3132 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3133 return SourceRange();
Alp Tokerd0787eb2014-07-02 01:47:15 +00003134
Alp Tokerf5b10792014-07-02 12:55:58 +00003135 return RTRange;
Alp Tokerd0787eb2014-07-02 01:47:15 +00003136}
3137
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003138SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
3139 const TypeSourceInfo *TSI = getTypeSourceInfo();
3140 if (!TSI)
3141 return SourceRange();
3142 FunctionTypeLoc FTL =
3143 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
3144 if (!FTL)
3145 return SourceRange();
3146
3147 return FTL.getExceptionSpecRange();
3148}
3149
Aaron Ballmane7964782016-03-07 22:44:55 +00003150const Attr *FunctionDecl::getUnusedResultAttr() const {
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003151 QualType RetType = getReturnType();
George Karpenkov39e51372018-07-28 02:16:13 +00003152 if (const auto *Ret = RetType->getAsRecordDecl()) {
3153 if (const auto *R = Ret->getAttr<WarnUnusedResultAttr>())
3154 return R;
Aaron Ballmane7964782016-03-07 22:44:55 +00003155 } else if (const auto *ET = RetType->getAs<EnumType>()) {
3156 if (const EnumDecl *ED = ET->getDecl()) {
3157 if (const auto *R = ED->getAttr<WarnUnusedResultAttr>())
3158 return R;
3159 }
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003160 }
Aaron Ballmane7964782016-03-07 22:44:55 +00003161 return getAttr<WarnUnusedResultAttr>();
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003162}
3163
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003164/// For an inline function definition in C, or for a gnu_inline function
Richard Smithf3814ad2013-01-25 00:08:28 +00003165/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00003166///
3167/// Inline function definitions are always available for inlining optimizations.
3168/// However, depending on the language dialect, declaration specifiers, and
3169/// attributes, the definition of an inline function may or may not be
3170/// "externally" visible to other translation units in the program.
3171///
3172/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00003173/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00003174/// inline definition becomes externally visible (C99 6.7.4p6).
3175///
3176/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3177/// definition, we use the GNU semantics for inline, which are nearly the
3178/// opposite of C99 semantics. In particular, "inline" by itself will create
3179/// an externally visible symbol, but "extern inline" will not create an
3180/// externally visible symbol.
3181bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Manuel Klimekda7456a2016-11-01 10:30:50 +00003182 assert((doesThisDeclarationHaveABody() || willHaveBody()) &&
3183 "Must be a function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003184 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00003185 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00003186
David Blaikiebbafb8a2012-03-11 07:00:24 +00003187 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003188 // Note: If you change the logic here, please change
3189 // doesDeclarationForceExternallyVisibleDefinition as well.
3190 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00003191 // If it's not the case that both 'inline' and 'extern' are
3192 // specified on the definition, then this inline definition is
3193 // externally visible.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003194 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00003195 return true;
3196
3197 // If any declaration is 'inline' but not 'extern', then this definition
3198 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00003199 for (auto Redecl : redecls()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00003200 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003201 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00003202 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00003203 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00003204
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003205 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003206 }
Eli Friedman1b125c32012-02-07 03:50:18 +00003207
Richard Smithf3814ad2013-01-25 00:08:28 +00003208 // The rest of this function is C-only.
3209 assert(!Context.getLangOpts().CPlusPlus &&
3210 "should not use C inline rules in C++");
3211
Douglas Gregor299d76e2009-09-13 07:46:26 +00003212 // C99 6.7.4p6:
3213 // [...] If all of the file scope declarations for a function in a
3214 // translation unit include the inline function specifier without extern,
3215 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00003216 for (auto Redecl : redecls()) {
3217 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00003218 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003219 }
3220
3221 // C99 6.7.4p6:
3222 // An inline definition does not provide an external definition for the
3223 // function, and does not forbid an external definition in another
3224 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003225 return false;
3226}
3227
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003228/// getOverloadedOperator - Which C++ overloaded operator this
3229/// function represents, if any.
3230OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00003231 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3232 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003233 else
3234 return OO_None;
3235}
3236
Alexis Huntc88db062010-01-13 09:01:02 +00003237/// getLiteralIdentifier - The literal suffix identifier this function
3238/// represents, if any.
3239const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3240 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3241 return getDeclName().getCXXLiteralIdentifier();
3242 else
Craig Topper36250ad2014-05-12 05:36:57 +00003243 return nullptr;
Alexis Huntc88db062010-01-13 09:01:02 +00003244}
3245
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003246FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3247 if (TemplateOrSpecialization.isNull())
3248 return TK_NonTemplate;
3249 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3250 return TK_FunctionTemplate;
3251 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3252 return TK_MemberSpecialization;
3253 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3254 return TK_FunctionTemplateSpecialization;
3255 if (TemplateOrSpecialization.is
3256 <DependentFunctionTemplateSpecializationInfo*>())
3257 return TK_DependentFunctionTemplateSpecialization;
3258
David Blaikie83d382b2011-09-23 05:06:16 +00003259 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003260}
3261
Douglas Gregord801b062009-10-07 23:56:10 +00003262FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00003263 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00003264 return cast<FunctionDecl>(Info->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00003265
3266 return nullptr;
Douglas Gregord801b062009-10-07 23:56:10 +00003267}
3268
Chandler Carruth21c90602015-12-30 03:24:14 +00003269MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3270 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>();
3271}
3272
Douglas Gregord801b062009-10-07 23:56:10 +00003273void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003274FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3275 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00003276 TemplateSpecializationKind TSK) {
3277 assert(TemplateOrSpecialization.isNull() &&
3278 "Member function is already a specialization");
3279 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003280 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00003281 TemplateOrSpecialization = Info;
3282}
3283
Chandler Carruth21c90602015-12-30 03:24:14 +00003284FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3285 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3286}
3287
3288void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3289 TemplateOrSpecialization = Template;
3290}
3291
Douglas Gregorafca3b42009-10-27 20:53:28 +00003292bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00003293 // If the function is invalid, it can't be implicitly instantiated.
3294 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00003295 return false;
3296
3297 switch (getTemplateSpecializationKind()) {
3298 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00003299 case TSK_ExplicitInstantiationDefinition:
3300 return false;
3301
3302 case TSK_ImplicitInstantiation:
3303 return true;
3304
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003305 // It is possible to instantiate TSK_ExplicitSpecialization kind
3306 // if the FunctionDecl has a class scope specialization pattern.
3307 case TSK_ExplicitSpecialization:
Craig Topper36250ad2014-05-12 05:36:57 +00003308 return getClassScopeSpecializationPattern() != nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003309
Douglas Gregorafca3b42009-10-27 20:53:28 +00003310 case TSK_ExplicitInstantiationDeclaration:
3311 // Handled below.
3312 break;
3313 }
3314
3315 // Find the actual template from which we will instantiate.
3316 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003317 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003318 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003319 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00003320
3321 // C++0x [temp.explicit]p9:
3322 // Except for inline functions, other explicit instantiation declarations
3323 // have the effect of suppressing the implicit instantiation of the entity
3324 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003325 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00003326 return true;
3327
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003328 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00003329}
3330
3331bool FunctionDecl::isTemplateInstantiation() const {
3332 switch (getTemplateSpecializationKind()) {
3333 case TSK_Undeclared:
3334 case TSK_ExplicitSpecialization:
3335 return false;
3336 case TSK_ImplicitInstantiation:
3337 case TSK_ExplicitInstantiationDeclaration:
3338 case TSK_ExplicitInstantiationDefinition:
3339 return true;
3340 }
3341 llvm_unreachable("All TSK values handled.");
3342}
Douglas Gregorafca3b42009-10-27 20:53:28 +00003343
3344FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003345 // Handle class scope explicit specialization special case.
Richard Smith2195ec92017-04-21 01:15:13 +00003346 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
3347 if (auto *Spec = getClassScopeSpecializationPattern())
3348 return getDefinitionOrSelf(Spec);
3349 return nullptr;
3350 }
3351
Faisal Valib90b2112014-04-03 16:32:21 +00003352 // If this is a generic lambda call operator specialization, its
3353 // instantiation pattern is always its primary template's pattern
3354 // even if its primary template was instantiated from another
3355 // member template (which happens with nested generic lambdas).
3356 // Since a lambda's call operator's body is transformed eagerly,
3357 // we don't have to go hunting for a prototype definition template
3358 // (i.e. instantiated-from-member-template) to use as an instantiation
3359 // pattern.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003360
Faisal Valib90b2112014-04-03 16:32:21 +00003361 if (isGenericLambdaCallOperatorSpecialization(
3362 dyn_cast<CXXMethodDecl>(this))) {
Richard Smith2195ec92017-04-21 01:15:13 +00003363 assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3364 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
Faisal Valib90b2112014-04-03 16:32:21 +00003365 }
Richard Smith2195ec92017-04-21 01:15:13 +00003366
Douglas Gregorafca3b42009-10-27 20:53:28 +00003367 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3368 while (Primary->getInstantiatedFromMemberTemplate()) {
3369 // If we have hit a point where the user provided a specialization of
3370 // this template, we're done looking.
3371 if (Primary->isMemberSpecialization())
3372 break;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003373 Primary = Primary->getInstantiatedFromMemberTemplate();
3374 }
Richard Smith2195ec92017-04-21 01:15:13 +00003375
3376 return getDefinitionOrSelf(Primary->getTemplatedDecl());
Douglas Gregorafca3b42009-10-27 20:53:28 +00003377 }
Richard Smith2195ec92017-04-21 01:15:13 +00003378
3379 if (auto *MFD = getInstantiatedFromMemberFunction())
3380 return getDefinitionOrSelf(MFD);
3381
3382 return nullptr;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003383}
3384
Douglas Gregor70d83e22009-06-29 17:30:29 +00003385FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00003386 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003387 = TemplateOrSpecialization
3388 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00003389 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00003390 }
Craig Topper36250ad2014-05-12 05:36:57 +00003391 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003392}
3393
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003394FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3395 return getASTContext().getClassScopeSpecializationPattern(this);
3396}
3397
Chandler Carruth21c90602015-12-30 03:24:14 +00003398FunctionTemplateSpecializationInfo *
3399FunctionDecl::getTemplateSpecializationInfo() const {
3400 return TemplateOrSpecialization
3401 .dyn_cast<FunctionTemplateSpecializationInfo *>();
3402}
3403
Douglas Gregor70d83e22009-06-29 17:30:29 +00003404const TemplateArgumentList *
3405FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00003406 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00003407 = TemplateOrSpecialization
3408 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003409 return Info->TemplateArguments;
3410 }
Craig Topper36250ad2014-05-12 05:36:57 +00003411 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003412}
3413
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00003414const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003415FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3416 if (FunctionTemplateSpecializationInfo *Info
3417 = TemplateOrSpecialization
3418 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3419 return Info->TemplateArgumentsAsWritten;
3420 }
Craig Topper36250ad2014-05-12 05:36:57 +00003421 return nullptr;
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003422}
3423
Mike Stump11289f42009-09-09 15:08:12 +00003424void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003425FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3426 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003427 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003428 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003429 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00003430 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3431 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003432 assert(TSK != TSK_Undeclared &&
3433 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00003434 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003435 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003436 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00003437 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3438 TemplateArgs,
3439 TemplateArgsAsWritten,
3440 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003441 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00003442 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003443}
3444
John McCallb9c78482010-04-08 09:05:18 +00003445void
3446FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3447 const UnresolvedSetImpl &Templates,
3448 const TemplateArgumentListInfo &TemplateArgs) {
3449 assert(TemplateOrSpecialization.isNull());
John McCallb9c78482010-04-08 09:05:18 +00003450 DependentFunctionTemplateSpecializationInfo *Info =
James Y Knight7a22b242015-08-06 20:26:32 +00003451 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3452 TemplateArgs);
John McCallb9c78482010-04-08 09:05:18 +00003453 TemplateOrSpecialization = Info;
3454}
3455
James Y Knight7a22b242015-08-06 20:26:32 +00003456DependentFunctionTemplateSpecializationInfo *
Chandler Carruth21c90602015-12-30 03:24:14 +00003457FunctionDecl::getDependentSpecializationInfo() const {
3458 return TemplateOrSpecialization
3459 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3460}
3461
3462DependentFunctionTemplateSpecializationInfo *
James Y Knight7a22b242015-08-06 20:26:32 +00003463DependentFunctionTemplateSpecializationInfo::Create(
3464 ASTContext &Context, const UnresolvedSetImpl &Ts,
3465 const TemplateArgumentListInfo &TArgs) {
3466 void *Buffer = Context.Allocate(
3467 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3468 TArgs.size(), Ts.size()));
3469 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3470}
3471
John McCallb9c78482010-04-08 09:05:18 +00003472DependentFunctionTemplateSpecializationInfo::
3473DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3474 const TemplateArgumentListInfo &TArgs)
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003475 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
James Y Knight53c76162015-07-17 18:21:37 +00003476 NumTemplates = Ts.size();
3477 NumArgs = TArgs.size();
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003478
James Y Knight7a22b242015-08-06 20:26:32 +00003479 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
John McCallb9c78482010-04-08 09:05:18 +00003480 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3481 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3482
James Y Knight7a22b242015-08-06 20:26:32 +00003483 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
John McCallb9c78482010-04-08 09:05:18 +00003484 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3485 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3486}
3487
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003488TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00003489 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003490 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00003491 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00003492 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00003493 if (FTSInfo)
3494 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00003495
Douglas Gregord801b062009-10-07 23:56:10 +00003496 MemberSpecializationInfo *MSInfo
3497 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3498 if (MSInfo)
3499 return MSInfo->getTemplateSpecializationKind();
3500
3501 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003502}
3503
Mike Stump11289f42009-09-09 15:08:12 +00003504void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003505FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3506 SourceLocation PointOfInstantiation) {
3507 if (FunctionTemplateSpecializationInfo *FTSInfo
3508 = TemplateOrSpecialization.dyn_cast<
3509 FunctionTemplateSpecializationInfo*>()) {
3510 FTSInfo->setTemplateSpecializationKind(TSK);
3511 if (TSK != TSK_ExplicitSpecialization &&
3512 PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00003513 FTSInfo->getPointOfInstantiation().isInvalid()) {
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003514 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00003515 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3516 L->InstantiationRequested(this);
3517 }
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003518 } else if (MemberSpecializationInfo *MSInfo
3519 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3520 MSInfo->setTemplateSpecializationKind(TSK);
3521 if (TSK != TSK_ExplicitSpecialization &&
3522 PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00003523 MSInfo->getPointOfInstantiation().isInvalid()) {
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003524 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00003525 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3526 L->InstantiationRequested(this);
3527 }
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003528 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003529 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003530}
3531
3532SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00003533 if (FunctionTemplateSpecializationInfo *FTSInfo
3534 = TemplateOrSpecialization.dyn_cast<
3535 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003536 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00003537 else if (MemberSpecializationInfo *MSInfo
3538 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003539 return MSInfo->getPointOfInstantiation();
3540
3541 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00003542}
3543
Douglas Gregor6411b922009-09-11 20:15:17 +00003544bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00003545 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00003546 return true;
3547
3548 // If this function was instantiated from a member function of a
3549 // class template, check whether that member function was defined out-of-line.
3550 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3551 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003552 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003553 return Definition->isOutOfLine();
3554 }
3555
3556 // If this function was instantiated from a function template,
3557 // check whether that function template was defined out-of-line.
3558 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3559 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003560 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003561 return Definition->isOutOfLine();
3562 }
3563
3564 return false;
3565}
3566
Abramo Bagnaraea947882011-03-08 16:41:52 +00003567SourceRange FunctionDecl::getSourceRange() const {
3568 return SourceRange(getOuterLocStart(), EndRangeLoc);
3569}
3570
Anna Zaks28db7ce2012-01-18 02:45:01 +00003571unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00003572 IdentifierInfo *FnInfo = getIdentifier();
3573
3574 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00003575 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003576
3577 // Builtin handling.
3578 switch (getBuiltinID()) {
3579 case Builtin::BI__builtin_memset:
3580 case Builtin::BI__builtin___memset_chk:
3581 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003582 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003583
3584 case Builtin::BI__builtin_memcpy:
3585 case Builtin::BI__builtin___memcpy_chk:
3586 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003587 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003588
3589 case Builtin::BI__builtin_memmove:
3590 case Builtin::BI__builtin___memmove_chk:
3591 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003592 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003593
3594 case Builtin::BIstrlcpy:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003595 case Builtin::BI__builtin___strlcpy_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003596 return Builtin::BIstrlcpy;
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003597
Anna Zaks201d4892012-01-13 21:52:01 +00003598 case Builtin::BIstrlcat:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003599 case Builtin::BI__builtin___strlcat_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003600 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003601
3602 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003603 case Builtin::BImemcmp:
3604 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003605
3606 case Builtin::BI__builtin_strncpy:
3607 case Builtin::BI__builtin___strncpy_chk:
3608 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003609 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003610
3611 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003612 case Builtin::BIstrncmp:
3613 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003614
3615 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003616 case Builtin::BIstrncasecmp:
3617 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003618
3619 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003620 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003621 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003622 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003623
3624 case Builtin::BI__builtin_strndup:
3625 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003626 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003627
Anna Zaks314cd092012-02-01 19:08:57 +00003628 case Builtin::BI__builtin_strlen:
3629 case Builtin::BIstrlen:
3630 return Builtin::BIstrlen;
3631
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003632 case Builtin::BI__builtin_bzero:
3633 case Builtin::BIbzero:
3634 return Builtin::BIbzero;
3635
Anna Zaks201d4892012-01-13 21:52:01 +00003636 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003637 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003638 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003639 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003640 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003641 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003642 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003643 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003644 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003645 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003646 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003647 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003648 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003649 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003650 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003651 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003652 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003653 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003654 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003655 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003656 else if (FnInfo->isStr("strlen"))
3657 return Builtin::BIstrlen;
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003658 else if (FnInfo->isStr("bzero"))
3659 return Builtin::BIbzero;
Anna Zaks201d4892012-01-13 21:52:01 +00003660 }
3661 break;
3662 }
Anna Zaks22122702012-01-17 00:37:07 +00003663 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003664}
3665
Richard Trieu27c1b1a2018-07-10 01:40:50 +00003666unsigned FunctionDecl::getODRHash() const {
3667 assert(HasODRHash);
3668 return ODRHash;
3669}
3670
Richard Trieue6caa262017-12-23 00:41:01 +00003671unsigned FunctionDecl::getODRHash() {
3672 if (HasODRHash)
3673 return ODRHash;
3674
Richard Trieu0ac2eb72018-02-22 05:50:29 +00003675 if (auto *FT = getInstantiatedFromMemberFunction()) {
3676 HasODRHash = true;
3677 ODRHash = FT->getODRHash();
3678 return ODRHash;
3679 }
3680
Richard Trieue6caa262017-12-23 00:41:01 +00003681 class ODRHash Hash;
3682 Hash.AddFunctionDecl(this);
3683 HasODRHash = true;
3684 ODRHash = Hash.CalculateHash();
3685 return ODRHash;
3686}
3687
Chris Lattner59a25942008-03-31 00:36:02 +00003688//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003689// FieldDecl Implementation
3690//===----------------------------------------------------------------------===//
3691
Jay Foad39c79802011-01-12 09:06:06 +00003692FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003693 SourceLocation StartLoc, SourceLocation IdLoc,
3694 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003695 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003696 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003697 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3698 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003699}
3700
Douglas Gregor72172e92012-01-05 21:55:30 +00003701FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003702 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3703 SourceLocation(), nullptr, QualType(), nullptr,
3704 nullptr, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00003705}
3706
Sebastian Redl833ef452010-01-26 22:01:41 +00003707bool FieldDecl::isAnonymousStructOrUnion() const {
3708 if (!isImplicit() || getDeclName())
3709 return false;
3710
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003711 if (const auto *Record = getType()->getAs<RecordType>())
Sebastian Redl833ef452010-01-26 22:01:41 +00003712 return Record->getDecl()->isAnonymousStructOrUnion();
3713
3714 return false;
3715}
3716
Richard Smithcaf33902011-10-10 18:28:20 +00003717unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3718 assert(isBitField() && "not a bitfield");
Richard Smith6b8e3c02017-08-28 00:28:14 +00003719 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
Richard Smithcaf33902011-10-10 18:28:20 +00003720}
3721
Richard Smith866dee42018-04-02 18:29:43 +00003722bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const {
3723 return isUnnamedBitfield() && !getBitWidth()->isValueDependent() &&
3724 getBitWidthValue(Ctx) == 0;
3725}
3726
John McCall4e819612011-01-20 07:57:12 +00003727unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00003728 const FieldDecl *Canonical = getCanonicalDecl();
3729 if (Canonical != this)
3730 return Canonical->getFieldIndex();
3731
John McCall4e819612011-01-20 07:57:12 +00003732 if (CachedFieldIndex) return CachedFieldIndex - 1;
3733
Richard Smithd62306a2011-11-10 06:34:14 +00003734 unsigned Index = 0;
Richard Smith85567dd2017-11-15 01:33:46 +00003735 const RecordDecl *RD = getParent()->getDefinition();
3736 assert(RD && "requested index for field of struct with no definition");
Richard Smithd62306a2011-11-10 06:34:14 +00003737
Hans Wennborga302cd92014-08-21 16:06:57 +00003738 for (auto *Field : RD->fields()) {
3739 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3740 ++Index;
3741 }
John McCall4e819612011-01-20 07:57:12 +00003742
Richard Smithd62306a2011-11-10 06:34:14 +00003743 assert(CachedFieldIndex && "failed to find field in parent");
3744 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00003745}
3746
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003747SourceRange FieldDecl::getSourceRange() const {
Richard Smith6b8e3c02017-08-28 00:28:14 +00003748 const Expr *FinalExpr = getInClassInitializer();
3749 if (!FinalExpr)
3750 FinalExpr = getBitWidth();
3751 if (FinalExpr)
3752 return SourceRange(getInnerLocStart(), FinalExpr->getLocEnd());
3753 return DeclaratorDecl::getSourceRange();
Alexey Bataev39c81e22014-08-28 04:28:19 +00003754}
3755
3756void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
David Blaikie11ab0782014-10-31 17:18:09 +00003757 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
Alexey Bataev330de032014-10-29 12:21:55 +00003758 "capturing type in non-lambda or captured record.");
Richard Smith6b8e3c02017-08-28 00:28:14 +00003759 assert(InitStorage.getInt() == ISK_NoInit &&
John McCallc90c1492014-10-10 18:44:34 +00003760 InitStorage.getPointer() == nullptr &&
Alexey Bataev39c81e22014-08-28 04:28:19 +00003761 "bit width, initializer or captured type already set");
John McCallc90c1492014-10-10 18:44:34 +00003762 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3763 ISK_CapturedVLAType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00003764}
3765
Sebastian Redl833ef452010-01-26 22:01:41 +00003766//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003767// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00003768//===----------------------------------------------------------------------===//
3769
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003770SourceLocation TagDecl::getOuterLocStart() const {
3771 return getTemplateOrInnerLocStart(this);
3772}
3773
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003774SourceRange TagDecl::getSourceRange() const {
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003775 SourceLocation RBraceLoc = BraceRange.getEnd();
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003776 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003777 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003778}
3779
Rafael Espindola8db352d2013-10-17 15:37:26 +00003780TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00003781
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00003782void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer00350522015-08-31 18:48:39 +00003783 TypedefNameDeclOrQualifier = TDD;
Reid Klecknercae82a22014-04-23 22:03:04 +00003784 if (const Type *T = getTypeForDecl()) {
3785 (void)T;
Richard Smith5b21db82014-04-23 18:20:42 +00003786 assert(T->isLinkageValid());
Reid Klecknercae82a22014-04-23 22:03:04 +00003787 }
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003788 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00003789}
3790
Douglas Gregordee1be82009-01-17 00:42:38 +00003791void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003792 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00003793
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003794 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
Richard Smith053f6c62014-05-16 23:01:30 +00003795 struct CXXRecordDecl::DefinitionData *Data =
John McCall67da35c2010-02-04 22:26:26 +00003796 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00003797 for (auto I : redecls())
Richard Smith64c06302014-05-22 23:19:02 +00003798 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00003799 }
Douglas Gregordee1be82009-01-17 00:42:38 +00003800}
3801
3802void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00003803 assert((!isa<CXXRecordDecl>(this) ||
3804 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3805 "definition completed but not started");
3806
John McCallf937c022011-10-07 06:10:15 +00003807 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003808 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00003809
3810 if (ASTMutationListener *L = getASTMutationListener())
3811 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00003812}
3813
John McCallf937c022011-10-07 06:10:15 +00003814TagDecl *TagDecl::getDefinition() const {
3815 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003816 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003817
3818 // If it's possible for us to have an out-of-date definition, check now.
3819 if (MayHaveOutOfDateDef) {
3820 if (IdentifierInfo *II = getIdentifier()) {
3821 if (II->isOutOfDate()) {
3822 updateOutOfDate(*II);
3823 }
3824 }
3825 }
3826
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003827 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
Andrew Trickba266ee2010-10-19 21:54:32 +00003828 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003829
Aaron Ballman86c93902014-03-06 23:45:36 +00003830 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00003831 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00003832 return R;
Mike Stump11289f42009-09-09 15:08:12 +00003833
Craig Topper36250ad2014-05-12 05:36:57 +00003834 return nullptr;
Ted Kremenek21475702008-09-05 17:16:31 +00003835}
3836
Douglas Gregor14454802011-02-25 02:25:35 +00003837void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3838 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00003839 // Make sure the extended qualifier info is allocated.
3840 if (!hasExtInfo())
David Majnemer00350522015-08-31 18:48:39 +00003841 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00003842 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00003843 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003844 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00003845 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00003846 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00003847 if (getExtInfo()->NumTemplParamLists == 0) {
3848 getASTContext().Deallocate(getExtInfo());
David Majnemer00350522015-08-31 18:48:39 +00003849 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003850 }
3851 else
3852 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00003853 }
3854 }
3855}
3856
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003857void TagDecl::setTemplateParameterListsInfo(
3858 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
3859 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00003860 // Make sure the extended decl info is allocated.
3861 if (!hasExtInfo())
3862 // Allocate external info struct.
David Majnemer00350522015-08-31 18:48:39 +00003863 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003864 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003865 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00003866}
3867
Ted Kremenek21475702008-09-05 17:16:31 +00003868//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003869// EnumDecl Implementation
3870//===----------------------------------------------------------------------===//
3871
Eugene Zelenkode0215c2017-11-13 23:01:27 +00003872void EnumDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00003873
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003874EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3875 SourceLocation StartLoc, SourceLocation IdLoc,
3876 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00003877 EnumDecl *PrevDecl, bool IsScoped,
3878 bool IsScopedUsingClassTag, bool IsFixed) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003879 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
3880 IsScoped, IsScopedUsingClassTag, IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003881 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00003882 C.getTypeDeclType(Enum, PrevDecl);
3883 return Enum;
3884}
3885
Douglas Gregor72172e92012-01-05 21:55:30 +00003886EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003887 EnumDecl *Enum =
3888 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3889 nullptr, nullptr, false, false, false);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003890 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3891 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003892}
3893
Alp Tokerb9fa5122014-01-06 11:31:18 +00003894SourceRange EnumDecl::getIntegerTypeRange() const {
3895 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3896 return TI->getTypeLoc().getSourceRange();
3897 return SourceRange();
3898}
3899
Douglas Gregord5058122010-02-11 01:19:42 +00003900void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00003901 QualType NewPromotionType,
3902 unsigned NumPositiveBits,
3903 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00003904 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00003905 if (!IntegerType)
3906 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00003907 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00003908 setNumPositiveBits(NumPositiveBits);
3909 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00003910 TagDecl::completeDefinition();
3911}
3912
Akira Hatanaka3c268af2017-03-21 02:23:00 +00003913bool EnumDecl::isClosed() const {
3914 if (const auto *A = getAttr<EnumExtensibilityAttr>())
3915 return A->getExtensibility() == EnumExtensibilityAttr::Closed;
3916 return true;
3917}
3918
3919bool EnumDecl::isClosedFlag() const {
3920 return isClosed() && hasAttr<FlagEnumAttr>();
3921}
3922
3923bool EnumDecl::isClosedNonFlag() const {
3924 return isClosed() && !hasAttr<FlagEnumAttr>();
3925}
3926
Richard Smith7d137e32012-03-23 03:33:32 +00003927TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3928 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3929 return MSI->getTemplateSpecializationKind();
3930
3931 return TSK_Undeclared;
3932}
3933
3934void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3935 SourceLocation PointOfInstantiation) {
3936 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3937 assert(MSI && "Not an instantiated member enumeration?");
3938 MSI->setTemplateSpecializationKind(TSK);
3939 if (TSK != TSK_ExplicitSpecialization &&
3940 PointOfInstantiation.isValid() &&
3941 MSI->getPointOfInstantiation().isInvalid())
3942 MSI->setPointOfInstantiation(PointOfInstantiation);
3943}
3944
Richard Smith6739a102016-05-05 00:56:12 +00003945EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
3946 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
3947 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
3948 EnumDecl *ED = getInstantiatedFromMemberEnum();
3949 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
3950 ED = NewED;
Richard Smith2195ec92017-04-21 01:15:13 +00003951 return getDefinitionOrSelf(ED);
Richard Smith6739a102016-05-05 00:56:12 +00003952 }
3953 }
3954
3955 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
3956 "couldn't find pattern for enum instantiation");
3957 return nullptr;
3958}
3959
Richard Smith4b38ded2012-03-14 23:13:10 +00003960EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3961 if (SpecializationInfo)
3962 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3963
Craig Topper36250ad2014-05-12 05:36:57 +00003964 return nullptr;
Richard Smith4b38ded2012-03-14 23:13:10 +00003965}
3966
3967void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3968 TemplateSpecializationKind TSK) {
3969 assert(!SpecializationInfo && "Member enum is already a specialization");
3970 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3971}
3972
Richard Trieuab4d7302018-07-25 22:52:05 +00003973unsigned EnumDecl::getODRHash() {
3974 if (HasODRHash)
3975 return ODRHash;
3976
3977 class ODRHash Hash;
3978 Hash.AddEnumDecl(this);
3979 HasODRHash = true;
3980 ODRHash = Hash.CalculateHash();
3981 return ODRHash;
3982}
3983
Sebastian Redl833ef452010-01-26 22:01:41 +00003984//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003985// RecordDecl Implementation
3986//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003987
Richard Smith053f6c62014-05-16 23:01:30 +00003988RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3989 DeclContext *DC, SourceLocation StartLoc,
3990 SourceLocation IdLoc, IdentifierInfo *Id,
3991 RecordDecl *PrevDecl)
Eugene Zelenkode0215c2017-11-13 23:01:27 +00003992 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc),
3993 HasFlexibleArrayMember(false), AnonymousStructOrUnion(false),
3994 HasObjectMember(false), HasVolatileMember(false),
Akira Hatanaka7275da02018-02-28 07:15:55 +00003995 LoadedFieldsFromExternalStorage(false),
3996 NonTrivialToPrimitiveDefaultInitialize(false),
Akira Hatanakad791e922018-03-19 17:38:40 +00003997 NonTrivialToPrimitiveCopy(false), NonTrivialToPrimitiveDestroy(false),
Akira Hatanakae6313ac2018-04-09 22:48:22 +00003998 ParamDestroyedInCallee(false), ArgPassingRestrictions(APK_CanPassInRegs) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003999 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00004000}
4001
Jay Foad39c79802011-01-12 09:06:06 +00004002RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004003 SourceLocation StartLoc, SourceLocation IdLoc,
4004 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smith053f6c62014-05-16 23:01:30 +00004005 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
4006 StartLoc, IdLoc, Id, PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00004007 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
4008
Ted Kremenek21475702008-09-05 17:16:31 +00004009 C.getTypeDeclType(R, PrevDecl);
4010 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00004011}
4012
Douglas Gregor72172e92012-01-05 21:55:30 +00004013RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004014 RecordDecl *R =
4015 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
4016 SourceLocation(), nullptr, nullptr);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00004017 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
4018 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00004019}
4020
Douglas Gregordfcad112009-03-25 15:59:44 +00004021bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00004022 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00004023 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
4024}
4025
Alexey Bataev39c81e22014-08-28 04:28:19 +00004026bool RecordDecl::isLambda() const {
4027 if (auto RD = dyn_cast<CXXRecordDecl>(this))
4028 return RD->isLambda();
4029 return false;
4030}
4031
Alexey Bataev330de032014-10-29 12:21:55 +00004032bool RecordDecl::isCapturedRecord() const {
4033 return hasAttr<CapturedRecordAttr>();
4034}
4035
4036void RecordDecl::setCapturedRecord() {
4037 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
4038}
4039
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004040RecordDecl::field_iterator RecordDecl::field_begin() const {
4041 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
4042 LoadFieldsFromExternalStorage();
4043
4044 return field_iterator(decl_iterator(FirstDecl));
4045}
4046
Douglas Gregorb11aad82011-02-19 18:51:44 +00004047/// completeDefinition - Notes that the definition of this type is now
4048/// complete.
4049void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00004050 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00004051 TagDecl::completeDefinition();
4052}
4053
Eli Friedman9ee2d0472012-10-12 23:29:20 +00004054/// isMsStruct - Get whether or not this record uses ms_struct layout.
4055/// This which can be turned on with an attribute, pragma, or the
4056/// -mms-bitfields command-line option.
4057bool RecordDecl::isMsStruct(const ASTContext &C) const {
David Majnemer8ab003a2015-02-02 19:30:52 +00004058 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00004059}
4060
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004061void RecordDecl::LoadFieldsFromExternalStorage() const {
4062 ExternalASTSource *Source = getASTContext().getExternalSource();
4063 assert(hasExternalLexicalStorage() && Source && "No external storage?");
4064
4065 // Notify that we have a RecordDecl doing some initialization.
4066 ExternalASTSource::Deserializing TheFields(Source);
4067
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004068 SmallVector<Decl*, 64> Decls;
Richard Smith3cb15722015-08-05 22:41:45 +00004069 LoadedFieldsFromExternalStorage = true;
4070 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
4071 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
4072 }, Decls);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004073
4074#ifndef NDEBUG
4075 // Check that all decls we got were FieldDecls.
4076 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00004077 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004078#endif
4079
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004080 if (Decls.empty())
4081 return;
4082
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00004083 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00004084 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004085}
4086
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004087bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
4088 ASTContext &Context = getASTContext();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004089 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
4090 (SanitizerKind::Address | SanitizerKind::KernelAddress);
4091 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004092 return false;
Alexey Samsonov33e00e22014-10-16 23:50:26 +00004093 const auto &Blacklist = Context.getSanitizerBlacklist();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004094 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004095 // We may be able to relax some of these requirements.
4096 int ReasonToReject = -1;
4097 if (!CXXRD || CXXRD->isExternCContext())
4098 ReasonToReject = 0; // is not C++.
4099 else if (CXXRD->hasAttr<PackedAttr>())
4100 ReasonToReject = 1; // is packed.
4101 else if (CXXRD->isUnion())
4102 ReasonToReject = 2; // is a union.
4103 else if (CXXRD->isTriviallyCopyable())
4104 ReasonToReject = 3; // is trivially copyable.
4105 else if (CXXRD->hasTrivialDestructor())
4106 ReasonToReject = 4; // has trivial destructor.
4107 else if (CXXRD->isStandardLayout())
4108 ReasonToReject = 5; // is standard layout.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004109 else if (Blacklist.isBlacklistedLocation(EnabledAsanMask, getLocation(),
4110 "field-padding"))
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004111 ReasonToReject = 6; // is in a blacklisted file.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004112 else if (Blacklist.isBlacklistedType(EnabledAsanMask,
4113 getQualifiedNameAsString(),
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004114 "field-padding"))
4115 ReasonToReject = 7; // is blacklisted.
4116
4117 if (EmitRemark) {
4118 if (ReasonToReject >= 0)
4119 Context.getDiagnostics().Report(
4120 getLocation(),
4121 diag::remark_sanitize_address_insert_extra_padding_rejected)
4122 << getQualifiedNameAsString() << ReasonToReject;
4123 else
4124 Context.getDiagnostics().Report(
4125 getLocation(),
4126 diag::remark_sanitize_address_insert_extra_padding_accepted)
4127 << getQualifiedNameAsString();
4128 }
4129 return ReasonToReject < 0;
4130}
4131
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004132const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
4133 for (const auto *I : fields()) {
4134 if (I->getIdentifier())
4135 return I;
4136
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004137 if (const auto *RT = I->getType()->getAs<RecordType>())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004138 if (const FieldDecl *NamedDataMember =
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004139 RT->getDecl()->findFirstNamedDataMember())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004140 return NamedDataMember;
4141 }
4142
4143 // We didn't find a named data member.
4144 return nullptr;
4145}
4146
Steve Naroff415d3d52008-10-08 17:01:13 +00004147//===----------------------------------------------------------------------===//
4148// BlockDecl Implementation
4149//===----------------------------------------------------------------------===//
4150
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004151void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00004152 assert(!ParamInfo && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00004153
Steve Naroffc4b30e52009-03-13 16:56:44 +00004154 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00004155 if (!NewParamInfo.empty()) {
4156 NumParams = NewParamInfo.size();
4157 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
4158 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00004159 }
4160}
4161
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004162void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4163 bool CapturesCXXThis) {
4164 this->CapturesCXXThis = CapturesCXXThis;
4165 this->NumCaptures = Captures.size();
John McCallc63de662011-02-02 13:00:07 +00004166
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004167 if (Captures.empty()) {
4168 this->Captures = nullptr;
John McCallc63de662011-02-02 13:00:07 +00004169 return;
4170 }
4171
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004172 this->Captures = Captures.copy(Context).data();
Steve Naroffc4b30e52009-03-13 16:56:44 +00004173}
Sebastian Redl833ef452010-01-26 22:01:41 +00004174
John McCallce45f882011-06-15 22:51:16 +00004175bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00004176 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00004177 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00004178 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00004179 return true;
4180
4181 return false;
4182}
4183
Douglas Gregor70226da2010-12-21 16:27:07 +00004184SourceRange BlockDecl::getSourceRange() const {
4185 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
4186}
Sebastian Redl833ef452010-01-26 22:01:41 +00004187
4188//===----------------------------------------------------------------------===//
4189// Other Decl Allocation/Deallocation Method Implementations
4190//===----------------------------------------------------------------------===//
4191
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004192void TranslationUnitDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004193
Sebastian Redl833ef452010-01-26 22:01:41 +00004194TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Craig Topper36250ad2014-05-12 05:36:57 +00004195 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00004196}
4197
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004198void PragmaCommentDecl::anchor() {}
Nico Weber66220292016-03-02 17:28:48 +00004199
4200PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4201 TranslationUnitDecl *DC,
4202 SourceLocation CommentLoc,
4203 PragmaMSCommentKind CommentKind,
4204 StringRef Arg) {
4205 PragmaCommentDecl *PCD =
4206 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4207 PragmaCommentDecl(DC, CommentLoc, CommentKind);
4208 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4209 PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4210 return PCD;
4211}
4212
4213PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4214 unsigned ID,
4215 unsigned ArgSize) {
4216 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
4217 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
4218}
4219
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004220void PragmaDetectMismatchDecl::anchor() {}
Nico Webercbbaeb12016-03-02 19:28:54 +00004221
4222PragmaDetectMismatchDecl *
4223PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4224 SourceLocation Loc, StringRef Name,
4225 StringRef Value) {
4226 size_t ValueStart = Name.size() + 1;
4227 PragmaDetectMismatchDecl *PDMD =
4228 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4229 PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4230 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4231 PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4232 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4233 Value.size());
4234 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4235 return PDMD;
4236}
4237
4238PragmaDetectMismatchDecl *
4239PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4240 unsigned NameValueSize) {
4241 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4242 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4243}
Nico Weber66220292016-03-02 17:28:48 +00004244
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004245void ExternCContextDecl::anchor() {}
Richard Smithf19e1272015-03-07 00:04:49 +00004246
4247ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4248 TranslationUnitDecl *DC) {
4249 return new (C, DC) ExternCContextDecl(DC);
4250}
4251
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004252void LabelDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004253
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004254LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004255 SourceLocation IdentL, IdentifierInfo *II) {
Craig Topper36250ad2014-05-12 05:36:57 +00004256 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004257}
4258
4259LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4260 SourceLocation IdentL, IdentifierInfo *II,
4261 SourceLocation GnuLabelL) {
4262 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Craig Topper36250ad2014-05-12 05:36:57 +00004263 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004264}
4265
Douglas Gregor72172e92012-01-05 21:55:30 +00004266LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004267 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
4268 SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00004269}
4270
Ehsan Akhgari31097582014-09-22 02:21:54 +00004271void LabelDecl::setMSAsmLabel(StringRef Name) {
4272 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
4273 memcpy(Buffer, Name.data(), Name.size());
4274 Buffer[Name.size()] = '\0';
4275 MSAsmName = Buffer;
4276}
4277
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004278void ValueDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004279
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004280bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00004281 for (const auto *I : attrs())
4282 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004283 return true;
4284
4285 return isWeakImported();
4286}
4287
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004288void ImplicitParamDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004289
Sebastian Redl833ef452010-01-26 22:01:41 +00004290ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004291 SourceLocation IdLoc,
Alexey Bataev56223232017-06-09 13:40:18 +00004292 IdentifierInfo *Id, QualType Type,
4293 ImplicitParamKind ParamKind) {
4294 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
4295}
4296
4297ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
4298 ImplicitParamKind ParamKind) {
4299 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
Sebastian Redl833ef452010-01-26 22:01:41 +00004300}
4301
Richard Smithf7981722013-11-22 09:01:48 +00004302ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004303 unsigned ID) {
Alexey Bataev56223232017-06-09 13:40:18 +00004304 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
Douglas Gregor72172e92012-01-05 21:55:30 +00004305}
4306
Sebastian Redl833ef452010-01-26 22:01:41 +00004307FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004308 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004309 const DeclarationNameInfo &NameInfo,
4310 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004311 StorageClass SC,
Richard Smithf7981722013-11-22 09:01:48 +00004312 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00004313 bool hasWrittenPrototype,
4314 bool isConstexprSpecified) {
Richard Smithf7981722013-11-22 09:01:48 +00004315 FunctionDecl *New =
Richard Smith053f6c62014-05-16 23:01:30 +00004316 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
4317 SC, isInlineSpecified, isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00004318 New->HasWrittenPrototype = hasWrittenPrototype;
4319 return New;
4320}
4321
Douglas Gregor72172e92012-01-05 21:55:30 +00004322FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004323 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004324 DeclarationNameInfo(), QualType(), nullptr,
Richard Smithf7981722013-11-22 09:01:48 +00004325 SC_None, false, false);
Douglas Gregor72172e92012-01-05 21:55:30 +00004326}
4327
Sebastian Redl833ef452010-01-26 22:01:41 +00004328BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004329 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00004330}
4331
Douglas Gregor72172e92012-01-05 21:55:30 +00004332BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004333 return new (C, ID) BlockDecl(nullptr, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00004334}
4335
Chandler Carruth21c90602015-12-30 03:24:14 +00004336CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
4337 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4338 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
4339
Ben Langmuir37943a72013-05-03 19:00:33 +00004340CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
4341 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004342 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Richard Smithf7981722013-11-22 09:01:48 +00004343 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004344}
4345
Ben Langmuirce914fc2013-05-03 19:20:19 +00004346CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00004347 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004348 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Craig Topper36250ad2014-05-12 05:36:57 +00004349 CapturedDecl(nullptr, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00004350}
4351
Chandler Carruth21c90602015-12-30 03:24:14 +00004352Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4353void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4354
4355bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4356void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4357
Sebastian Redl833ef452010-01-26 22:01:41 +00004358EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4359 SourceLocation L,
4360 IdentifierInfo *Id, QualType T,
4361 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00004362 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00004363}
4364
Douglas Gregor72172e92012-01-05 21:55:30 +00004365EnumConstantDecl *
4366EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004367 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4368 QualType(), nullptr, llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00004369}
4370
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004371void IndirectFieldDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004372
Richard Smith9f951822016-01-06 22:49:11 +00004373IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4374 SourceLocation L, DeclarationName N,
David Majnemer59f77922016-06-24 04:05:48 +00004375 QualType T,
4376 MutableArrayRef<NamedDecl *> CH)
4377 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4378 ChainingSize(CH.size()) {
Richard Smith9f951822016-01-06 22:49:11 +00004379 // In C++, indirect field declarations conflict with tag declarations in the
4380 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4381 if (C.getLangOpts().CPlusPlus)
4382 IdentifierNamespace |= IDNS_Tag;
4383}
4384
Benjamin Kramer39593702010-11-21 14:11:41 +00004385IndirectFieldDecl *
4386IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
David Majnemer59f77922016-06-24 04:05:48 +00004387 IdentifierInfo *Id, QualType T,
4388 llvm::MutableArrayRef<NamedDecl *> CH) {
4389 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
Francois Pichet783dd6e2010-11-21 06:08:52 +00004390}
4391
Douglas Gregor72172e92012-01-05 21:55:30 +00004392IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4393 unsigned ID) {
Richard Smith9f951822016-01-06 22:49:11 +00004394 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
David Majnemer59f77922016-06-24 04:05:48 +00004395 DeclarationName(), QualType(), None);
Douglas Gregor72172e92012-01-05 21:55:30 +00004396}
4397
Douglas Gregorbe996932010-09-01 20:41:53 +00004398SourceRange EnumConstantDecl::getSourceRange() const {
4399 SourceLocation End = getLocation();
4400 if (Init)
4401 End = Init->getLocEnd();
4402 return SourceRange(getLocation(), End);
4403}
4404
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004405void TypeDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004406
Sebastian Redl833ef452010-01-26 22:01:41 +00004407TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00004408 SourceLocation StartLoc, SourceLocation IdLoc,
4409 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004410 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00004411}
4412
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004413void TypedefNameDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004414
Richard Smith42413142015-05-15 20:05:43 +00004415TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4416 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4417 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4418 auto *ThisTypedef = this;
4419 if (AnyRedecl && OwningTypedef) {
4420 OwningTypedef = OwningTypedef->getCanonicalDecl();
4421 ThisTypedef = ThisTypedef->getCanonicalDecl();
4422 }
4423 if (OwningTypedef == ThisTypedef)
Richard Smitha5230222015-03-27 01:37:43 +00004424 return TT->getDecl();
Richard Smith42413142015-05-15 20:05:43 +00004425 }
Richard Smitha5230222015-03-27 01:37:43 +00004426
4427 return nullptr;
4428}
4429
Argyrios Kyrtzidis3b25c912017-03-21 16:56:02 +00004430bool TypedefNameDecl::isTransparentTagSlow() const {
4431 auto determineIsTransparent = [&]() {
4432 if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
4433 if (auto *TD = TT->getDecl()) {
4434 if (TD->getName() != getName())
4435 return false;
4436 SourceLocation TTLoc = getLocation();
4437 SourceLocation TDLoc = TD->getLocation();
4438 if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
4439 return false;
4440 SourceManager &SM = getASTContext().getSourceManager();
4441 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
4442 }
4443 }
4444 return false;
4445 };
4446
4447 bool isTransparent = determineIsTransparent();
Benjamin Kramerdfb730a2018-01-26 14:14:11 +00004448 MaybeModedTInfo.setInt((isTransparent << 1) | 1);
Argyrios Kyrtzidis3b25c912017-03-21 16:56:02 +00004449 return isTransparent;
4450}
4451
Douglas Gregor72172e92012-01-05 21:55:30 +00004452TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004453 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004454 nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004455}
4456
Richard Smithdda56e42011-04-15 14:24:37 +00004457TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4458 SourceLocation StartLoc,
4459 SourceLocation IdLoc, IdentifierInfo *Id,
4460 TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004461 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00004462}
4463
Douglas Gregor72172e92012-01-05 21:55:30 +00004464TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004465 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
4466 SourceLocation(), nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004467}
4468
Abramo Bagnaraea947882011-03-08 16:41:52 +00004469SourceRange TypedefDecl::getSourceRange() const {
4470 SourceLocation RangeEnd = getLocation();
4471 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4472 if (typeIsPostfix(TInfo->getType()))
4473 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4474 }
4475 return SourceRange(getLocStart(), RangeEnd);
4476}
4477
Richard Smithdda56e42011-04-15 14:24:37 +00004478SourceRange TypeAliasDecl::getSourceRange() const {
4479 SourceLocation RangeEnd = getLocStart();
4480 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4481 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4482 return SourceRange(getLocStart(), RangeEnd);
4483}
4484
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004485void FileScopeAsmDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004486
Sebastian Redl833ef452010-01-26 22:01:41 +00004487FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00004488 StringLiteral *Str,
4489 SourceLocation AsmLoc,
4490 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00004491 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00004492}
Douglas Gregorba345522011-12-02 23:23:56 +00004493
Richard Smithf7981722013-11-22 09:01:48 +00004494FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004495 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004496 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4497 SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00004498}
4499
Michael Han84324352013-02-22 17:15:32 +00004500void EmptyDecl::anchor() {}
4501
4502EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004503 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00004504}
4505
4506EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004507 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00004508}
4509
Douglas Gregorba345522011-12-02 23:23:56 +00004510//===----------------------------------------------------------------------===//
4511// ImportDecl Implementation
4512//===----------------------------------------------------------------------===//
4513
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004514/// Retrieve the number of module identifiers needed to name the given
Douglas Gregorba345522011-12-02 23:23:56 +00004515/// module.
4516static unsigned getNumModuleIdentifiers(Module *Mod) {
4517 unsigned Result = 1;
4518 while (Mod->Parent) {
4519 Mod = Mod->Parent;
4520 ++Result;
4521 }
4522 return Result;
4523}
4524
Douglas Gregor22d09742012-01-03 18:04:46 +00004525ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004526 Module *Imported,
4527 ArrayRef<SourceLocation> IdentifierLocs)
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004528 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true) {
Douglas Gregorba345522011-12-02 23:23:56 +00004529 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004530 auto *StoredLocs = getTrailingObjects<SourceLocation>();
James Y Knight7a22b242015-08-06 20:26:32 +00004531 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4532 StoredLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004533}
4534
Douglas Gregor22d09742012-01-03 18:04:46 +00004535ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004536 Module *Imported, SourceLocation EndLoc)
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004537 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false) {
James Y Knight7a22b242015-08-06 20:26:32 +00004538 *getTrailingObjects<SourceLocation>() = EndLoc;
Douglas Gregorba345522011-12-02 23:23:56 +00004539}
4540
Richard Smithf7981722013-11-22 09:01:48 +00004541ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004542 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004543 ArrayRef<SourceLocation> IdentifierLocs) {
James Y Knight7a22b242015-08-06 20:26:32 +00004544 return new (C, DC,
4545 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
Richard Smithf7981722013-11-22 09:01:48 +00004546 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004547}
4548
Richard Smithf7981722013-11-22 09:01:48 +00004549ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004550 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00004551 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004552 SourceLocation EndLoc) {
James Y Knight7a22b242015-08-06 20:26:32 +00004553 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
4554 ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00004555 Import->setImplicit();
4556 return Import;
4557}
4558
Douglas Gregor72172e92012-01-05 21:55:30 +00004559ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4560 unsigned NumLocations) {
James Y Knight7a22b242015-08-06 20:26:32 +00004561 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
Richard Smithf7981722013-11-22 09:01:48 +00004562 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00004563}
4564
4565ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4566 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004567 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00004568
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004569 const auto *StoredLocs = getTrailingObjects<SourceLocation>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00004570 return llvm::makeArrayRef(StoredLocs,
4571 getNumModuleIdentifiers(getImportedModule()));
Douglas Gregorba345522011-12-02 23:23:56 +00004572}
4573
4574SourceRange ImportDecl::getSourceRange() const {
4575 if (!ImportedAndComplete.getInt())
James Y Knight7a22b242015-08-06 20:26:32 +00004576 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
4577
Douglas Gregorba345522011-12-02 23:23:56 +00004578 return SourceRange(getLocation(), getIdentifierLocs().back());
4579}
Richard Smith8df390f2016-09-08 23:14:54 +00004580
4581//===----------------------------------------------------------------------===//
4582// ExportDecl Implementation
4583//===----------------------------------------------------------------------===//
4584
4585void ExportDecl::anchor() {}
4586
4587ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
4588 SourceLocation ExportLoc) {
4589 return new (C, DC) ExportDecl(DC, ExportLoc);
4590}
4591
4592ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4593 return new (C, ID) ExportDecl(nullptr, SourceLocation());
4594}