blob: 6e4f9b99478fcc44ff757409c8a246b445651de7 [file] [log] [blame]
Douglas Gregord7e7a512009-03-17 21:15:40 +00001//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Douglas Gregord7e7a512009-03-17 21:15:40 +00006//===----------------------------------------------------------------------===/
7//
8// This file implements C++ template instantiation for declarations.
9//
10//===----------------------------------------------------------------------===/
John McCall83024632010-08-25 22:03:47 +000011#include "clang/Sema/SemaInternal.h"
Douglas Gregor28ad4b52009-05-26 20:50:29 +000012#include "clang/AST/ASTConsumer.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000013#include "clang/AST/ASTContext.h"
Richard Smithd28ac5b2014-03-22 23:33:22 +000014#include "clang/AST/ASTMutationListener.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000015#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/DeclVisitor.h"
John McCallc62bb642010-03-24 05:22:00 +000017#include "clang/AST/DependentDiagnostic.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000018#include "clang/AST/Expr.h"
Douglas Gregor6131b442009-12-12 18:16:41 +000019#include "clang/AST/ExprCXX.h"
Jordan Rose1e879d82018-03-23 00:07:18 +000020#include "clang/AST/PrettyDeclStackTrace.h"
John McCall58f10c32010-03-11 09:03:00 +000021#include "clang/AST/TypeLoc.h"
Richard Smith3997b1b2016-08-12 01:55:21 +000022#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Sema/Lookup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/Template.h"
Gabor Horvath207e7b12018-02-10 14:04:45 +000025#include "clang/Sema/TemplateInstCallback.h"
Anton Afanasyevd880de22019-03-30 08:42:48 +000026#include "llvm/Support/TimeProfiler.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000027
28using namespace clang;
29
David Majnemer192d1792013-11-27 08:20:38 +000030static bool isDeclWithinFunction(const Decl *D) {
31 const DeclContext *DC = D->getDeclContext();
32 if (DC->isFunctionOrMethod())
33 return true;
34
35 if (DC->isRecord())
36 return cast<CXXRecordDecl>(DC)->isLocalClass();
37
38 return false;
39}
40
Richard Smithcc928662014-10-17 20:37:29 +000041template<typename DeclT>
42static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
43 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor14454802011-02-25 02:25:35 +000044 if (!OldDecl->getQualifierLoc())
45 return false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000046
Richard Smithcc928662014-10-17 20:37:29 +000047 assert((NewDecl->getFriendObjectKind() ||
48 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
49 "non-friend with qualified name defined in dependent context");
50 Sema::ContextRAII SavedContext(
51 SemaRef,
52 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
53 ? NewDecl->getLexicalDeclContext()
54 : OldDecl->getLexicalDeclContext()));
55
Douglas Gregor14454802011-02-25 02:25:35 +000056 NestedNameSpecifierLoc NewQualifierLoc
Richard Smithcc928662014-10-17 20:37:29 +000057 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
58 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000059
Douglas Gregor14454802011-02-25 02:25:35 +000060 if (!NewQualifierLoc)
John McCall3e11ebe2010-03-15 10:12:16 +000061 return true;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000062
Douglas Gregor14454802011-02-25 02:25:35 +000063 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +000064 return false;
65}
66
Richard Smithcc928662014-10-17 20:37:29 +000067bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
68 DeclaratorDecl *NewDecl) {
69 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
70}
71
John McCall3e11ebe2010-03-15 10:12:16 +000072bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
73 TagDecl *NewDecl) {
Richard Smithcc928662014-10-17 20:37:29 +000074 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
John McCall3e11ebe2010-03-15 10:12:16 +000075}
76
DeLesley Hutchinsceec3062012-01-20 22:37:06 +000077// Include attribute instantiation code.
78#include "clang/Sema/AttrTemplateInstantiate.inc"
79
Richard Smith44c247f2013-02-22 08:32:16 +000080static void instantiateDependentAlignedAttr(
81 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
82 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
83 if (Aligned->isAlignmentExpr()) {
84 // The alignment expression is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +000085 EnterExpressionEvaluationContext Unevaluated(
86 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Richard Smith44c247f2013-02-22 08:32:16 +000087 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
88 if (!Result.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +000089 S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
Richard Smith44c247f2013-02-22 08:32:16 +000090 Aligned->getSpellingListIndex(), IsPackExpansion);
91 } else {
92 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
93 TemplateArgs, Aligned->getLocation(),
94 DeclarationName());
95 if (Result)
96 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
97 Aligned->getSpellingListIndex(), IsPackExpansion);
98 }
99}
100
101static void instantiateDependentAlignedAttr(
102 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
103 const AlignedAttr *Aligned, Decl *New) {
104 if (!Aligned->isPackExpansion()) {
105 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
106 return;
107 }
108
109 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
110 if (Aligned->isAlignmentExpr())
111 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
112 Unexpanded);
113 else
114 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
115 Unexpanded);
116 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
117
118 // Determine whether we can expand this attribute pack yet.
119 bool Expand = true, RetainExpansion = false;
120 Optional<unsigned> NumExpansions;
121 // FIXME: Use the actual location of the ellipsis.
122 SourceLocation EllipsisLoc = Aligned->getLocation();
123 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
124 Unexpanded, TemplateArgs, Expand,
125 RetainExpansion, NumExpansions))
126 return;
127
128 if (!Expand) {
129 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
130 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
131 } else {
132 for (unsigned I = 0; I != *NumExpansions; ++I) {
133 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
134 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
135 }
136 }
137}
138
Hal Finkelee90a222014-09-26 05:04:30 +0000139static void instantiateDependentAssumeAlignedAttr(
140 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
141 const AssumeAlignedAttr *Aligned, Decl *New) {
142 // The alignment expression is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +0000143 EnterExpressionEvaluationContext Unevaluated(
144 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Hal Finkelee90a222014-09-26 05:04:30 +0000145
146 Expr *E, *OE = nullptr;
147 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
148 if (Result.isInvalid())
149 return;
150 E = Result.getAs<Expr>();
151
152 if (Aligned->getOffset()) {
153 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
154 if (Result.isInvalid())
155 return;
156 OE = Result.getAs<Expr>();
157 }
158
159 S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE,
160 Aligned->getSpellingListIndex());
161}
162
Hal Finkel1b0d24e2014-10-02 21:21:25 +0000163static void instantiateDependentAlignValueAttr(
164 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
165 const AlignValueAttr *Aligned, Decl *New) {
166 // The alignment expression is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +0000167 EnterExpressionEvaluationContext Unevaluated(
168 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Hal Finkel1b0d24e2014-10-02 21:21:25 +0000169 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
170 if (!Result.isInvalid())
171 S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
172 Aligned->getSpellingListIndex());
173}
174
Erich Keane623efd82017-03-30 21:48:55 +0000175static void instantiateDependentAllocAlignAttr(
176 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
177 const AllocAlignAttr *Align, Decl *New) {
178 Expr *Param = IntegerLiteral::Create(
Joel E. Denny81508102018-03-13 14:51:22 +0000179 S.getASTContext(),
180 llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
Erich Keane623efd82017-03-30 21:48:55 +0000181 S.getASTContext().UnsignedLongLongTy, Align->getLocation());
182 S.AddAllocAlignAttr(Align->getLocation(), New, Param,
183 Align->getSpellingListIndex());
184}
185
George Burgess IV177399e2017-01-09 04:12:14 +0000186static Expr *instantiateDependentFunctionAttrCondition(
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000187 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
George Burgess IV177399e2017-01-09 04:12:14 +0000188 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000189 Expr *Cond = nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000190 {
George Burgess IV177399e2017-01-09 04:12:14 +0000191 Sema::ContextRAII SwitchContext(S, New);
Faisal Valid143a0c2017-04-01 21:30:49 +0000192 EnterExpressionEvaluationContext Unevaluated(
193 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
George Burgess IV177399e2017-01-09 04:12:14 +0000194 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000195 if (Result.isInvalid())
George Burgess IV177399e2017-01-09 04:12:14 +0000196 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000197 Cond = Result.getAs<Expr>();
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000198 }
George Burgess IV00431952016-11-17 01:33:54 +0000199 if (!Cond->isTypeDependent()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000200 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
201 if (Converted.isInvalid())
George Burgess IV177399e2017-01-09 04:12:14 +0000202 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000203 Cond = Converted.get();
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000204 }
205
206 SmallVector<PartialDiagnosticAt, 8> Diags;
George Burgess IV177399e2017-01-09 04:12:14 +0000207 if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
208 !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
209 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
210 for (const auto &P : Diags)
211 S.Diag(P.first, P.second);
212 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000213 }
George Burgess IV177399e2017-01-09 04:12:14 +0000214 return Cond;
215}
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000216
George Burgess IV177399e2017-01-09 04:12:14 +0000217static void instantiateDependentEnableIfAttr(
218 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
219 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
220 Expr *Cond = instantiateDependentFunctionAttrCondition(
221 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
222
223 if (Cond)
224 New->addAttr(new (S.getASTContext()) EnableIfAttr(
225 EIA->getLocation(), S.getASTContext(), Cond, EIA->getMessage(),
226 EIA->getSpellingListIndex()));
227}
228
229static void instantiateDependentDiagnoseIfAttr(
230 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
231 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
232 Expr *Cond = instantiateDependentFunctionAttrCondition(
233 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
234
235 if (Cond)
236 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
237 DIA->getLocation(), S.getASTContext(), Cond, DIA->getMessage(),
238 DIA->getDiagnosticType(), DIA->getArgDependent(), New,
239 DIA->getSpellingListIndex()));
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000240}
241
Artem Belevich7093e402015-04-21 22:55:54 +0000242// Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
243// template A as the base and arguments from TemplateArgs.
244static void instantiateDependentCUDALaunchBoundsAttr(
245 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
246 const CUDALaunchBoundsAttr &Attr, Decl *New) {
247 // The alignment expression is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +0000248 EnterExpressionEvaluationContext Unevaluated(
249 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Artem Belevich7093e402015-04-21 22:55:54 +0000250
251 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
252 if (Result.isInvalid())
253 return;
254 Expr *MaxThreads = Result.getAs<Expr>();
255
256 Expr *MinBlocks = nullptr;
257 if (Attr.getMinBlocks()) {
258 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
259 if (Result.isInvalid())
260 return;
261 MinBlocks = Result.getAs<Expr>();
262 }
263
264 S.AddLaunchBoundsAttr(Attr.getLocation(), New, MaxThreads, MinBlocks,
265 Attr.getSpellingListIndex());
266}
267
Denis Zobnind9e2dcd2016-02-02 13:50:39 +0000268static void
269instantiateDependentModeAttr(Sema &S,
270 const MultiLevelTemplateArgumentList &TemplateArgs,
271 const ModeAttr &Attr, Decl *New) {
272 S.AddModeAttr(Attr.getRange(), New, Attr.getMode(),
273 Attr.getSpellingListIndex(), /*InInstantiation=*/true);
274}
275
Alexey Bataev2af33e32016-04-07 12:45:37 +0000276/// Instantiation of 'declare simd' attribute and its arguments.
277static void instantiateOMPDeclareSimdDeclAttr(
278 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
279 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +0000280 // Allow 'this' in clauses with varlists.
281 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
282 New = FTD->getTemplatedDecl();
283 auto *FD = cast<FunctionDecl>(New);
284 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
Alexey Bataevecba70f2016-04-12 11:02:11 +0000285 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
286 SmallVector<unsigned, 4> LinModifiers;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +0000287
Richard Smith715f7a12019-06-11 17:50:32 +0000288 auto SubstExpr = [&](Expr *E) -> ExprResult {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +0000289 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
290 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
291 Sema::ContextRAII SavedContext(S, FD);
292 LocalInstantiationScope Local(S);
293 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
294 Local.InstantiatedLocal(
295 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
296 return S.SubstExpr(E, TemplateArgs);
297 }
Mikael Nilsson9d2872d2018-12-13 10:15:27 +0000298 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
Alexey Bataeve48a5fc2016-04-12 05:28:34 +0000299 FD->isCXXInstanceMember());
300 return S.SubstExpr(E, TemplateArgs);
301 };
302
Richard Smith715f7a12019-06-11 17:50:32 +0000303 // Substitute a single OpenMP clause, which is a potentially-evaluated
304 // full-expression.
305 auto Subst = [&](Expr *E) -> ExprResult {
306 EnterExpressionEvaluationContext Evaluated(
307 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
308 ExprResult Res = SubstExpr(E);
309 if (Res.isInvalid())
310 return Res;
311 return S.ActOnFinishFullExpr(Res.get(), false);
312 };
313
Alexey Bataevecba70f2016-04-12 11:02:11 +0000314 ExprResult Simdlen;
315 if (auto *E = Attr.getSimdlen())
316 Simdlen = Subst(E);
317
Alexey Bataeve48a5fc2016-04-12 05:28:34 +0000318 if (Attr.uniforms_size() > 0) {
319 for(auto *E : Attr.uniforms()) {
320 ExprResult Inst = Subst(E);
321 if (Inst.isInvalid())
322 continue;
323 Uniforms.push_back(Inst.get());
324 }
Alexey Bataev2af33e32016-04-07 12:45:37 +0000325 }
326
Alexey Bataevd93d3762016-04-12 09:35:56 +0000327 auto AI = Attr.alignments_begin();
328 for (auto *E : Attr.aligneds()) {
329 ExprResult Inst = Subst(E);
330 if (Inst.isInvalid())
331 continue;
332 Aligneds.push_back(Inst.get());
333 Inst = ExprEmpty();
334 if (*AI)
335 Inst = S.SubstExpr(*AI, TemplateArgs);
336 Alignments.push_back(Inst.get());
337 ++AI;
338 }
Alexey Bataevecba70f2016-04-12 11:02:11 +0000339
340 auto SI = Attr.steps_begin();
341 for (auto *E : Attr.linears()) {
342 ExprResult Inst = Subst(E);
343 if (Inst.isInvalid())
344 continue;
345 Linears.push_back(Inst.get());
346 Inst = ExprEmpty();
347 if (*SI)
348 Inst = S.SubstExpr(*SI, TemplateArgs);
349 Steps.push_back(Inst.get());
350 ++SI;
351 }
352 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
Alexey Bataevd93d3762016-04-12 09:35:56 +0000353 (void)S.ActOnOpenMPDeclareSimdDirective(
354 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
Alexey Bataevecba70f2016-04-12 11:02:11 +0000355 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
356 Attr.getRange());
Alexey Bataev2af33e32016-04-07 12:45:37 +0000357}
358
Michael Liao7557afa2019-02-26 18:49:36 +0000359static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
360 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
361 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
362 // Both min and max expression are constant expressions.
363 EnterExpressionEvaluationContext Unevaluated(
364 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
365
366 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
367 if (Result.isInvalid())
368 return;
369 Expr *MinExpr = Result.getAs<Expr>();
370
371 Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
372 if (Result.isInvalid())
373 return;
374 Expr *MaxExpr = Result.getAs<Expr>();
375
376 S.addAMDGPUFlatWorkGroupSizeAttr(Attr.getLocation(), New, MinExpr, MaxExpr,
377 Attr.getSpellingListIndex());
378}
379
Richard Smith76b90272019-05-09 03:59:21 +0000380static ExplicitSpecifier
381instantiateExplicitSpecifier(Sema &S,
382 const MultiLevelTemplateArgumentList &TemplateArgs,
383 ExplicitSpecifier ES, FunctionDecl *New) {
384 if (!ES.getExpr())
385 return ES;
386 Expr *OldCond = ES.getExpr();
387 Expr *Cond = nullptr;
388 {
389 EnterExpressionEvaluationContext Unevaluated(
390 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
391 ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs);
392 if (SubstResult.isInvalid()) {
393 return ExplicitSpecifier::Invalid();
394 }
395 Cond = SubstResult.get();
396 }
397 ExplicitSpecifier Result(Cond, ES.getKind());
398 if (!Cond->isTypeDependent())
399 S.tryResolveExplicitSpecifier(Result);
400 return Result;
401}
402
Michael Liao7557afa2019-02-26 18:49:36 +0000403static void instantiateDependentAMDGPUWavesPerEUAttr(
404 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
405 const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
406 // Both min and max expression are constant expressions.
407 EnterExpressionEvaluationContext Unevaluated(
408 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
409
410 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
411 if (Result.isInvalid())
412 return;
413 Expr *MinExpr = Result.getAs<Expr>();
414
415 Expr *MaxExpr = nullptr;
416 if (auto Max = Attr.getMax()) {
417 Result = S.SubstExpr(Max, TemplateArgs);
418 if (Result.isInvalid())
419 return;
420 MaxExpr = Result.getAs<Expr>();
421 }
422
423 S.addAMDGPUWavesPerEUAttr(Attr.getLocation(), New, MinExpr, MaxExpr,
424 Attr.getSpellingListIndex());
425}
426
Erich Keanea32910d2017-03-23 18:51:54 +0000427void Sema::InstantiateAttrsForDecl(
428 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
429 Decl *New, LateInstantiatedAttrVec *LateAttrs,
430 LocalInstantiationScope *OuterMostScope) {
431 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
432 for (const auto *TmplAttr : Tmpl->attrs()) {
433 // FIXME: If any of the special case versions from InstantiateAttrs become
434 // applicable to template declaration, we'll need to add them here.
435 CXXThisScopeRAII ThisScope(
436 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
Mikael Nilsson9d2872d2018-12-13 10:15:27 +0000437 Qualifiers(), ND->isCXXInstanceMember());
Erich Keanea32910d2017-03-23 18:51:54 +0000438
439 Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
440 TmplAttr, Context, *this, TemplateArgs);
Richard Smith33bddbd2018-01-04 23:42:29 +0000441 if (NewAttr)
Erich Keanea32910d2017-03-23 18:51:54 +0000442 New->addAttr(NewAttr);
443 }
444 }
445}
446
George Karpenkov1657f362018-11-30 02:18:37 +0000447static Sema::RetainOwnershipKind
448attrToRetainOwnershipKind(const Attr *A) {
449 switch (A->getKind()) {
450 case clang::attr::CFConsumed:
451 return Sema::RetainOwnershipKind::CF;
452 case clang::attr::OSConsumed:
453 return Sema::RetainOwnershipKind::OS;
454 case clang::attr::NSConsumed:
455 return Sema::RetainOwnershipKind::NS;
456 default:
457 llvm_unreachable("Wrong argument supplied");
458 }
459}
460
John McCall6602bb12010-08-01 02:01:53 +0000461void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000462 const Decl *Tmpl, Decl *New,
463 LateInstantiatedAttrVec *LateAttrs,
464 LocalInstantiationScope *OuterMostScope) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000465 for (const auto *TmplAttr : Tmpl->attrs()) {
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000466 // FIXME: This should be generalized to more than just the AlignedAttr.
Richard Smith44c247f2013-02-22 08:32:16 +0000467 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
468 if (Aligned && Aligned->isAlignmentDependent()) {
469 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
470 continue;
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000471 }
472
Erich Keane23384a12019-08-23 15:58:35 +0000473 if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
Hal Finkelee90a222014-09-26 05:04:30 +0000474 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
475 continue;
476 }
477
Erich Keane23384a12019-08-23 15:58:35 +0000478 if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
Hal Finkel1b0d24e2014-10-02 21:21:25 +0000479 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
480 continue;
481 }
482
Erich Keane623efd82017-03-30 21:48:55 +0000483 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
484 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
485 continue;
486 }
487
488
George Burgess IV00431952016-11-17 01:33:54 +0000489 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000490 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
George Burgess IV177399e2017-01-09 04:12:14 +0000491 cast<FunctionDecl>(New));
492 continue;
493 }
494
495 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
496 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
497 cast<FunctionDecl>(New));
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000498 continue;
499 }
500
Erich Keane23384a12019-08-23 15:58:35 +0000501 if (const auto *CUDALaunchBounds =
Artem Belevich7093e402015-04-21 22:55:54 +0000502 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
503 instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
504 *CUDALaunchBounds, New);
505 continue;
506 }
507
Erich Keane23384a12019-08-23 15:58:35 +0000508 if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +0000509 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
510 continue;
511 }
512
Alexey Bataev2af33e32016-04-07 12:45:37 +0000513 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
514 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
515 continue;
516 }
517
Erich Keane23384a12019-08-23 15:58:35 +0000518 if (const auto *AMDGPUFlatWorkGroupSize =
Michael Liao7557afa2019-02-26 18:49:36 +0000519 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
520 instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
521 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
522 }
523
Erich Keane23384a12019-08-23 15:58:35 +0000524 if (const auto *AMDGPUFlatWorkGroupSize =
Michael Liao7557afa2019-02-26 18:49:36 +0000525 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
526 instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
527 *AMDGPUFlatWorkGroupSize, New);
528 }
529
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +0000530 // Existing DLL attribute on the instantiation takes precedence.
531 if (TmplAttr->getKind() == attr::DLLExport ||
532 TmplAttr->getKind() == attr::DLLImport) {
533 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
534 continue;
535 }
536 }
537
Erich Keane23384a12019-08-23 15:58:35 +0000538 if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
John McCall477f2bb2016-03-03 06:39:32 +0000539 AddParameterABIAttr(ABIAttr->getRange(), New, ABIAttr->getABI(),
540 ABIAttr->getSpellingListIndex());
541 continue;
542 }
543
George Karpenkov1657f362018-11-30 02:18:37 +0000544 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
545 isa<CFConsumedAttr>(TmplAttr)) {
546 AddXConsumedAttr(New, TmplAttr->getRange(),
547 TmplAttr->getSpellingListIndex(),
548 attrToRetainOwnershipKind(TmplAttr),
549 /*template instantiation=*/true);
John McCall3b5a8f52016-03-03 00:10:03 +0000550 continue;
551 }
552
Richard Smith44c247f2013-02-22 08:32:16 +0000553 assert(!TmplAttr->isPackExpansion());
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000554 if (TmplAttr->isLateParsed() && LateAttrs) {
555 // Late parsed attributes must be instantiated and attached after the
556 // enclosing class has been instantiated. See Sema::InstantiateClass.
Craig Topperc3ec1492014-05-26 06:22:03 +0000557 LocalInstantiationScope *Saved = nullptr;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000558 if (CurrentInstantiationScope)
559 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
560 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
561 } else {
Richard Smithc3d2ebb2013-06-07 02:33:37 +0000562 // Allow 'this' within late-parsed attributes.
563 NamedDecl *ND = dyn_cast<NamedDecl>(New);
564 CXXRecordDecl *ThisContext =
565 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
Mikael Nilsson9d2872d2018-12-13 10:15:27 +0000566 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
Richard Smithc3d2ebb2013-06-07 02:33:37 +0000567 ND && ND->isCXXInstanceMember());
568
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +0000569 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
570 *this, TemplateArgs);
Richard Smith33bddbd2018-01-04 23:42:29 +0000571 if (NewAttr)
Rafael Espindola7f90b7d2012-05-15 14:09:55 +0000572 New->addAttr(NewAttr);
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000573 }
Anders Carlsson3d709752009-11-07 06:07:58 +0000574 }
575}
576
Richard Smith41c79d92014-10-11 00:37:16 +0000577/// Get the previous declaration of a declaration for the purposes of template
578/// instantiation. If this finds a previous declaration, then the previous
579/// declaration of the instantiation of D should be an instantiation of the
580/// result of this function.
581template<typename DeclT>
582static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
583 DeclT *Result = D->getPreviousDecl();
584
585 // If the declaration is within a class, and the previous declaration was
586 // merged from a different definition of that class, then we don't have a
587 // previous declaration for the purpose of template instantiation.
588 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
589 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
590 return nullptr;
591
592 return Result;
593}
594
Douglas Gregor8a655532009-03-25 15:45:12 +0000595Decl *
596TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000597 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000598}
599
600Decl *
Nico Weber66220292016-03-02 17:28:48 +0000601TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
602 llvm_unreachable("pragma comment cannot be instantiated");
603}
604
Nico Webercbbaeb12016-03-02 19:28:54 +0000605Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
606 PragmaDetectMismatchDecl *D) {
607 llvm_unreachable("pragma comment cannot be instantiated");
608}
609
Nico Weber66220292016-03-02 17:28:48 +0000610Decl *
Richard Smithf19e1272015-03-07 00:04:49 +0000611TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
612 llvm_unreachable("extern \"C\" context cannot be instantiated");
613}
614
615Decl *
Chris Lattnercab02a62011-02-17 20:34:02 +0000616TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
617 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
618 D->getIdentifier());
619 Owner->addDecl(Inst);
620 return Inst;
621}
622
623Decl *
Douglas Gregor8a655532009-03-25 15:45:12 +0000624TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000625 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000626}
627
John McCalld8d0d432010-02-16 06:53:13 +0000628Decl *
629TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
630 NamespaceAliasDecl *Inst
631 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
632 D->getNamespaceLoc(),
633 D->getAliasLoc(),
Douglas Gregorc05ba2e2011-02-25 17:08:07 +0000634 D->getIdentifier(),
635 D->getQualifierLoc(),
John McCalld8d0d432010-02-16 06:53:13 +0000636 D->getTargetNameLoc(),
637 D->getNamespace());
638 Owner->addDecl(Inst);
639 return Inst;
640}
641
Richard Smith3f1b5d02011-05-05 21:57:07 +0000642Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
643 bool IsTypeAlias) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000644 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000645 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000646 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000647 DI->getType()->isVariablyModifiedType()) {
John McCall703a3f82009-10-24 08:00:42 +0000648 DI = SemaRef.SubstType(DI, TemplateArgs,
649 D->getLocation(), D->getDeclName());
650 if (!DI) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000651 Invalid = true;
John McCallbcd03502009-12-07 02:54:59 +0000652 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000653 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000654 } else {
655 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000656 }
Mike Stump11289f42009-09-09 15:08:12 +0000657
Richard Smith2ddcbab2012-10-23 00:32:41 +0000658 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
659 // libstdc++ relies upon this bug in its implementation of common_type.
660 // If we happen to be processing that implementation, fake up the g++ ?:
661 // semantics. See LWG issue 2141 for more information on the bug.
662 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
663 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
664 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
665 DT->isReferenceType() &&
666 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
667 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
668 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000669 SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
Richard Smith2ddcbab2012-10-23 00:32:41 +0000670 // Fold it to the (non-reference) type which g++ would have produced.
671 DI = SemaRef.Context.getTrivialTypeSourceInfo(
672 DI->getType().getNonReferenceType());
673
Douglas Gregord7e7a512009-03-17 21:15:40 +0000674 // Create the new typedef
Richard Smithdda56e42011-04-15 14:24:37 +0000675 TypedefNameDecl *Typedef;
676 if (IsTypeAlias)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000677 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
Richard Smithdda56e42011-04-15 14:24:37 +0000678 D->getLocation(), D->getIdentifier(), DI);
679 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000680 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
Richard Smithdda56e42011-04-15 14:24:37 +0000681 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000682 if (Invalid)
683 Typedef->setInvalidDecl();
684
John McCall04fcd0d2011-02-01 08:20:08 +0000685 // If the old typedef was the name for linkage purposes of an anonymous
686 // tag decl, re-establish that relationship for the new typedef.
687 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
688 TagDecl *oldTag = oldTagType->getDecl();
Douglas Gregord831d952013-03-08 22:15:15 +0000689 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
John McCall04fcd0d2011-02-01 08:20:08 +0000690 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
John McCall5ea95772013-03-09 00:54:27 +0000691 assert(!newTag->hasNameForLinkage());
Richard Smithdda56e42011-04-15 14:24:37 +0000692 newTag->setTypedefNameForAnonDecl(Typedef);
John McCall04fcd0d2011-02-01 08:20:08 +0000693 }
Douglas Gregor83eb5032010-04-23 16:25:07 +0000694 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000695
Richard Smith41c79d92014-10-11 00:37:16 +0000696 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000697 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
698 TemplateArgs);
Douglas Gregor55e6b312011-03-04 19:46:35 +0000699 if (!InstPrev)
Craig Topperc3ec1492014-05-26 06:22:03 +0000700 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000701
Rafael Espindolacde2c8f2011-12-26 22:42:47 +0000702 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
703
704 // If the typedef types are not identical, reject them.
705 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
706
Rafael Espindola8db352d2013-10-17 15:37:26 +0000707 Typedef->setPreviousDecl(InstPrevTypedef);
John McCall91f1a022009-12-30 00:31:22 +0000708 }
709
John McCall6602bb12010-08-01 02:01:53 +0000710 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregor83eb5032010-04-23 16:25:07 +0000711
John McCall401982f2010-01-20 21:53:11 +0000712 Typedef->setAccess(D->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +0000713
Douglas Gregord7e7a512009-03-17 21:15:40 +0000714 return Typedef;
715}
716
Richard Smithdda56e42011-04-15 14:24:37 +0000717Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000718 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
Richard Smith41c79d92014-10-11 00:37:16 +0000719 if (Typedef)
720 Owner->addDecl(Typedef);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000721 return Typedef;
Richard Smithdda56e42011-04-15 14:24:37 +0000722}
723
724Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000725 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
Richard Smith41c79d92014-10-11 00:37:16 +0000726 if (Typedef)
727 Owner->addDecl(Typedef);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000728 return Typedef;
729}
730
731Decl *
732TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
733 // Create a local instantiation scope for this type alias template, which
734 // will contain the instantiations of the template parameters.
735 LocalInstantiationScope Scope(SemaRef);
736
737 TemplateParameterList *TempParams = D->getTemplateParameters();
738 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
739 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +0000740 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000741
742 TypeAliasDecl *Pattern = D->getTemplatedDecl();
743
Craig Topperc3ec1492014-05-26 06:22:03 +0000744 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
Richard Smith41c79d92014-10-11 00:37:16 +0000745 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000746 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000747 if (!Found.empty()) {
748 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
Richard Smith3f1b5d02011-05-05 21:57:07 +0000749 }
750 }
751
752 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
753 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
754 if (!AliasInst)
Craig Topperc3ec1492014-05-26 06:22:03 +0000755 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000756
757 TypeAliasTemplateDecl *Inst
758 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
759 D->getDeclName(), InstParams, AliasInst);
Richard Smith43ccec8e2014-08-26 03:52:16 +0000760 AliasInst->setDescribedAliasTemplate(Inst);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000761 if (PrevAliasTemplate)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000762 Inst->setPreviousDecl(PrevAliasTemplate);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000763
764 Inst->setAccess(D->getAccess());
765
766 if (!PrevAliasTemplate)
767 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000768
Richard Smith3f1b5d02011-05-05 21:57:07 +0000769 Owner->addDecl(Inst);
770
771 return Inst;
Richard Smithdda56e42011-04-15 14:24:37 +0000772}
773
Richard Smithbdb84f32016-07-22 23:36:59 +0000774Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
Richard Smith3997b1b2016-08-12 01:55:21 +0000775 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
776 D->getIdentifier());
Richard Smith81df9eb2017-10-02 22:43:36 +0000777 NewBD->setReferenced(D->isReferenced());
Richard Smith3997b1b2016-08-12 01:55:21 +0000778 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
779 return NewBD;
Richard Smithbdb84f32016-07-22 23:36:59 +0000780}
781
782Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
Richard Smith3997b1b2016-08-12 01:55:21 +0000783 // Transform the bindings first.
784 SmallVector<BindingDecl*, 16> NewBindings;
785 for (auto *OldBD : D->bindings())
786 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
787 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
788
789 auto *NewDD = cast_or_null<DecompositionDecl>(
790 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
791
792 if (!NewDD || NewDD->isInvalidDecl())
793 for (auto *NewBD : NewBindings)
794 NewBD->setInvalidDecl();
795
796 return NewDD;
Richard Smithbdb84f32016-07-22 23:36:59 +0000797}
798
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000799Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000800 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000801}
802
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000803Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
Richard Smith3997b1b2016-08-12 01:55:21 +0000804 bool InstantiatingVarTemplate,
805 ArrayRef<BindingDecl*> *Bindings) {
Larisse Voufo39a1e502013-08-06 01:03:05 +0000806
John McCall76d824f2009-08-25 22:02:44 +0000807 // Do substitution on the type of the declaration
Richard Smithee579842017-01-30 20:39:26 +0000808 TypeSourceInfo *DI = SemaRef.SubstType(
809 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
810 D->getDeclName(), /*AllowDeducedTST*/true);
John McCallf1abcdc2009-10-21 02:39:02 +0000811 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +0000812 return nullptr;
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000813
Douglas Gregor61623342010-09-12 07:37:24 +0000814 if (DI->getType()->isFunctionType()) {
815 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
816 << D->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +0000817 return nullptr;
Douglas Gregor61623342010-09-12 07:37:24 +0000818 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000819
Richard Smith541b38b2013-09-20 01:15:31 +0000820 DeclContext *DC = Owner;
821 if (D->isLocalExternDecl())
822 SemaRef.adjustContextForLocalExternDecl(DC);
823
Larisse Voufo39a1e502013-08-06 01:03:05 +0000824 // Build the instantiated declaration.
Richard Smith3997b1b2016-08-12 01:55:21 +0000825 VarDecl *Var;
826 if (Bindings)
827 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
828 D->getLocation(), DI->getType(), DI,
829 D->getStorageClass(), *Bindings);
830 else
831 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
832 D->getLocation(), D->getIdentifier(), DI->getType(),
833 DI, D->getStorageClass());
Mike Stump11289f42009-09-09 15:08:12 +0000834
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000835 // In ARC, infer 'retaining' for variables of retainable type.
Fangrui Song6907ce22018-07-30 19:24:48 +0000836 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000837 SemaRef.inferObjCARCLifetime(Var))
838 Var->setInvalidDecl();
839
Larisse Voufo39a1e502013-08-06 01:03:05 +0000840 // Substitute the nested name specifier, if any.
841 if (SubstQualifier(D, Var))
Craig Topperc3ec1492014-05-26 06:22:03 +0000842 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000843
Richard Smith541b38b2013-09-20 01:15:31 +0000844 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000845 StartingScope, InstantiatingVarTemplate);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +0000846
847 if (D->isNRVOVariable()) {
848 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
Richard Trieu09c163b2018-03-15 03:00:55 +0000849 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, Sema::CES_Strict))
Taiju Tsuiki3be68e12018-06-19 05:35:30 +0000850 Var->setNRVOVariable(true);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +0000851 }
Taiju Tsuiki3be68e12018-06-19 05:35:30 +0000852
Alexander Kornienko83a4e182014-05-27 21:29:22 +0000853 Var->setImplicit(D->isImplicit());
854
Hans Wennborg262baa42018-10-31 10:34:46 +0000855 if (Var->isStaticLocal())
856 SemaRef.CheckStaticLocalForDllExport(Var);
857
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000858 return Var;
859}
860
Abramo Bagnarad7340582010-06-05 05:09:32 +0000861Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
862 AccessSpecDecl* AD
863 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
864 D->getAccessSpecifierLoc(), D->getColonLoc());
865 Owner->addHiddenDecl(AD);
866 return AD;
867}
868
Douglas Gregord7e7a512009-03-17 21:15:40 +0000869Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
870 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000871 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000872 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000873 DI->getType()->isVariablyModifiedType()) {
John McCall90459c52009-10-22 23:33:21 +0000874 DI = SemaRef.SubstType(DI, TemplateArgs,
875 D->getLocation(), D->getDeclName());
876 if (!DI) {
John McCallbcd03502009-12-07 02:54:59 +0000877 DI = D->getTypeSourceInfo();
John McCall90459c52009-10-22 23:33:21 +0000878 Invalid = true;
879 } else if (DI->getType()->isFunctionType()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000880 // C++ [temp.arg.type]p3:
881 // If a declaration acquires a function type through a type
882 // dependent on a template-parameter and this causes a
883 // declaration that does not use the syntactic form of a
884 // function declarator to have function type, the program is
885 // ill-formed.
886 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall90459c52009-10-22 23:33:21 +0000887 << DI->getType();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000888 Invalid = true;
889 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000890 } else {
891 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000892 }
893
894 Expr *BitWidth = D->getBitWidth();
895 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +0000896 BitWidth = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000897 else if (BitWidth) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000898 // The bit-width expression is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +0000899 EnterExpressionEvaluationContext Unevaluated(
900 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000901
John McCalldadc5752010-08-24 06:29:42 +0000902 ExprResult InstantiatedBitWidth
John McCall76d824f2009-08-25 22:02:44 +0000903 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000904 if (InstantiatedBitWidth.isInvalid()) {
905 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +0000906 BitWidth = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000907 } else
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000908 BitWidth = InstantiatedBitWidth.getAs<Expr>();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000909 }
910
John McCall90459c52009-10-22 23:33:21 +0000911 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
912 DI->getType(), DI,
Mike Stump11289f42009-09-09 15:08:12 +0000913 cast<RecordDecl>(Owner),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000914 D->getLocation(),
915 D->isMutable(),
916 BitWidth,
Richard Smith2b013182012-06-10 03:12:00 +0000917 D->getInClassInitStyle(),
Richard Smith47ad0172012-05-23 04:22:22 +0000918 D->getInnerLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000919 D->getAccess(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000920 nullptr);
Douglas Gregor3c74d412009-10-14 20:14:33 +0000921 if (!Field) {
922 cast<Decl>(Owner)->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +0000923 return nullptr;
Douglas Gregor3c74d412009-10-14 20:14:33 +0000924 }
Mike Stump11289f42009-09-09 15:08:12 +0000925
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000926 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000927
Richard Smith848e1f12013-02-01 08:12:08 +0000928 if (Field->hasAttrs())
929 SemaRef.CheckAlignasUnderalignment(Field);
930
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000931 if (Invalid)
932 Field->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000933
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000934 if (!Field->getDeclName()) {
935 // Keep track of where this decl came from.
936 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000937 }
Douglas Gregor04163182010-05-21 00:31:19 +0000938 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
939 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl50c68252010-08-31 00:36:30 +0000940 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor04163182010-05-21 00:31:19 +0000941 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000942 }
Mike Stump11289f42009-09-09 15:08:12 +0000943
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000944 Field->setImplicit(D->isImplicit());
John McCall401982f2010-01-20 21:53:11 +0000945 Field->setAccess(D->getAccess());
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000946 Owner->addDecl(Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000947
948 return Field;
949}
950
John McCall5e77d762013-04-16 07:28:30 +0000951Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
952 bool Invalid = false;
953 TypeSourceInfo *DI = D->getTypeSourceInfo();
954
955 if (DI->getType()->isVariablyModifiedType()) {
956 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
Aaron Ballman1bda4592014-01-03 01:09:27 +0000957 << D;
John McCall5e77d762013-04-16 07:28:30 +0000958 Invalid = true;
959 } else if (DI->getType()->isInstantiationDependentType()) {
960 DI = SemaRef.SubstType(DI, TemplateArgs,
961 D->getLocation(), D->getDeclName());
962 if (!DI) {
963 DI = D->getTypeSourceInfo();
964 Invalid = true;
965 } else if (DI->getType()->isFunctionType()) {
966 // C++ [temp.arg.type]p3:
967 // If a declaration acquires a function type through a type
968 // dependent on a template-parameter and this causes a
969 // declaration that does not use the syntactic form of a
970 // function declarator to have function type, the program is
971 // ill-formed.
972 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
973 << DI->getType();
974 Invalid = true;
975 }
976 } else {
977 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
978 }
979
Richard Smithf7981722013-11-22 09:01:48 +0000980 MSPropertyDecl *Property = MSPropertyDecl::Create(
981 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000982 DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
John McCall5e77d762013-04-16 07:28:30 +0000983
984 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
985 StartingScope);
986
987 if (Invalid)
988 Property->setInvalidDecl();
989
990 Property->setAccess(D->getAccess());
991 Owner->addDecl(Property);
992
993 return Property;
994}
995
Francois Pichet783dd6e2010-11-21 06:08:52 +0000996Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
997 NamedDecl **NamedChain =
998 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
999
1000 int i = 0;
Aaron Ballman29c94602014-03-07 18:36:15 +00001001 for (auto *PI : D->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00001002 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
Douglas Gregor55e6b312011-03-04 19:46:35 +00001003 TemplateArgs);
1004 if (!Next)
Craig Topperc3ec1492014-05-26 06:22:03 +00001005 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001006
Douglas Gregor55e6b312011-03-04 19:46:35 +00001007 NamedChain[i++] = Next;
1008 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00001009
Francois Pichetdbafc192010-12-09 10:07:54 +00001010 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Aaron Ballman260995b2014-10-15 16:58:18 +00001011 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1012 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
David Majnemer59f77922016-06-24 04:05:48 +00001013 {NamedChain, D->getChainingSize()});
Francois Pichet783dd6e2010-11-21 06:08:52 +00001014
NAKAMURA Takumi729be142014-10-27 12:37:26 +00001015 for (const auto *Attr : D->attrs())
1016 IndirectField->addAttr(Attr->clone(SemaRef.Context));
Francois Pichet783dd6e2010-11-21 06:08:52 +00001017
1018 IndirectField->setImplicit(D->isImplicit());
1019 IndirectField->setAccess(D->getAccess());
1020 Owner->addDecl(IndirectField);
1021 return IndirectField;
1022}
1023
John McCallaa74a0c2009-08-28 07:59:38 +00001024Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCallaa74a0c2009-08-28 07:59:38 +00001025 // Handle friend type expressions by simply substituting template
Douglas Gregor3b4abb62010-04-07 17:57:12 +00001026 // parameters into the pattern type and checking the result.
John McCall15ad0962010-03-25 18:04:51 +00001027 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth08836322011-05-01 00:51:33 +00001028 TypeSourceInfo *InstTy;
1029 // If this is an unsupported friend, don't bother substituting template
1030 // arguments into it. The actual type referred to won't be used by any
1031 // parts of Clang, and may not be valid for instantiating. Just use the
1032 // same info for the instantiated friend.
1033 if (D->isUnsupportedFriend()) {
1034 InstTy = Ty;
1035 } else {
1036 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
1037 D->getLocation(), DeclarationName());
1038 }
1039 if (!InstTy)
Craig Topperc3ec1492014-05-26 06:22:03 +00001040 return nullptr;
John McCallaa74a0c2009-08-28 07:59:38 +00001041
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001042 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
Abramo Bagnara254b6302011-10-29 20:52:52 +00001043 D->getFriendLoc(), InstTy);
Douglas Gregor3b4abb62010-04-07 17:57:12 +00001044 if (!FD)
Craig Topperc3ec1492014-05-26 06:22:03 +00001045 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001046
Douglas Gregor3b4abb62010-04-07 17:57:12 +00001047 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +00001048 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor3b4abb62010-04-07 17:57:12 +00001049 Owner->addDecl(FD);
1050 return FD;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001051 }
1052
Douglas Gregor3b4abb62010-04-07 17:57:12 +00001053 NamedDecl *ND = D->getFriendDecl();
1054 assert(ND && "friend decl must be a decl or a type!");
1055
John McCallb9c78482010-04-08 09:05:18 +00001056 // All of the Visit implementations for the various potential friend
1057 // declarations have to be carefully written to work for friend
1058 // objects, with the most important detail being that the target
1059 // decl should almost certainly not be placed in Owner.
1060 Decl *NewND = Visit(ND);
Craig Topperc3ec1492014-05-26 06:22:03 +00001061 if (!NewND) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001062
John McCallaa74a0c2009-08-28 07:59:38 +00001063 FriendDecl *FD =
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001064 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor3b4abb62010-04-07 17:57:12 +00001065 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall75c03bb2009-08-29 03:50:18 +00001066 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +00001067 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCallaa74a0c2009-08-28 07:59:38 +00001068 Owner->addDecl(FD);
1069 return FD;
John McCall58de3582009-08-14 02:03:10 +00001070}
1071
Douglas Gregord7e7a512009-03-17 21:15:40 +00001072Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1073 Expr *AssertExpr = D->getAssertExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001074
Richard Smith764d2fe2011-12-20 02:08:33 +00001075 // The expression in a static assertion is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +00001076 EnterExpressionEvaluationContext Unevaluated(
1077 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +00001078
John McCalldadc5752010-08-24 06:29:42 +00001079 ExprResult InstantiatedAssertExpr
John McCall76d824f2009-08-25 22:02:44 +00001080 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +00001081 if (InstantiatedAssertExpr.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00001082 return nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +00001083
Richard Smithded9c2e2012-07-11 22:37:56 +00001084 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCallb268a282010-08-23 23:25:46 +00001085 InstantiatedAssertExpr.get(),
Richard Smithded9c2e2012-07-11 22:37:56 +00001086 D->getMessage(),
1087 D->getRParenLoc(),
1088 D->isFailed());
Douglas Gregord7e7a512009-03-17 21:15:40 +00001089}
1090
1091Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001092 EnumDecl *PrevDecl = nullptr;
Richard Smith41c79d92014-10-11 00:37:16 +00001093 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
Richard Smith2e6610a2012-03-26 04:58:10 +00001094 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Richard Smith41c79d92014-10-11 00:37:16 +00001095 PatternPrev,
Richard Smith2e6610a2012-03-26 04:58:10 +00001096 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +00001097 if (!Prev) return nullptr;
Richard Smith2e6610a2012-03-26 04:58:10 +00001098 PrevDecl = cast<EnumDecl>(Prev);
1099 }
1100
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001101 EnumDecl *Enum =
1102 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1103 D->getLocation(), D->getIdentifier(), PrevDecl,
1104 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001105 if (D->isFixed()) {
Richard Smith4b38ded2012-03-14 23:13:10 +00001106 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00001107 // If we have type source information for the underlying type, it means it
1108 // has been explicitly set by the user. Perform substitution on it before
1109 // moving on.
1110 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smith4b38ded2012-03-14 23:13:10 +00001111 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1112 DeclarationName());
1113 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor0bf31402010-10-08 23:50:27 +00001114 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smith4b38ded2012-03-14 23:13:10 +00001115 else
1116 Enum->setIntegerTypeSourceInfo(NewTI);
1117 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +00001118 assert(!D->getIntegerType()->isDependentType()
1119 && "Dependent type without type source info");
1120 Enum->setIntegerType(D->getIntegerType());
1121 }
1122 }
1123
John McCall811a0f52010-10-22 23:36:17 +00001124 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1125
Richard Smith4b38ded2012-03-14 23:13:10 +00001126 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor6c2adff2009-03-25 22:00:53 +00001127 Enum->setAccess(D->getAccess());
David Majnemerdbc0c8f2013-12-04 09:01:55 +00001128 // Forward the mangling number from the template to the instantiated decl.
1129 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
David Majnemer00350522015-08-31 18:48:39 +00001130 // See if the old tag was defined along with a declarator.
1131 // If it did, mark the new tag as being associated with that declarator.
1132 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1133 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1134 // See if the old tag was defined along with a typedef.
1135 // If it did, mark the new tag as being associated with that typedef.
1136 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1137 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
Craig Topperc3ec1492014-05-26 06:22:03 +00001138 if (SubstQualifier(D, Enum)) return nullptr;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001139 Owner->addDecl(Enum);
Richard Smith4b38ded2012-03-14 23:13:10 +00001140
Richard Smith258a7442012-03-26 04:08:46 +00001141 EnumDecl *Def = D->getDefinition();
1142 if (Def && Def != D) {
1143 // If this is an out-of-line definition of an enum member template, check
1144 // that the underlying types match in the instantiation of both
1145 // declarations.
1146 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1147 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1148 QualType DefnUnderlying =
1149 SemaRef.SubstType(TI->getType(), TemplateArgs,
1150 UnderlyingLoc, DeclarationName());
1151 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
Reid Klecknerb0a17ed2018-02-12 17:37:06 +00001152 DefnUnderlying, /*IsFixed=*/true, Enum);
Richard Smith258a7442012-03-26 04:08:46 +00001153 }
1154 }
Douglas Gregord7e7a512009-03-17 21:15:40 +00001155
Richard Smith4b38ded2012-03-14 23:13:10 +00001156 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1157 // specialization causes the implicit instantiation of the declarations, but
1158 // not the definitions of scoped member enumerations.
David Majnemer192d1792013-11-27 08:20:38 +00001159 //
1160 // DR1484 clarifies that enumeration definitions inside of a template
1161 // declaration aren't considered entities that can be separately instantiated
1162 // from the rest of the entity they are declared inside of.
1163 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1164 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
Richard Smith258a7442012-03-26 04:08:46 +00001165 InstantiateEnumDefinition(Enum, Def);
David Majnemer192d1792013-11-27 08:20:38 +00001166 }
Richard Smith4b38ded2012-03-14 23:13:10 +00001167
1168 return Enum;
1169}
1170
1171void TemplateDeclInstantiator::InstantiateEnumDefinition(
1172 EnumDecl *Enum, EnumDecl *Pattern) {
1173 Enum->startDefinition();
1174
Richard Smith7d137e32012-03-23 03:33:32 +00001175 // Update the location to refer to the definition.
1176 Enum->setLocation(Pattern->getLocation());
1177
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001178 SmallVector<Decl*, 4> Enumerators;
Douglas Gregord7e7a512009-03-17 21:15:40 +00001179
Craig Topperc3ec1492014-05-26 06:22:03 +00001180 EnumConstantDecl *LastEnumConst = nullptr;
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001181 for (auto *EC : Pattern->enumerators()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +00001182 // The specified value for the enumerator.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001183 ExprResult Value((Expr *)nullptr);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00001184 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smith764d2fe2011-12-20 02:08:33 +00001185 // The enumerator's value expression is a constant expression.
Faisal Valid143a0c2017-04-01 21:30:49 +00001186 EnterExpressionEvaluationContext Unevaluated(
1187 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +00001188
John McCall76d824f2009-08-25 22:02:44 +00001189 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00001190 }
Douglas Gregord7e7a512009-03-17 21:15:40 +00001191
1192 // Drop the initial value and continue.
1193 bool isInvalid = false;
1194 if (Value.isInvalid()) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001195 Value = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +00001196 isInvalid = true;
1197 }
1198
Mike Stump11289f42009-09-09 15:08:12 +00001199 EnumConstantDecl *EnumConst
Douglas Gregord7e7a512009-03-17 21:15:40 +00001200 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1201 EC->getLocation(), EC->getIdentifier(),
John McCallb268a282010-08-23 23:25:46 +00001202 Value.get());
Douglas Gregord7e7a512009-03-17 21:15:40 +00001203
1204 if (isInvalid) {
1205 if (EnumConst)
1206 EnumConst->setInvalidDecl();
1207 Enum->setInvalidDecl();
1208 }
1209
1210 if (EnumConst) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001211 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
John McCall811a0f52010-10-22 23:36:17 +00001212
John McCallf9b528c2010-01-23 22:37:59 +00001213 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001214 Enum->addDecl(EnumConst);
John McCall48871652010-08-21 09:40:31 +00001215 Enumerators.push_back(EnumConst);
Douglas Gregord7e7a512009-03-17 21:15:40 +00001216 LastEnumConst = EnumConst;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001217
Richard Smith4b38ded2012-03-14 23:13:10 +00001218 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1219 !Enum->isScoped()) {
Douglas Gregoraff9c1a2010-03-01 19:00:07 +00001220 // If the enumeration is within a function or method, record the enum
1221 // constant as a local.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001222 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
Douglas Gregoraff9c1a2010-03-01 19:00:07 +00001223 }
Douglas Gregord7e7a512009-03-17 21:15:40 +00001224 }
1225 }
Mike Stump11289f42009-09-09 15:08:12 +00001226
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00001227 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
Erich Keanec480f302018-07-12 21:09:05 +00001228 Enumerators, nullptr, ParsedAttributesView());
Douglas Gregord7e7a512009-03-17 21:15:40 +00001229}
1230
Douglas Gregor9106b822009-03-25 15:04:13 +00001231Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +00001232 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor9106b822009-03-25 15:04:13 +00001233}
1234
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001235Decl *
1236TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1237 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1238}
1239
John McCall87a44eb2009-08-20 01:44:21 +00001240Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall598b4402010-03-25 06:39:04 +00001241 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1242
Douglas Gregor954de172009-10-31 17:21:17 +00001243 // Create a local instantiation scope for this class template, which
1244 // will contain the instantiations of the template parameters.
John McCall19c1bfd2010-08-25 05:32:35 +00001245 LocalInstantiationScope Scope(SemaRef);
John McCall87a44eb2009-08-20 01:44:21 +00001246 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCall76d824f2009-08-25 22:02:44 +00001247 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +00001248 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001249 return nullptr;
John McCall87a44eb2009-08-20 01:44:21 +00001250
1251 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall598b4402010-03-25 06:39:04 +00001252
1253 // Instantiate the qualifier. We have to do this first in case
1254 // we're a friend declaration, because if we are then we need to put
1255 // the new declaration in the appropriate context.
Douglas Gregor14454802011-02-25 02:25:35 +00001256 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1257 if (QualifierLoc) {
1258 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1259 TemplateArgs);
1260 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00001261 return nullptr;
John McCall598b4402010-03-25 06:39:04 +00001262 }
1263
Craig Topperc3ec1492014-05-26 06:22:03 +00001264 CXXRecordDecl *PrevDecl = nullptr;
1265 ClassTemplateDecl *PrevClassTemplate = nullptr;
John McCall598b4402010-03-25 06:39:04 +00001266
Richard Smith41c79d92014-10-11 00:37:16 +00001267 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
Nick Lewycky61478912010-11-08 23:29:42 +00001268 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00001269 if (!Found.empty()) {
1270 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky61478912010-11-08 23:29:42 +00001271 if (PrevClassTemplate)
1272 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1273 }
1274 }
1275
John McCall598b4402010-03-25 06:39:04 +00001276 // If this isn't a friend, then it's a member template, in which
1277 // case we just want to build the instantiation in the
1278 // specialization. If it is a friend, we want to build it in
1279 // the appropriate context.
1280 DeclContext *DC = Owner;
1281 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +00001282 if (QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +00001283 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001284 SS.Adopt(QualifierLoc);
John McCall598b4402010-03-25 06:39:04 +00001285 DC = SemaRef.computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +00001286 if (!DC) return nullptr;
John McCall598b4402010-03-25 06:39:04 +00001287 } else {
1288 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1289 Pattern->getDeclContext(),
1290 TemplateArgs);
1291 }
1292
1293 // Look for a previous declaration of the template in the owning
1294 // context.
1295 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
Richard Smithbecb92d2017-10-10 22:33:17 +00001296 Sema::LookupOrdinaryName,
1297 SemaRef.forRedeclarationInCurContext());
John McCall598b4402010-03-25 06:39:04 +00001298 SemaRef.LookupQualifiedName(R, DC);
1299
1300 if (R.isSingleResult()) {
1301 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1302 if (PrevClassTemplate)
1303 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1304 }
1305
Douglas Gregor14454802011-02-25 02:25:35 +00001306 if (!PrevClassTemplate && QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +00001307 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregorf5af3582010-03-31 23:17:41 +00001308 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregor14454802011-02-25 02:25:35 +00001309 << QualifierLoc.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001310 return nullptr;
John McCall598b4402010-03-25 06:39:04 +00001311 }
1312
Douglas Gregor01e09d92010-04-08 18:16:15 +00001313 bool AdoptedPreviousTemplateParams = false;
John McCall598b4402010-03-25 06:39:04 +00001314 if (PrevClassTemplate) {
Douglas Gregor01e09d92010-04-08 18:16:15 +00001315 bool Complain = true;
1316
1317 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
1318 // template for struct std::tr1::__detail::_Map_base, where the
1319 // template parameters of the friend declaration don't match the
1320 // template parameters of the original declaration. In this one
1321 // case, we don't complain about the ill-formed friend
1322 // declaration.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001323 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregor01e09d92010-04-08 18:16:15 +00001324 Pattern->getIdentifier()->isStr("_Map_base") &&
1325 DC->isNamespace() &&
1326 cast<NamespaceDecl>(DC)->getIdentifier() &&
1327 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
1328 DeclContext *DCParent = DC->getParent();
1329 if (DCParent->isNamespace() &&
1330 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
1331 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
Richard Trieuc771d5d2014-05-28 02:16:01 +00001332 if (cast<Decl>(DCParent)->isInStdNamespace())
Douglas Gregor01e09d92010-04-08 18:16:15 +00001333 Complain = false;
1334 }
1335 }
1336
John McCall598b4402010-03-25 06:39:04 +00001337 TemplateParameterList *PrevParams
Richard Smithc4577662018-09-12 02:13:47 +00001338 = PrevClassTemplate->getMostRecentDecl()->getTemplateParameters();
John McCall598b4402010-03-25 06:39:04 +00001339
1340 // Make sure the parameter lists match.
1341 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001342 Complain,
Douglas Gregor01e09d92010-04-08 18:16:15 +00001343 Sema::TPL_TemplateMatch)) {
1344 if (Complain)
Craig Topperc3ec1492014-05-26 06:22:03 +00001345 return nullptr;
Douglas Gregor01e09d92010-04-08 18:16:15 +00001346
1347 AdoptedPreviousTemplateParams = true;
1348 InstParams = PrevParams;
1349 }
John McCall598b4402010-03-25 06:39:04 +00001350
1351 // Do some additional validation, then merge default arguments
1352 // from the existing declarations.
Douglas Gregor01e09d92010-04-08 18:16:15 +00001353 if (!AdoptedPreviousTemplateParams &&
1354 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall598b4402010-03-25 06:39:04 +00001355 Sema::TPC_ClassTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00001356 return nullptr;
John McCall598b4402010-03-25 06:39:04 +00001357 }
1358 }
1359
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001360 CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
1361 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1362 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1363 /*DelayTypeCreation=*/true);
John McCall87a44eb2009-08-20 01:44:21 +00001364
Douglas Gregor14454802011-02-25 02:25:35 +00001365 if (QualifierLoc)
1366 RecordInst->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001367
Louis Dionne3c011e12018-09-14 14:07:16 +00001368 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1369 StartingScope);
1370
John McCall87a44eb2009-08-20 01:44:21 +00001371 ClassTemplateDecl *Inst
John McCall598b4402010-03-25 06:39:04 +00001372 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
Vassil Vassilev352e4412017-01-12 09:16:26 +00001373 D->getIdentifier(), InstParams, RecordInst);
1374 assert(!(isFriend && Owner->isDependentContext()));
1375 Inst->setPreviousDecl(PrevClassTemplate);
1376
John McCall87a44eb2009-08-20 01:44:21 +00001377 RecordInst->setDescribedClassTemplate(Inst);
John McCall17762b82010-04-08 20:25:50 +00001378
John McCall598b4402010-03-25 06:39:04 +00001379 if (isFriend) {
John McCall17762b82010-04-08 20:25:50 +00001380 if (PrevClassTemplate)
1381 Inst->setAccess(PrevClassTemplate->getAccess());
1382 else
1383 Inst->setAccess(D->getAccess());
1384
Richard Smith64017682013-07-17 23:53:16 +00001385 Inst->setObjectOfFriendDecl();
John McCall598b4402010-03-25 06:39:04 +00001386 // TODO: do we want to track the instantiation progeny of this
1387 // friend target decl?
1388 } else {
Douglas Gregor412e8bc2009-10-30 21:07:27 +00001389 Inst->setAccess(D->getAccess());
Nick Lewycky61478912010-11-08 23:29:42 +00001390 if (!PrevClassTemplate)
1391 Inst->setInstantiatedFromMemberTemplate(D);
John McCall598b4402010-03-25 06:39:04 +00001392 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001393
Douglas Gregoref06ccf2009-10-12 23:11:44 +00001394 // Trigger creation of the type for the instantiation.
John McCalle78aac42010-03-10 03:28:59 +00001395 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor9961ce92010-07-08 18:37:38 +00001396 Inst->getInjectedClassNameSpecialization());
John McCall17762b82010-04-08 20:25:50 +00001397
Douglas Gregorbb3b46e2009-10-30 22:42:42 +00001398 // Finish handling of friends.
John McCall598b4402010-03-25 06:39:04 +00001399 if (isFriend) {
Richard Smith05afe5e2012-03-13 03:12:56 +00001400 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +00001401 Inst->setLexicalDeclContext(Owner);
1402 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregor412e8bc2009-10-30 21:07:27 +00001403 return Inst;
Douglas Gregorbb3b46e2009-10-30 22:42:42 +00001404 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001405
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +00001406 if (D->isOutOfLine()) {
1407 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1408 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1409 }
1410
John McCall87a44eb2009-08-20 01:44:21 +00001411 Owner->addDecl(Inst);
Douglas Gregor869853e2010-11-10 19:44:59 +00001412
1413 if (!PrevClassTemplate) {
1414 // Queue up any out-of-line partial specializations of this member
1415 // class template; the client will force their instantiation once
1416 // the enclosing class has been instantiated.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001417 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor869853e2010-11-10 19:44:59 +00001418 D->getPartialSpecializations(PartialSpecs);
1419 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +00001420 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Douglas Gregor869853e2010-11-10 19:44:59 +00001421 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1422 }
1423
John McCall87a44eb2009-08-20 01:44:21 +00001424 return Inst;
1425}
1426
Douglas Gregore704c9d2009-08-27 16:57:43 +00001427Decl *
Douglas Gregore4b05162009-10-07 17:21:34 +00001428TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1429 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregor21610382009-10-29 00:04:11 +00001430 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001431
Douglas Gregor21610382009-10-29 00:04:11 +00001432 // Lookup the already-instantiated declaration in the instantiation
1433 // of the class template and return that.
1434 DeclContext::lookup_result Found
1435 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00001436 if (Found.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00001437 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001438
Douglas Gregor21610382009-10-29 00:04:11 +00001439 ClassTemplateDecl *InstClassTemplate
David Blaikieff7d47a2012-12-19 00:45:41 +00001440 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregor21610382009-10-29 00:04:11 +00001441 if (!InstClassTemplate)
Craig Topperc3ec1492014-05-26 06:22:03 +00001442 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001443
Douglas Gregor869853e2010-11-10 19:44:59 +00001444 if (ClassTemplatePartialSpecializationDecl *Result
1445 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1446 return Result;
1447
1448 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregore4b05162009-10-07 17:21:34 +00001449}
1450
Larisse Voufo39a1e502013-08-06 01:03:05 +00001451Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1452 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1453 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001454
1455 // Create a local instantiation scope for this variable template, which
1456 // will contain the instantiations of the template parameters.
1457 LocalInstantiationScope Scope(SemaRef);
1458 TemplateParameterList *TempParams = D->getTemplateParameters();
1459 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1460 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001461 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001462
1463 VarDecl *Pattern = D->getTemplatedDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001464 VarTemplateDecl *PrevVarTemplate = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001465
Richard Smith41c79d92014-10-11 00:37:16 +00001466 if (getPreviousDeclForInstantiation(Pattern)) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00001467 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1468 if (!Found.empty())
1469 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1470 }
1471
Richard Smith1c34fb72013-08-13 18:18:50 +00001472 VarDecl *VarInst =
Larisse Voufo72caf2b2013-08-22 00:59:14 +00001473 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1474 /*InstantiatingVarTemplate=*/true));
Nick Lewycky6ca07ca2015-08-10 21:54:08 +00001475 if (!VarInst) return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001476
1477 DeclContext *DC = Owner;
1478
Larisse Voufo39a1e502013-08-06 01:03:05 +00001479 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1480 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
Richard Smithbeef3452014-01-16 23:39:20 +00001481 VarInst);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001482 VarInst->setDescribedVarTemplate(Inst);
Richard Smithbeef3452014-01-16 23:39:20 +00001483 Inst->setPreviousDecl(PrevVarTemplate);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001484
1485 Inst->setAccess(D->getAccess());
1486 if (!PrevVarTemplate)
1487 Inst->setInstantiatedFromMemberTemplate(D);
1488
1489 if (D->isOutOfLine()) {
1490 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1491 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1492 }
1493
1494 Owner->addDecl(Inst);
1495
1496 if (!PrevVarTemplate) {
1497 // Queue up any out-of-line partial specializations of this member
1498 // variable template; the client will force their instantiation once
1499 // the enclosing class has been instantiated.
1500 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1501 D->getPartialSpecializations(PartialSpecs);
1502 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +00001503 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00001504 OutOfLineVarPartialSpecs.push_back(
1505 std::make_pair(Inst, PartialSpecs[I]));
1506 }
1507
1508 return Inst;
1509}
1510
1511Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1512 VarTemplatePartialSpecializationDecl *D) {
1513 assert(D->isStaticDataMember() &&
1514 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001515
1516 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1517
1518 // Lookup the already-instantiated declaration and return that.
1519 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1520 assert(!Found.empty() && "Instantiation found nothing?");
1521
1522 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1523 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1524
1525 if (VarTemplatePartialSpecializationDecl *Result =
1526 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1527 return Result;
1528
1529 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1530}
1531
Douglas Gregore4b05162009-10-07 17:21:34 +00001532Decl *
Douglas Gregore704c9d2009-08-27 16:57:43 +00001533TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor954de172009-10-31 17:21:17 +00001534 // Create a local instantiation scope for this function template, which
1535 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001536 // merged with the local instantiation scope for the function template
Douglas Gregor954de172009-10-31 17:21:17 +00001537 // itself.
John McCall19c1bfd2010-08-25 05:32:35 +00001538 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor14cf7522010-04-30 18:55:50 +00001539
Douglas Gregore704c9d2009-08-27 16:57:43 +00001540 TemplateParameterList *TempParams = D->getTemplateParameters();
1541 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +00001542 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001543 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001544
Craig Topperc3ec1492014-05-26 06:22:03 +00001545 FunctionDecl *Instantiated = nullptr;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001546 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001547 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001548 InstParams));
1549 else
1550 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001551 D->getTemplatedDecl(),
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001552 InstParams));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001553
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001554 if (!Instantiated)
Craig Topperc3ec1492014-05-26 06:22:03 +00001555 return nullptr;
Douglas Gregore704c9d2009-08-27 16:57:43 +00001556
Mike Stump11289f42009-09-09 15:08:12 +00001557 // Link the instantiated function template declaration to the function
Douglas Gregore704c9d2009-08-27 16:57:43 +00001558 // template from which it was instantiated.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001559 FunctionTemplateDecl *InstTemplate
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001560 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregorca027af2009-10-12 22:27:17 +00001561 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001562 assert(InstTemplate &&
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001563 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCall2079d0b2009-12-14 23:19:40 +00001564
John McCall30837102010-03-26 23:10:15 +00001565 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1566
John McCall2079d0b2009-12-14 23:19:40 +00001567 // Link the instantiation back to the pattern *unless* this is a
1568 // non-definition friend declaration.
1569 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCall30837102010-03-26 23:10:15 +00001570 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001571 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001572
John McCall30837102010-03-26 23:10:15 +00001573 // Make declarations visible in the appropriate context.
John McCalla0a96892012-08-10 03:15:35 +00001574 if (!isFriend) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001575 Owner->addDecl(InstTemplate);
John McCalla0a96892012-08-10 03:15:35 +00001576 } else if (InstTemplate->getDeclContext()->isRecord() &&
Richard Smith41c79d92014-10-11 00:37:16 +00001577 !getPreviousDeclForInstantiation(D)) {
John McCalla0a96892012-08-10 03:15:35 +00001578 SemaRef.CheckFriendAccess(InstTemplate);
1579 }
John McCall30837102010-03-26 23:10:15 +00001580
Douglas Gregore704c9d2009-08-27 16:57:43 +00001581 return InstTemplate;
1582}
1583
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001584Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001585 CXXRecordDecl *PrevDecl = nullptr;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001586 if (D->isInjectedClassName())
1587 PrevDecl = cast<CXXRecordDecl>(Owner);
Richard Smith41c79d92014-10-11 00:37:16 +00001588 else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001589 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Richard Smith41c79d92014-10-11 00:37:16 +00001590 PatternPrev,
John McCalle9f92a02009-12-15 22:29:06 +00001591 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +00001592 if (!Prev) return nullptr;
John McCalle9f92a02009-12-15 22:29:06 +00001593 PrevDecl = cast<CXXRecordDecl>(Prev);
1594 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001595
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001596 CXXRecordDecl *Record = CXXRecordDecl::Create(
1597 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
1598 D->getLocation(), D->getIdentifier(), PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00001599
1600 // Substitute the nested name specifier, if any.
1601 if (SubstQualifier(D, Record))
Craig Topperc3ec1492014-05-26 06:22:03 +00001602 return nullptr;
John McCall3e11ebe2010-03-15 10:12:16 +00001603
Louis Dionne3c011e12018-09-14 14:07:16 +00001604 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
1605 StartingScope);
1606
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001607 Record->setImplicit(D->isImplicit());
Eli Friedmanbda4ef12009-08-27 19:11:42 +00001608 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1609 // the tag decls introduced by friend class declarations don't have an access
1610 // specifier. Remove once this area of the code gets sorted out.
1611 if (D->getAccess() != AS_none)
1612 Record->setAccess(D->getAccess());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001613 if (!D->isInjectedClassName())
Douglas Gregorbbe8f462009-10-08 15:14:33 +00001614 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001615
John McCallaa74a0c2009-08-28 07:59:38 +00001616 // If the original function was part of a friend declaration,
1617 // inherit its namespace state.
Richard Smith64017682013-07-17 23:53:16 +00001618 if (D->getFriendObjectKind())
1619 Record->setObjectOfFriendDecl();
John McCallaa74a0c2009-08-28 07:59:38 +00001620
Douglas Gregor04163182010-05-21 00:31:19 +00001621 // Make sure that anonymous structs and unions are recorded.
David Majnemer192d1792013-11-27 08:20:38 +00001622 if (D->isAnonymousStructOrUnion())
Douglas Gregor04163182010-05-21 00:31:19 +00001623 Record->setAnonymousStructOrUnion(true);
David Majnemer192d1792013-11-27 08:20:38 +00001624
1625 if (D->isLocalClass())
1626 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
Anders Carlsson5da84842009-09-01 04:26:58 +00001627
David Majnemerdbc0c8f2013-12-04 09:01:55 +00001628 // Forward the mangling number from the template to the instantiated decl.
1629 SemaRef.Context.setManglingNumber(Record,
1630 SemaRef.Context.getManglingNumber(D));
1631
David Majnemer00350522015-08-31 18:48:39 +00001632 // See if the old tag was defined along with a declarator.
1633 // If it did, mark the new tag as being associated with that declarator.
1634 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1635 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1636
1637 // See if the old tag was defined along with a typedef.
1638 // If it did, mark the new tag as being associated with that typedef.
1639 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1640 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1641
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001642 Owner->addDecl(Record);
David Majnemer192d1792013-11-27 08:20:38 +00001643
1644 // DR1484 clarifies that the members of a local class are instantiated as part
1645 // of the instantiation of their enclosing entity.
1646 if (D->isCompleteDefinition() && D->isLocalClass()) {
Richard Smith4f3e3812017-05-20 01:36:41 +00001647 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
Richard Smithb0b68012015-05-11 23:09:06 +00001648
David Majnemera64cb5a2014-02-22 00:17:46 +00001649 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1650 TSK_ImplicitInstantiation,
1651 /*Complain=*/true);
Richard Smithb0b68012015-05-11 23:09:06 +00001652
Richard Smithece47582017-01-04 23:45:01 +00001653 // For nested local classes, we will instantiate the members when we
1654 // reach the end of the outermost (non-nested) local class.
1655 if (!D->isCXXClassMember())
1656 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1657 TSK_ImplicitInstantiation);
Richard Smithb0b68012015-05-11 23:09:06 +00001658
1659 // This class may have local implicit instantiations that need to be
1660 // performed within this scope.
Richard Smith4f3e3812017-05-20 01:36:41 +00001661 LocalInstantiations.perform();
David Majnemer192d1792013-11-27 08:20:38 +00001662 }
Nico Weber72889432014-09-06 01:25:55 +00001663
1664 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1665
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001666 return Record;
1667}
1668
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001669/// Adjust the given function type for an instantiation of the
Douglas Gregor89f593a2012-09-13 21:56:43 +00001670/// given declaration, to cope with modifications to the function's type that
1671/// aren't reflected in the type-source information.
1672///
1673/// \param D The declaration we're instantiating.
1674/// \param TInfo The already-instantiated type.
1675static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1676 FunctionDecl *D,
1677 TypeSourceInfo *TInfo) {
Douglas Gregor1af8ad42012-09-13 22:01:49 +00001678 const FunctionProtoType *OrigFunc
1679 = D->getType()->castAs<FunctionProtoType>();
1680 const FunctionProtoType *NewFunc
1681 = TInfo->getType()->castAs<FunctionProtoType>();
1682 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1683 return TInfo->getType();
1684
1685 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1686 NewEPI.ExtInfo = OrigFunc->getExtInfo();
Alp Toker314cc812014-01-25 16:55:45 +00001687 return Context.getFunctionType(NewFunc->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00001688 NewFunc->getParamTypes(), NewEPI);
Douglas Gregor89f593a2012-09-13 21:56:43 +00001689}
1690
John McCallaa74a0c2009-08-28 07:59:38 +00001691/// Normal class members are of more specific types and therefore
Richard Smith4fa145152017-12-21 19:43:39 +00001692/// don't make it here. This function serves three purposes:
John McCallaa74a0c2009-08-28 07:59:38 +00001693/// 1) instantiating function templates
1694/// 2) substituting friend declarations
Richard Smith4fa145152017-12-21 19:43:39 +00001695/// 3) substituting deduction guide declarations for nested class templates
Douglas Gregor33636e62009-12-24 20:56:24 +00001696Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001697 TemplateParameterList *TemplateParams) {
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001698 // Check whether there is already a function template specialization for
1699 // this declaration.
1700 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCall2f88d7d2010-03-27 05:57:59 +00001701 if (FunctionTemplate && !TemplateParams) {
Richard Smith47752e42013-05-03 23:46:09 +00001702 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001703
Craig Topperc3ec1492014-05-26 06:22:03 +00001704 void *InsertPos = nullptr;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001705 FunctionDecl *SpecFunc
Craig Topper7e0daca2014-06-26 04:58:53 +00001706 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001707
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001708 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001709 if (SpecFunc)
1710 return SpecFunc;
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001711 }
Mike Stump11289f42009-09-09 15:08:12 +00001712
John McCall2f88d7d2010-03-27 05:57:59 +00001713 bool isFriend;
1714 if (FunctionTemplate)
1715 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1716 else
1717 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1718
Craig Topperc3ec1492014-05-26 06:22:03 +00001719 bool MergeWithParentScope = (TemplateParams != nullptr) ||
Douglas Gregor9f44d142010-05-21 21:25:08 +00001720 Owner->isFunctionOrMethod() ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001721 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001722 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001723 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00001724
Richard Smith76b90272019-05-09 03:59:21 +00001725 ExplicitSpecifier InstantiatedExplicitSpecifier;
1726 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
1727 InstantiatedExplicitSpecifier = instantiateExplicitSpecifier(
1728 SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide);
1729 if (InstantiatedExplicitSpecifier.isInvalid())
1730 return nullptr;
1731 }
1732
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001733 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie4d142962011-11-10 05:42:04 +00001734 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001735 if (!TInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00001736 return nullptr;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001737 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCall58de3582009-08-14 02:03:10 +00001738
Douglas Gregor14454802011-02-25 02:25:35 +00001739 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1740 if (QualifierLoc) {
1741 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1742 TemplateArgs);
1743 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00001744 return nullptr;
John McCalle0b2ddb2010-03-26 04:53:08 +00001745 }
1746
John McCallce410662010-02-06 01:50:47 +00001747 // If we're instantiating a local function declaration, put the result
Richard Smith541b38b2013-09-20 01:15:31 +00001748 // in the enclosing namespace; otherwise we need to find the instantiated
1749 // context.
John McCallce410662010-02-06 01:50:47 +00001750 DeclContext *DC;
Richard Smith541b38b2013-09-20 01:15:31 +00001751 if (D->isLocalExternDecl()) {
John McCallce410662010-02-06 01:50:47 +00001752 DC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001753 SemaRef.adjustContextForLocalExternDecl(DC);
1754 } else if (isFriend && QualifierLoc) {
John McCalle0b2ddb2010-03-26 04:53:08 +00001755 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001756 SS.Adopt(QualifierLoc);
John McCalle0b2ddb2010-03-26 04:53:08 +00001757 DC = SemaRef.computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +00001758 if (!DC) return nullptr;
John McCalle0b2ddb2010-03-26 04:53:08 +00001759 } else {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001760 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001761 TemplateArgs);
John McCalle0b2ddb2010-03-26 04:53:08 +00001762 }
John McCallce410662010-02-06 01:50:47 +00001763
Richard Smith4fa145152017-12-21 19:43:39 +00001764 DeclarationNameInfo NameInfo
1765 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1766
Richard Smithbc491202017-02-17 20:05:37 +00001767 FunctionDecl *Function;
Faisal Vali81b756e2017-10-22 14:45:08 +00001768 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
Richard Smithbc491202017-02-17 20:05:37 +00001769 Function = CXXDeductionGuideDecl::Create(
Richard Smith76b90272019-05-09 03:59:21 +00001770 SemaRef.Context, DC, D->getInnerLocStart(),
1771 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
1772 D->getSourceRange().getEnd());
Faisal Vali81b756e2017-10-22 14:45:08 +00001773 if (DGuide->isCopyDeductionCandidate())
1774 cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate();
Richard Smithc660c8f2018-03-16 13:36:56 +00001775 Function->setAccess(D->getAccess());
Faisal Vali81b756e2017-10-22 14:45:08 +00001776 } else {
Richard Smithbc491202017-02-17 20:05:37 +00001777 Function = FunctionDecl::Create(
Richard Smith4fa145152017-12-21 19:43:39 +00001778 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
Richard Smithbc491202017-02-17 20:05:37 +00001779 D->getCanonicalDecl()->getStorageClass(), D->isInlineSpecified(),
Gauthier Harnisch796ed032019-06-14 08:56:20 +00001780 D->hasWrittenPrototype(), D->getConstexprKind());
Richard Smithbc491202017-02-17 20:05:37 +00001781 Function->setRangeEnd(D->getSourceRange().getEnd());
1782 }
John McCall3e11ebe2010-03-15 10:12:16 +00001783
Richard Smithf3814ad2013-01-25 00:08:28 +00001784 if (D->isInlined())
1785 Function->setImplicitlyInline();
1786
Douglas Gregor14454802011-02-25 02:25:35 +00001787 if (QualifierLoc)
1788 Function->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001789
Richard Smith541b38b2013-09-20 01:15:31 +00001790 if (D->isLocalExternDecl())
1791 Function->setLocalExternDecl();
1792
John McCall30837102010-03-26 23:10:15 +00001793 DeclContext *LexicalDC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001794 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
John McCall30837102010-03-26 23:10:15 +00001795 assert(D->getDeclContext()->isFileContext());
1796 LexicalDC = D->getDeclContext();
1797 }
1798
1799 Function->setLexicalDeclContext(LexicalDC);
Mike Stump11289f42009-09-09 15:08:12 +00001800
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001801 // Attach the parameters
Reid Klecknera09e44c2013-07-31 21:00:18 +00001802 for (unsigned P = 0; P < Params.size(); ++P)
1803 if (Params[P])
1804 Params[P]->setOwningFunction(Function);
David Blaikie9c70e042011-09-21 18:16:56 +00001805 Function->setParams(Params);
John McCallaa74a0c2009-08-28 07:59:38 +00001806
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001807 if (TemplateParams) {
1808 // Our resulting instantiation is actually a function template, since we
1809 // are substituting only the outer template parameters. For example, given
1810 //
1811 // template<typename T>
1812 // struct X {
1813 // template<typename U> friend void f(T, U);
1814 // };
1815 //
1816 // X<int> x;
1817 //
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001818 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001819 // which means substituting int for T, but leaving "f" as a friend function
1820 // template.
1821 // Build the function template itself.
John McCalle0b2ddb2010-03-26 04:53:08 +00001822 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001823 Function->getLocation(),
1824 Function->getDeclName(),
1825 TemplateParams, Function);
1826 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCall30837102010-03-26 23:10:15 +00001827
1828 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalle0b2ddb2010-03-26 04:53:08 +00001829
1830 if (isFriend && D->isThisDeclarationADefinition()) {
John McCalle0b2ddb2010-03-26 04:53:08 +00001831 FunctionTemplate->setInstantiatedFromMemberTemplate(
1832 D->getDescribedFunctionTemplate());
1833 }
Douglas Gregorffe14e32009-11-14 01:20:54 +00001834 } else if (FunctionTemplate) {
1835 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001836 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001837 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001838 TemplateArgumentList::CreateCopy(SemaRef.Context,
David Majnemer8b622692016-07-03 21:17:51 +00001839 Innermost),
Craig Topperc3ec1492014-05-26 06:22:03 +00001840 /*InsertPos=*/nullptr);
Richard Smith152bcd22017-01-28 02:56:07 +00001841 } else if (isFriend && D->isThisDeclarationADefinition()) {
1842 // Do not connect the friend to the template unless it's actually a
1843 // definition. We don't want non-template functions to be marked as being
1844 // template instantiations.
John McCalle0b2ddb2010-03-26 04:53:08 +00001845 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCallaa74a0c2009-08-28 07:59:38 +00001846 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001847
Richard Smith64095fc2019-01-11 01:59:33 +00001848 if (isFriend)
1849 Function->setObjectOfFriendDecl();
1850
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001851 if (InitFunctionInstantiation(Function, D))
1852 Function->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001853
Richard Smith64095fc2019-01-11 01:59:33 +00001854 bool IsExplicitSpecialization = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001855
Richard Smith541b38b2013-09-20 01:15:31 +00001856 LookupResult Previous(
1857 SemaRef, Function->getDeclName(), SourceLocation(),
1858 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1859 : Sema::LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001860 D->isLocalExternDecl() ? Sema::ForExternalRedeclaration
1861 : SemaRef.forRedeclarationInCurContext());
John McCall1f82f242009-11-18 22:49:29 +00001862
John McCallb9c78482010-04-08 09:05:18 +00001863 if (DependentFunctionTemplateSpecializationInfo *Info
1864 = D->getDependentSpecializationInfo()) {
1865 assert(isFriend && "non-friend has dependent specialization info?");
1866
John McCallb9c78482010-04-08 09:05:18 +00001867 // Instantiate the explicit template arguments.
1868 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1869 Info->getRAngleLoc());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001870 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1871 ExplicitArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00001872 return nullptr;
John McCallb9c78482010-04-08 09:05:18 +00001873
1874 // Map the candidate templates to their instantiations.
1875 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1876 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1877 Info->getTemplate(I),
1878 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +00001879 if (!Temp) return nullptr;
John McCallb9c78482010-04-08 09:05:18 +00001880
1881 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1882 }
1883
1884 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1885 &ExplicitArgs,
1886 Previous))
1887 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001888
Richard Smith64095fc2019-01-11 01:59:33 +00001889 IsExplicitSpecialization = true;
1890 } else if (const ASTTemplateArgumentListInfo *Info =
1891 D->getTemplateSpecializationArgsAsWritten()) {
1892 // The name of this function was written as a template-id.
1893 SemaRef.LookupQualifiedName(Previous, DC);
John McCallb9c78482010-04-08 09:05:18 +00001894
Richard Smith64095fc2019-01-11 01:59:33 +00001895 // Instantiate the explicit template arguments.
1896 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1897 Info->getRAngleLoc());
1898 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1899 ExplicitArgs, TemplateArgs))
1900 return nullptr;
1901
1902 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1903 &ExplicitArgs,
1904 Previous))
1905 Function->setInvalidDecl();
1906
1907 IsExplicitSpecialization = true;
John McCallb9c78482010-04-08 09:05:18 +00001908 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001909 // Look only into the namespace where the friend would be declared to
1910 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001911 // as described in ActOnFriendFunctionDecl.
John McCall1f82f242009-11-18 22:49:29 +00001912 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001913
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001914 // In C++, the previous declaration we find might be a tag type
1915 // (class or enum). In this case, the new declaration will hide the
1916 // tag type. Note that this does does not apply if we're declaring a
1917 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001918 if (Previous.isSingleTagDecl())
1919 Previous.clear();
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001920 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001921
Craig Topperc3ec1492014-05-26 06:22:03 +00001922 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
Richard Smith64095fc2019-01-11 01:59:33 +00001923 IsExplicitSpecialization);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001924
John McCallb9467b62010-04-24 01:30:58 +00001925 NamedDecl *PrincipalDecl = (TemplateParams
1926 ? cast<NamedDecl>(FunctionTemplate)
1927 : Function);
1928
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001929 // If the original function was part of a friend declaration,
1930 // inherit its namespace state and add it to the owner.
John McCalle0b2ddb2010-03-26 04:53:08 +00001931 if (isFriend) {
Serge Pavlovacfcd782018-12-06 09:35:04 +00001932 Function->setObjectOfFriendDecl();
1933 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
1934 FT->setObjectOfFriendDecl();
Richard Smith05afe5e2012-03-13 03:12:56 +00001935 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greif718d5152010-08-30 21:10:05 +00001936
Richard Smith91dfaac2014-02-03 02:37:59 +00001937 bool QueuedInstantiation = false;
Gabor Greif718d5152010-08-30 21:10:05 +00001938
Richard Smith91dfaac2014-02-03 02:37:59 +00001939 // C++11 [temp.friend]p4 (DR329):
1940 // When a function is defined in a friend function declaration in a class
1941 // template, the function is instantiated when the function is odr-used.
1942 // The same restrictions on multiple declarations and definitions that
1943 // apply to non-template function declarations and definitions also apply
1944 // to these implicit definitions.
1945 if (D->isThisDeclarationADefinition()) {
Serge Pavlove6e534c2018-03-01 07:04:11 +00001946 SemaRef.CheckForFunctionRedefinition(Function);
1947 if (!Function->isInvalidDecl()) {
1948 for (auto R : Function->redecls()) {
1949 if (R == Function)
1950 continue;
Richard Smith91dfaac2014-02-03 02:37:59 +00001951
Serge Pavlove6e534c2018-03-01 07:04:11 +00001952 // If some prior declaration of this function has been used, we need
1953 // to instantiate its definition.
1954 if (!QueuedInstantiation && R->isUsed(false)) {
1955 if (MemberSpecializationInfo *MSInfo =
1956 Function->getMemberSpecializationInfo()) {
1957 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1958 SourceLocation Loc = R->getLocation(); // FIXME
1959 MSInfo->setPointOfInstantiation(Loc);
1960 SemaRef.PendingLocalImplicitInstantiations.push_back(
1961 std::make_pair(Function, Loc));
1962 QueuedInstantiation = true;
1963 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001964 }
Richard Smith91dfaac2014-02-03 02:37:59 +00001965 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001966 }
1967 }
1968 }
Richard Smithf3597652017-05-10 00:01:13 +00001969
1970 // Check the template parameter list against the previous declaration. The
1971 // goal here is to pick up default arguments added since the friend was
1972 // declared; we know the template parameter lists match, since otherwise
1973 // we would not have picked this template as the previous declaration.
1974 if (TemplateParams && FunctionTemplate->getPreviousDecl()) {
1975 SemaRef.CheckTemplateParameterList(
1976 TemplateParams,
1977 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
1978 Function->isThisDeclarationADefinition()
1979 ? Sema::TPC_FriendFunctionTemplateDefinition
1980 : Sema::TPC_FriendFunctionTemplate);
1981 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001982 }
1983
Richard Smith541b38b2013-09-20 01:15:31 +00001984 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1985 DC->makeDeclVisibleInContext(PrincipalDecl);
1986
John McCallb9467b62010-04-24 01:30:58 +00001987 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1988 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1989 PrincipalDecl->setNonMemberOperator();
1990
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001991 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001992 return Function;
1993}
1994
Richard Smithf19a8b02019-05-02 00:49:14 +00001995Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
1996 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
1997 Optional<const ASTTemplateArgumentListInfo *>
1998 ClassScopeSpecializationArgs) {
Douglas Gregor97628d62009-08-21 00:16:32 +00001999 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregore704c9d2009-08-27 16:57:43 +00002000 if (FunctionTemplate && !TemplateParams) {
Mike Stump11289f42009-09-09 15:08:12 +00002001 // We are creating a function template specialization from a function
2002 // template. Check whether there is already a function template
Douglas Gregore704c9d2009-08-27 16:57:43 +00002003 // specialization for this particular set of template arguments.
Richard Smith47752e42013-05-03 23:46:09 +00002004 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00002005
Craig Topperc3ec1492014-05-26 06:22:03 +00002006 void *InsertPos = nullptr;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00002007 FunctionDecl *SpecFunc
Craig Topper7e0daca2014-06-26 04:58:53 +00002008 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002009
Douglas Gregor97628d62009-08-21 00:16:32 +00002010 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00002011 if (SpecFunc)
2012 return SpecFunc;
Douglas Gregor97628d62009-08-21 00:16:32 +00002013 }
2014
John McCall2f88d7d2010-03-27 05:57:59 +00002015 bool isFriend;
2016 if (FunctionTemplate)
2017 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2018 else
2019 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2020
Craig Topperc3ec1492014-05-26 06:22:03 +00002021 bool MergeWithParentScope = (TemplateParams != nullptr) ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002022 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00002023 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00002024 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor37256522009-05-14 21:44:34 +00002025
John McCalld0e23ec2010-10-19 02:26:41 +00002026 // Instantiate enclosing template arguments for friends.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002027 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCalld0e23ec2010-10-19 02:26:41 +00002028 unsigned NumTempParamLists = 0;
2029 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
Benjamin Kramer9dc549b2015-08-04 14:46:06 +00002030 TempParamLists.resize(NumTempParamLists);
John McCalld0e23ec2010-10-19 02:26:41 +00002031 for (unsigned I = 0; I != NumTempParamLists; ++I) {
2032 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2033 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2034 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002035 return nullptr;
John McCalld0e23ec2010-10-19 02:26:41 +00002036 TempParamLists[I] = InstParams;
2037 }
2038 }
2039
Richard Smith76b90272019-05-09 03:59:21 +00002040 ExplicitSpecifier InstantiatedExplicitSpecifier =
2041 instantiateExplicitSpecifier(SemaRef, TemplateArgs,
2042 ExplicitSpecifier::getFromDecl(D), D);
2043 if (InstantiatedExplicitSpecifier.isInvalid())
2044 return nullptr;
2045
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002046 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramer1dd48bc2012-01-20 14:42:32 +00002047 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00002048 if (!TInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00002049 return nullptr;
Douglas Gregor89f593a2012-09-13 21:56:43 +00002050 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002051
Douglas Gregor14454802011-02-25 02:25:35 +00002052 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2053 if (QualifierLoc) {
2054 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCall2f88d7d2010-03-27 05:57:59 +00002055 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002056 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002057 return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00002058 }
2059
2060 DeclContext *DC = Owner;
2061 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +00002062 if (QualifierLoc) {
John McCall2f88d7d2010-03-27 05:57:59 +00002063 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00002064 SS.Adopt(QualifierLoc);
John McCall2f88d7d2010-03-27 05:57:59 +00002065 DC = SemaRef.computeDeclContext(SS);
John McCall1a1b53e2010-10-19 05:01:53 +00002066
2067 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
Craig Topperc3ec1492014-05-26 06:22:03 +00002068 return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00002069 } else {
2070 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2071 D->getDeclContext(),
2072 TemplateArgs);
2073 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002074 if (!DC) return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00002075 }
2076
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002077 // Build the instantiated method declaration.
John McCall2f88d7d2010-03-27 05:57:59 +00002078 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Craig Topperc3ec1492014-05-26 06:22:03 +00002079 CXXMethodDecl *Method = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002080
Abramo Bagnaradff19302011-03-08 08:55:46 +00002081 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002082 DeclarationNameInfo NameInfo
2083 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregore8394862009-08-21 22:43:28 +00002084 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Richard Smith76b90272019-05-09 03:59:21 +00002085 Method = CXXConstructorDecl::Create(
2086 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2087 InstantiatedExplicitSpecifier, Constructor->isInlineSpecified(), false,
Gauthier Harnisch796ed032019-06-14 08:56:20 +00002088 Constructor->getConstexprKind());
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002089 Method->setRangeEnd(Constructor->getEndLoc());
Douglas Gregore8394862009-08-21 22:43:28 +00002090 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregore8394862009-08-21 22:43:28 +00002091 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002092 StartLoc, NameInfo, T, TInfo,
Reid Kleckner0f764e52015-04-07 20:46:51 +00002093 Destructor->isInlineSpecified(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002094 false);
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002095 Method->setRangeEnd(Destructor->getEndLoc());
Douglas Gregor05155d82009-08-21 23:19:43 +00002096 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002097 Method = CXXConversionDecl::Create(
2098 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
Richard Smith76b90272019-05-09 03:59:21 +00002099 Conversion->isInlineSpecified(), InstantiatedExplicitSpecifier,
Gauthier Harnisch796ed032019-06-14 08:56:20 +00002100 Conversion->getConstexprKind(), Conversion->getEndLoc());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002101 } else {
Rafael Espindola29cda592013-04-15 12:38:20 +00002102 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002103 Method = CXXMethodDecl::Create(SemaRef.Context, Record, StartLoc, NameInfo,
2104 T, TInfo, SC, D->isInlineSpecified(),
Gauthier Harnisch796ed032019-06-14 08:56:20 +00002105 D->getConstexprKind(), D->getEndLoc());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002106 }
Douglas Gregor97628d62009-08-21 00:16:32 +00002107
Richard Smithf3814ad2013-01-25 00:08:28 +00002108 if (D->isInlined())
2109 Method->setImplicitlyInline();
2110
Douglas Gregor14454802011-02-25 02:25:35 +00002111 if (QualifierLoc)
2112 Method->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00002113
Douglas Gregore704c9d2009-08-27 16:57:43 +00002114 if (TemplateParams) {
2115 // Our resulting instantiation is actually a function template, since we
2116 // are substituting only the outer template parameters. For example, given
Mike Stump11289f42009-09-09 15:08:12 +00002117 //
Douglas Gregore704c9d2009-08-27 16:57:43 +00002118 // template<typename T>
2119 // struct X {
2120 // template<typename U> void f(T, U);
2121 // };
2122 //
2123 // X<int> x;
2124 //
2125 // We are instantiating the member template "f" within X<int>, which means
2126 // substituting int for T, but leaving "f" as a member function template.
2127 // Build the function template itself.
2128 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2129 Method->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002130 Method->getDeclName(),
Douglas Gregore704c9d2009-08-27 16:57:43 +00002131 TemplateParams, Method);
John McCall2f88d7d2010-03-27 05:57:59 +00002132 if (isFriend) {
2133 FunctionTemplate->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00002134 FunctionTemplate->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00002135 } else if (D->isOutOfLine())
Mike Stump11289f42009-09-09 15:08:12 +00002136 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregore704c9d2009-08-27 16:57:43 +00002137 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002138 } else if (FunctionTemplate) {
2139 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00002140 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00002141 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002142 TemplateArgumentList::CreateCopy(SemaRef.Context,
David Majnemer8b622692016-07-03 21:17:51 +00002143 Innermost),
Craig Topperc3ec1492014-05-26 06:22:03 +00002144 /*InsertPos=*/nullptr);
John McCall2f88d7d2010-03-27 05:57:59 +00002145 } else if (!isFriend) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00002146 // Record that this is an instantiation of a member function.
Douglas Gregord801b062009-10-07 23:56:10 +00002147 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002148 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002149
Mike Stump11289f42009-09-09 15:08:12 +00002150 // If we are instantiating a member function defined
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002151 // out-of-line, the instantiation will have the same lexical
2152 // context (which will be a namespace scope) as the template.
John McCall2f88d7d2010-03-27 05:57:59 +00002153 if (isFriend) {
John McCalld0e23ec2010-10-19 02:26:41 +00002154 if (NumTempParamLists)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00002155 Method->setTemplateParameterListsInfo(
2156 SemaRef.Context,
2157 llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
John McCalld0e23ec2010-10-19 02:26:41 +00002158
John McCall2f88d7d2010-03-27 05:57:59 +00002159 Method->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00002160 Method->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00002161 } else if (D->isOutOfLine())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002162 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00002163
Douglas Gregor21342092009-03-24 00:38:23 +00002164 // Attach the parameters
2165 for (unsigned P = 0; P < Params.size(); ++P)
2166 Params[P]->setOwningFunction(Method);
David Blaikie9c70e042011-09-21 18:16:56 +00002167 Method->setParams(Params);
Douglas Gregor21342092009-03-24 00:38:23 +00002168
2169 if (InitMethodInstantiation(Method, D))
2170 Method->setInvalidDecl();
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002171
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002172 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00002173 Sema::ForExternalRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00002174
Richard Smith64095fc2019-01-11 01:59:33 +00002175 bool IsExplicitSpecialization = false;
2176
2177 // If the name of this function was written as a template-id, instantiate
2178 // the explicit template arguments.
2179 if (DependentFunctionTemplateSpecializationInfo *Info
2180 = D->getDependentSpecializationInfo()) {
2181 assert(isFriend && "non-friend has dependent specialization info?");
2182
2183 // Instantiate the explicit template arguments.
2184 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2185 Info->getRAngleLoc());
2186 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2187 ExplicitArgs, TemplateArgs))
2188 return nullptr;
2189
2190 // Map the candidate templates to their instantiations.
2191 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
2192 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2193 Info->getTemplate(I),
2194 TemplateArgs);
2195 if (!Temp) return nullptr;
2196
2197 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2198 }
2199
2200 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2201 &ExplicitArgs,
2202 Previous))
2203 Method->setInvalidDecl();
2204
2205 IsExplicitSpecialization = true;
2206 } else if (const ASTTemplateArgumentListInfo *Info =
Richard Smithf19a8b02019-05-02 00:49:14 +00002207 ClassScopeSpecializationArgs.getValueOr(
2208 D->getTemplateSpecializationArgsAsWritten())) {
Richard Smith64095fc2019-01-11 01:59:33 +00002209 SemaRef.LookupQualifiedName(Previous, DC);
2210
2211 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2212 Info->getRAngleLoc());
2213 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2214 ExplicitArgs, TemplateArgs))
2215 return nullptr;
2216
2217 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2218 &ExplicitArgs,
2219 Previous))
2220 Method->setInvalidDecl();
2221
2222 IsExplicitSpecialization = true;
Richard Smithf19a8b02019-05-02 00:49:14 +00002223 } else if (ClassScopeSpecializationArgs) {
2224 // Class-scope explicit specialization written without explicit template
2225 // arguments.
2226 SemaRef.LookupQualifiedName(Previous, DC);
2227 if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous))
2228 Method->setInvalidDecl();
2229
2230 IsExplicitSpecialization = true;
Richard Smith64095fc2019-01-11 01:59:33 +00002231 } else if (!FunctionTemplate || TemplateParams || isFriend) {
John McCall2f88d7d2010-03-27 05:57:59 +00002232 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump11289f42009-09-09 15:08:12 +00002233
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002234 // In C++, the previous declaration we find might be a tag type
2235 // (class or enum). In this case, the new declaration will hide the
2236 // tag type. Note that this does does not apply if we're declaring a
2237 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00002238 if (Previous.isSingleTagDecl())
2239 Previous.clear();
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002240 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002241
Richard Smithf19a8b02019-05-02 00:49:14 +00002242 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2243 IsExplicitSpecialization);
Douglas Gregor05155d82009-08-21 23:19:43 +00002244
Douglas Gregor21920e372009-12-01 17:24:26 +00002245 if (D->isPure())
2246 SemaRef.CheckPureMethod(Method, SourceRange());
2247
John McCalla0a96892012-08-10 03:15:35 +00002248 // Propagate access. For a non-friend declaration, the access is
2249 // whatever we're propagating from. For a friend, it should be the
2250 // previous declaration we just found.
2251 if (isFriend && Method->getPreviousDecl())
2252 Method->setAccess(Method->getPreviousDecl()->getAccess());
Fangrui Song6907ce22018-07-30 19:24:48 +00002253 else
John McCalla0a96892012-08-10 03:15:35 +00002254 Method->setAccess(D->getAccess());
2255 if (FunctionTemplate)
2256 FunctionTemplate->setAccess(Method->getAccess());
John McCall401982f2010-01-20 21:53:11 +00002257
Anders Carlsson7c812f52011-01-20 06:52:44 +00002258 SemaRef.CheckOverrideControl(Method);
2259
Eli Friedman41340732011-11-15 22:39:08 +00002260 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smith92f241f2012-12-08 02:53:02 +00002261 if (D->isExplicitlyDefaulted())
2262 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00002263 if (D->isDeletedAsWritten())
Richard Smith92f241f2012-12-08 02:53:02 +00002264 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00002265
Richard Smithf19a8b02019-05-02 00:49:14 +00002266 // If this is an explicit specialization, mark the implicitly-instantiated
2267 // template specialization as being an explicit specialization too.
2268 // FIXME: Is this necessary?
2269 if (IsExplicitSpecialization && !isFriend)
2270 SemaRef.CompleteMemberSpecialization(Method, Previous);
2271
John McCalla0a96892012-08-10 03:15:35 +00002272 // If there's a function template, let our caller handle it.
John McCall2f88d7d2010-03-27 05:57:59 +00002273 if (FunctionTemplate) {
John McCalla0a96892012-08-10 03:15:35 +00002274 // do nothing
2275
2276 // Don't hide a (potentially) valid declaration with an invalid one.
John McCall2f88d7d2010-03-27 05:57:59 +00002277 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCalla0a96892012-08-10 03:15:35 +00002278 // do nothing
2279
2280 // Otherwise, check access to friends and make them visible.
2281 } else if (isFriend) {
2282 // We only need to re-check access for methods which we didn't
2283 // manage to match during parsing.
2284 if (!D->getPreviousDecl())
2285 SemaRef.CheckFriendAccess(Method);
2286
2287 Record->makeDeclVisibleInContext(Method);
2288
2289 // Otherwise, add the declaration. We don't need to do this for
2290 // class-scope specializations because we'll have matched them with
2291 // the appropriate template.
Richard Smithf19a8b02019-05-02 00:49:14 +00002292 } else {
John McCalla0a96892012-08-10 03:15:35 +00002293 Owner->addDecl(Method);
John McCall2f88d7d2010-03-27 05:57:59 +00002294 }
Alexis Hunt1fb4e762011-05-23 21:07:59 +00002295
Rafael Auler9dde31e2019-03-20 19:22:24 +00002296 // PR17480: Honor the used attribute to instantiate member function
2297 // definitions
2298 if (Method->hasAttr<UsedAttr>()) {
2299 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2300 SourceLocation Loc;
2301 if (const MemberSpecializationInfo *MSInfo =
2302 A->getMemberSpecializationInfo())
2303 Loc = MSInfo->getPointOfInstantiation();
2304 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2305 Loc = Spec->getPointOfInstantiation();
2306 SemaRef.MarkFunctionReferenced(Loc, Method);
2307 }
2308 }
2309
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002310 return Method;
2311}
2312
Douglas Gregor4044d992009-03-24 16:43:20 +00002313Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002314 return VisitCXXMethodDecl(D);
Douglas Gregor4044d992009-03-24 16:43:20 +00002315}
2316
Douglas Gregor654b07e2009-03-24 00:15:49 +00002317Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore8394862009-08-21 22:43:28 +00002318 return VisitCXXMethodDecl(D);
Douglas Gregor654b07e2009-03-24 00:15:49 +00002319}
2320
Douglas Gregor1880ba52009-03-25 00:34:44 +00002321Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002322 return VisitCXXMethodDecl(D);
Douglas Gregor1880ba52009-03-25 00:34:44 +00002323}
2324
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002325Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie7a30dc52013-02-21 01:47:18 +00002326 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
2327 /*ExpectParameterPack=*/ false);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002328}
2329
John McCall87a44eb2009-08-20 01:44:21 +00002330Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2331 TemplateTypeParmDecl *D) {
2332 // TODO: don't always clone when decls are refcounted.
Chandler Carruth08836322011-05-01 00:51:33 +00002333 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump11289f42009-09-09 15:08:12 +00002334
Richard Smithb4f96252017-02-21 06:30:38 +00002335 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002336 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
Richard Smithb4f96252017-02-21 06:30:38 +00002337 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2338 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack());
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002339 Inst->setAccess(AS_public);
John McCall87a44eb2009-08-20 01:44:21 +00002340
Richard Smith52933792015-06-16 21:57:05 +00002341 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
David Majnemer89189202013-08-28 23:48:32 +00002342 TypeSourceInfo *InstantiatedDefaultArg =
2343 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2344 D->getDefaultArgumentLoc(), D->getDeclName());
2345 if (InstantiatedDefaultArg)
Richard Smith1469b912015-06-10 00:29:03 +00002346 Inst->setDefaultArgument(InstantiatedDefaultArg);
David Majnemer89189202013-08-28 23:48:32 +00002347 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002348
2349 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00002350 // scope.
2351 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002352
John McCall87a44eb2009-08-20 01:44:21 +00002353 return Inst;
2354}
2355
Douglas Gregor6b815c82009-10-23 23:25:44 +00002356Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2357 NonTypeTemplateParmDecl *D) {
2358 // Substitute into the type of the non-type template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002359 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002360 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2361 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002362 bool IsExpandedParameterPack = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002363 TypeSourceInfo *DI;
Douglas Gregor6b815c82009-10-23 23:25:44 +00002364 QualType T;
Douglas Gregor6b815c82009-10-23 23:25:44 +00002365 bool Invalid = false;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002366
2367 if (D->isExpandedParameterPack()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002368 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002369 // expansion of types. Substitute into each of the expanded types.
2370 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2371 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2372 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
Richard Smith15361a22016-12-28 06:27:18 +00002373 TypeSourceInfo *NewDI =
2374 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2375 D->getLocation(), D->getDeclName());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002376 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002377 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002378
Richard Smith15361a22016-12-28 06:27:18 +00002379 QualType NewT =
2380 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002381 if (NewT.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00002382 return nullptr;
Richard Smith15361a22016-12-28 06:27:18 +00002383
2384 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002385 ExpandedParameterPackTypes.push_back(NewT);
2386 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002387
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002388 IsExpandedParameterPack = true;
2389 DI = D->getTypeSourceInfo();
2390 T = DI->getType();
Richard Smith1fde8ec2012-09-07 02:06:42 +00002391 } else if (D->isPackExpansion()) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002392 // The non-type template parameter pack's type is a pack expansion of types.
2393 // Determine whether we need to expand this parameter pack into separate
2394 // types.
David Blaikie6adc78e2013-02-18 22:06:02 +00002395 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002396 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002397 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002398 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002399
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002400 // Determine whether the set of unexpanded parameter packs can and should
2401 // be expanded.
2402 bool Expand = true;
2403 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00002404 Optional<unsigned> OrigNumExpansions
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002405 = Expansion.getTypePtr()->getNumExpansions();
David Blaikie05785d12013-02-20 22:23:23 +00002406 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002407 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2408 Pattern.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00002409 Unexpanded,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002410 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002411 Expand, RetainExpansion,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002412 NumExpansions))
Craig Topperc3ec1492014-05-26 06:22:03 +00002413 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002414
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002415 if (Expand) {
2416 for (unsigned I = 0; I != *NumExpansions; ++I) {
2417 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2418 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002419 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002420 D->getDeclName());
2421 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002422 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002423
Richard Smith15361a22016-12-28 06:27:18 +00002424 QualType NewT =
2425 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002426 if (NewT.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00002427 return nullptr;
Richard Smith15361a22016-12-28 06:27:18 +00002428
2429 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002430 ExpandedParameterPackTypes.push_back(NewT);
2431 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002432
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002433 // Note that we have an expanded parameter pack. The "type" of this
2434 // expanded parameter pack is the original expansion type, but callers
2435 // will end up using the expanded parameter pack types for type-checking.
2436 IsExpandedParameterPack = true;
2437 DI = D->getTypeSourceInfo();
2438 T = DI->getType();
2439 } else {
2440 // We cannot fully expand the pack expansion now, so substitute into the
2441 // pattern and create a new pack expansion type.
2442 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2443 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002444 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002445 D->getDeclName());
2446 if (!NewPattern)
Craig Topperc3ec1492014-05-26 06:22:03 +00002447 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002448
Richard Smith15361a22016-12-28 06:27:18 +00002449 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002450 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2451 NumExpansions);
2452 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002453 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002454
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002455 T = DI->getType();
2456 }
2457 } else {
2458 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002459 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002460 D->getLocation(), D->getDeclName());
2461 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002462 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002463
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002464 // Check that this type is acceptable for a non-type template parameter.
Richard Smith15361a22016-12-28 06:27:18 +00002465 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002466 if (T.isNull()) {
2467 T = SemaRef.Context.IntTy;
2468 Invalid = true;
2469 }
Douglas Gregor6b815c82009-10-23 23:25:44 +00002470 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002471
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002472 NonTypeTemplateParmDecl *Param;
2473 if (IsExpandedParameterPack)
David Majnemerdfecf1a2016-07-06 04:19:16 +00002474 Param = NonTypeTemplateParmDecl::Create(
2475 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
Richard Smithb4f96252017-02-21 06:30:38 +00002476 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2477 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
David Majnemerdfecf1a2016-07-06 04:19:16 +00002478 ExpandedParameterPackTypesAsWritten);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002479 else
Richard Smithb4f96252017-02-21 06:30:38 +00002480 Param = NonTypeTemplateParmDecl::Create(
2481 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2482 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2483 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002484
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002485 Param->setAccess(AS_public);
Douglas Gregor6b815c82009-10-23 23:25:44 +00002486 if (Invalid)
2487 Param->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002488
Richard Smith52933792015-06-16 21:57:05 +00002489 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
Faisal Valid143a0c2017-04-01 21:30:49 +00002490 EnterExpressionEvaluationContext ConstantEvaluated(
2491 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00002492 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2493 if (!Value.isInvalid())
Richard Smith1469b912015-06-10 00:29:03 +00002494 Param->setDefaultArgument(Value.get());
David Majnemer89189202013-08-28 23:48:32 +00002495 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002496
2497 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00002498 // scope.
2499 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor6b815c82009-10-23 23:25:44 +00002500 return Param;
2501}
2502
Richard Smith1fde8ec2012-09-07 02:06:42 +00002503static void collectUnexpandedParameterPacks(
2504 Sema &S,
2505 TemplateParameterList *Params,
2506 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Davide Italiano18960b92015-07-02 19:20:11 +00002507 for (const auto &P : *Params) {
2508 if (P->isTemplateParameterPack())
Richard Smith1fde8ec2012-09-07 02:06:42 +00002509 continue;
Davide Italiano18960b92015-07-02 19:20:11 +00002510 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
Richard Smith1fde8ec2012-09-07 02:06:42 +00002511 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2512 Unexpanded);
Davide Italiano18960b92015-07-02 19:20:11 +00002513 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
Richard Smith1fde8ec2012-09-07 02:06:42 +00002514 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2515 Unexpanded);
2516 }
2517}
2518
Anders Carlsson4bd78752009-08-28 15:18:15 +00002519Decl *
Douglas Gregor38fee962009-11-11 16:58:32 +00002520TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2521 TemplateTemplateParmDecl *D) {
2522 // Instantiate the template parameter list of the template template parameter.
2523 TemplateParameterList *TempParams = D->getTemplateParameters();
2524 TemplateParameterList *InstParams;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002525 SmallVector<TemplateParameterList*, 8> ExpandedParams;
2526
2527 bool IsExpandedParameterPack = false;
2528
2529 if (D->isExpandedParameterPack()) {
2530 // The template template parameter pack is an already-expanded pack
2531 // expansion of template parameters. Substitute into each of the expanded
2532 // parameters.
2533 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2534 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2535 I != N; ++I) {
2536 LocalInstantiationScope Scope(SemaRef);
2537 TemplateParameterList *Expansion =
2538 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2539 if (!Expansion)
Craig Topperc3ec1492014-05-26 06:22:03 +00002540 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002541 ExpandedParams.push_back(Expansion);
2542 }
2543
2544 IsExpandedParameterPack = true;
2545 InstParams = TempParams;
2546 } else if (D->isPackExpansion()) {
2547 // The template template parameter pack expands to a pack of template
2548 // template parameters. Determine whether we need to expand this parameter
2549 // pack into separate parameters.
2550 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2551 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2552 Unexpanded);
2553
2554 // Determine whether the set of unexpanded parameter packs can and should
2555 // be expanded.
2556 bool Expand = true;
2557 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00002558 Optional<unsigned> NumExpansions;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002559 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2560 TempParams->getSourceRange(),
2561 Unexpanded,
2562 TemplateArgs,
2563 Expand, RetainExpansion,
2564 NumExpansions))
Craig Topperc3ec1492014-05-26 06:22:03 +00002565 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002566
2567 if (Expand) {
2568 for (unsigned I = 0; I != *NumExpansions; ++I) {
2569 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2570 LocalInstantiationScope Scope(SemaRef);
2571 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2572 if (!Expansion)
Craig Topperc3ec1492014-05-26 06:22:03 +00002573 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002574 ExpandedParams.push_back(Expansion);
2575 }
2576
2577 // Note that we have an expanded parameter pack. The "type" of this
2578 // expanded parameter pack is the original expansion type, but callers
2579 // will end up using the expanded parameter pack types for type-checking.
2580 IsExpandedParameterPack = true;
2581 InstParams = TempParams;
2582 } else {
2583 // We cannot fully expand the pack expansion now, so just substitute
2584 // into the pattern.
2585 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2586
2587 LocalInstantiationScope Scope(SemaRef);
2588 InstParams = SubstTemplateParams(TempParams);
2589 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002590 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002591 }
2592 } else {
Douglas Gregor38fee962009-11-11 16:58:32 +00002593 // Perform the actual substitution of template parameters within a new,
2594 // local instantiation scope.
John McCall19c1bfd2010-08-25 05:32:35 +00002595 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor38fee962009-11-11 16:58:32 +00002596 InstParams = SubstTemplateParams(TempParams);
2597 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002598 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002599 }
2600
Douglas Gregor38fee962009-11-11 16:58:32 +00002601 // Build the template template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002602 TemplateTemplateParmDecl *Param;
2603 if (IsExpandedParameterPack)
Richard Smithb4f96252017-02-21 06:30:38 +00002604 Param = TemplateTemplateParmDecl::Create(
2605 SemaRef.Context, Owner, D->getLocation(),
2606 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2607 D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
Richard Smith1fde8ec2012-09-07 02:06:42 +00002608 else
Richard Smithb4f96252017-02-21 06:30:38 +00002609 Param = TemplateTemplateParmDecl::Create(
2610 SemaRef.Context, Owner, D->getLocation(),
2611 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2612 D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
Richard Smith52933792015-06-16 21:57:05 +00002613 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
David Majnemer89189202013-08-28 23:48:32 +00002614 NestedNameSpecifierLoc QualifierLoc =
2615 D->getDefaultArgument().getTemplateQualifierLoc();
2616 QualifierLoc =
2617 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2618 TemplateName TName = SemaRef.SubstTemplateName(
2619 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2620 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2621 if (!TName.isNull())
2622 Param->setDefaultArgument(
Richard Smith1469b912015-06-10 00:29:03 +00002623 SemaRef.Context,
David Majnemer89189202013-08-28 23:48:32 +00002624 TemplateArgumentLoc(TemplateArgument(TName),
2625 D->getDefaultArgument().getTemplateQualifierLoc(),
Richard Smith1469b912015-06-10 00:29:03 +00002626 D->getDefaultArgument().getTemplateNameLoc()));
David Majnemer89189202013-08-28 23:48:32 +00002627 }
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002628 Param->setAccess(AS_public);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002629
2630 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor38fee962009-11-11 16:58:32 +00002631 // scope.
2632 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002633
Douglas Gregor38fee962009-11-11 16:58:32 +00002634 return Param;
2635}
2636
Douglas Gregore0b28662009-11-17 06:07:40 +00002637Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregor12441b32011-02-25 16:33:46 +00002638 // Using directives are never dependent (and never contain any types or
2639 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002640
Douglas Gregore0b28662009-11-17 06:07:40 +00002641 UsingDirectiveDecl *Inst
2642 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002643 D->getNamespaceKeyLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00002644 D->getQualifierLoc(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002645 D->getIdentLocation(),
2646 D->getNominatedNamespace(),
Douglas Gregore0b28662009-11-17 06:07:40 +00002647 D->getCommonAncestor());
Abramo Bagnara8843f9f2012-09-05 09:55:10 +00002648
2649 // Add the using directive to its declaration context
2650 // only if this is not a function or method.
2651 if (!Owner->isFunctionOrMethod())
2652 Owner->addDecl(Inst);
2653
Douglas Gregore0b28662009-11-17 06:07:40 +00002654 return Inst;
2655}
2656
John McCallb96ec562009-12-04 22:46:56 +00002657Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorac2e4302010-09-29 17:58:28 +00002658
2659 // The nested name specifier may be dependent, for example
2660 // template <typename T> struct t {
2661 // struct s1 { T f1(); };
2662 // struct s2 : s1 { using s1::f1; };
2663 // };
2664 // template struct t<int>;
2665 // Here, in using s1::f1, s1 refers to t<T>::s1;
2666 // we need to substitute for t<int>::s1.
Douglas Gregor0499ab62011-02-25 15:54:31 +00002667 NestedNameSpecifierLoc QualifierLoc
2668 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2669 TemplateArgs);
2670 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002671 return nullptr;
Douglas Gregorac2e4302010-09-29 17:58:28 +00002672
Richard Smith5179eb72016-06-28 19:03:57 +00002673 // For an inheriting constructor declaration, the name of the using
2674 // declaration is the name of a constructor in this class, not in the
2675 // base class.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002676 DeclarationNameInfo NameInfo = D->getNameInfo();
Richard Smith5179eb72016-06-28 19:03:57 +00002677 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2678 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
2679 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
2680 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
John McCallb96ec562009-12-04 22:46:56 +00002681
John McCall84d87672009-12-10 09:41:52 +00002682 // We only need to do redeclaration lookups if we're in a class
2683 // scope (in fact, it's not really even possible in non-class
2684 // scopes).
2685 bool CheckRedeclaration = Owner->isRecord();
2686
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002687 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
Richard Smithbecb92d2017-10-10 22:33:17 +00002688 Sema::ForVisibleRedeclaration);
John McCall84d87672009-12-10 09:41:52 +00002689
John McCallb96ec562009-12-04 22:46:56 +00002690 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002691 D->getUsingLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002692 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002693 NameInfo,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002694 D->hasTypename());
John McCallb96ec562009-12-04 22:46:56 +00002695
Douglas Gregor0499ab62011-02-25 15:54:31 +00002696 CXXScopeSpec SS;
2697 SS.Adopt(QualifierLoc);
John McCall84d87672009-12-10 09:41:52 +00002698 if (CheckRedeclaration) {
2699 Prev.setHideTags(false);
2700 SemaRef.LookupQualifiedName(Prev, Owner);
2701
2702 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002703 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2704 D->hasTypename(), SS,
John McCall84d87672009-12-10 09:41:52 +00002705 D->getLocation(), Prev))
2706 NewUD->setInvalidDecl();
2707
2708 }
2709
2710 if (!NewUD->isInvalidDecl() &&
Richard Smithd8a9e372016-12-18 21:39:37 +00002711 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(),
2712 SS, NameInfo, D->getLocation()))
John McCallb96ec562009-12-04 22:46:56 +00002713 NewUD->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00002714
John McCallb96ec562009-12-04 22:46:56 +00002715 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2716 NewUD->setAccess(D->getAccess());
2717 Owner->addDecl(NewUD);
2718
John McCall84d87672009-12-10 09:41:52 +00002719 // Don't process the shadow decls for an invalid decl.
2720 if (NewUD->isInvalidDecl())
2721 return NewUD;
2722
Richard Smith5179eb72016-06-28 19:03:57 +00002723 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
Richard Smith09d5b3a2014-05-01 00:35:04 +00002724 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
Richard Smith23d55872012-04-02 01:30:27 +00002725
John McCalla1d85502009-12-22 22:26:37 +00002726 bool isFunctionScope = Owner->isFunctionOrMethod();
2727
John McCall84d87672009-12-10 09:41:52 +00002728 // Process the shadow decls.
Aaron Ballman91cdc282014-03-13 18:07:29 +00002729 for (auto *Shadow : D->shadows()) {
Richard Smith5179eb72016-06-28 19:03:57 +00002730 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
2731 // reconstruct it in the case where it matters.
2732 NamedDecl *OldTarget = Shadow->getTargetDecl();
2733 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
2734 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
2735 OldTarget = BaseShadow;
2736
John McCall84d87672009-12-10 09:41:52 +00002737 NamedDecl *InstTarget =
Richard Smithfd8634a2013-10-23 02:17:46 +00002738 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
Richard Smith5179eb72016-06-28 19:03:57 +00002739 Shadow->getLocation(), OldTarget, TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00002740 if (!InstTarget)
Craig Topperc3ec1492014-05-26 06:22:03 +00002741 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00002742
Craig Topperc3ec1492014-05-26 06:22:03 +00002743 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00002744 if (CheckRedeclaration) {
2745 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2746 continue;
Richard Smith41c79d92014-10-11 00:37:16 +00002747 } else if (UsingShadowDecl *OldPrev =
2748 getPreviousDeclForInstantiation(Shadow)) {
Richard Smithfd8634a2013-10-23 02:17:46 +00002749 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2750 Shadow->getLocation(), OldPrev, TemplateArgs));
2751 }
John McCall84d87672009-12-10 09:41:52 +00002752
Richard Smithfd8634a2013-10-23 02:17:46 +00002753 UsingShadowDecl *InstShadow =
Craig Topperc3ec1492014-05-26 06:22:03 +00002754 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2755 PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00002756 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCalla1d85502009-12-22 22:26:37 +00002757
2758 if (isFunctionScope)
2759 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall84d87672009-12-10 09:41:52 +00002760 }
John McCallb96ec562009-12-04 22:46:56 +00002761
2762 return NewUD;
2763}
2764
2765Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall84d87672009-12-10 09:41:52 +00002766 // Ignore these; we handle them in bulk when processing the UsingDecl.
Craig Topperc3ec1492014-05-26 06:22:03 +00002767 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00002768}
2769
Richard Smith5179eb72016-06-28 19:03:57 +00002770Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
2771 ConstructorUsingShadowDecl *D) {
2772 // Ignore these; we handle them in bulk when processing the UsingDecl.
2773 return nullptr;
2774}
2775
Richard Smith151c4562016-12-20 21:35:28 +00002776template <typename T>
2777Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
2778 T *D, bool InstantiatingPackElement) {
2779 // If this is a pack expansion, expand it now.
2780 if (D->isPackExpansion() && !InstantiatingPackElement) {
2781 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2782 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
2783 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
2784
2785 // Determine whether the set of unexpanded parameter packs can and should
2786 // be expanded.
2787 bool Expand = true;
2788 bool RetainExpansion = false;
2789 Optional<unsigned> NumExpansions;
2790 if (SemaRef.CheckParameterPacksForExpansion(
2791 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
2792 Expand, RetainExpansion, NumExpansions))
2793 return nullptr;
2794
2795 // This declaration cannot appear within a function template signature,
2796 // so we can't have a partial argument list for a parameter pack.
2797 assert(!RetainExpansion &&
2798 "should never need to retain an expansion for UsingPackDecl");
2799
2800 if (!Expand) {
2801 // We cannot fully expand the pack expansion now, so substitute into the
2802 // pattern and create a new pack expansion.
2803 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2804 return instantiateUnresolvedUsingDecl(D, true);
2805 }
2806
2807 // Within a function, we don't have any normal way to check for conflicts
2808 // between shadow declarations from different using declarations in the
2809 // same pack expansion, but this is always ill-formed because all expansions
2810 // must produce (conflicting) enumerators.
2811 //
2812 // Sadly we can't just reject this in the template definition because it
2813 // could be valid if the pack is empty or has exactly one expansion.
2814 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
2815 SemaRef.Diag(D->getEllipsisLoc(),
2816 diag::err_using_decl_redeclaration_expansion);
2817 return nullptr;
2818 }
2819
2820 // Instantiate the slices of this pack and build a UsingPackDecl.
2821 SmallVector<NamedDecl*, 8> Expansions;
2822 for (unsigned I = 0; I != *NumExpansions; ++I) {
2823 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2824 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
2825 if (!Slice)
2826 return nullptr;
2827 // Note that we can still get unresolved using declarations here, if we
2828 // had arguments for all packs but the pattern also contained other
2829 // template arguments (this only happens during partial substitution, eg
2830 // into the body of a generic lambda in a function template).
2831 Expansions.push_back(cast<NamedDecl>(Slice));
2832 }
2833
2834 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2835 if (isDeclWithinFunction(D))
2836 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2837 return NewD;
2838 }
2839
2840 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
2841 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
2842
Douglas Gregor0499ab62011-02-25 15:54:31 +00002843 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002844 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002845 TemplateArgs);
2846 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002847 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002848
Anders Carlsson4bd78752009-08-28 15:18:15 +00002849 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002850 SS.Adopt(QualifierLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002851
Daniel Jasper9949ead2016-12-19 10:09:25 +00002852 DeclarationNameInfo NameInfo
2853 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2854
Richard Smith151c4562016-12-20 21:35:28 +00002855 // Produce a pack expansion only if we're not instantiating a particular
2856 // slice of a pack expansion.
2857 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
2858 SemaRef.ArgumentPackSubstitutionIndex != -1;
2859 SourceLocation EllipsisLoc =
2860 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
2861
2862 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
2863 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
Erich Keanec480f302018-07-12 21:09:05 +00002864 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
2865 ParsedAttributesView(),
Richard Smith151c4562016-12-20 21:35:28 +00002866 /*IsInstantiation*/ true);
Daniel Jasper9949ead2016-12-19 10:09:25 +00002867 if (UD)
2868 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
2869
2870 return UD;
Richard Smith22a250c2016-12-19 04:08:53 +00002871}
2872
Richard Smith151c4562016-12-20 21:35:28 +00002873Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
2874 UnresolvedUsingTypenameDecl *D) {
2875 return instantiateUnresolvedUsingDecl(D);
2876}
2877
2878Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
2879 UnresolvedUsingValueDecl *D) {
2880 return instantiateUnresolvedUsingDecl(D);
2881}
2882
2883Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
2884 SmallVector<NamedDecl*, 8> Expansions;
2885 for (auto *UD : D->expansions()) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00002886 if (NamedDecl *NewUD =
Richard Smith151c4562016-12-20 21:35:28 +00002887 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
George Burgess IV00f70bd2018-03-01 05:43:23 +00002888 Expansions.push_back(NewUD);
Richard Smith151c4562016-12-20 21:35:28 +00002889 else
2890 return nullptr;
2891 }
2892
2893 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2894 if (isDeclWithinFunction(D))
2895 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2896 return NewD;
2897}
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002898
2899Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
Richard Smith6e671422018-12-04 22:26:32 +00002900 ClassScopeFunctionSpecializationDecl *Decl) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002901 CXXMethodDecl *OldFD = Decl->getSpecialization();
Richard Smithf19a8b02019-05-02 00:49:14 +00002902 return cast_or_null<CXXMethodDecl>(
2903 VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten()));
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002904}
2905
Alexey Bataeva769e072013-03-22 06:34:35 +00002906Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2907 OMPThreadPrivateDecl *D) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002908 SmallVector<Expr *, 5> Vars;
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002909 for (auto *I : D->varlists()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002910 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
Alexey Bataeva769e072013-03-22 06:34:35 +00002911 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002912 Vars.push_back(Var);
Alexey Bataeva769e072013-03-22 06:34:35 +00002913 }
2914
2915 OMPThreadPrivateDecl *TD =
2916 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2917
Alexey Bataevd3db6ac2014-03-07 09:46:29 +00002918 TD->setAccess(AS_public);
2919 Owner->addDecl(TD);
2920
Alexey Bataeva769e072013-03-22 06:34:35 +00002921 return TD;
2922}
2923
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002924Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
2925 SmallVector<Expr *, 5> Vars;
2926 for (auto *I : D->varlists()) {
2927 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
2928 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
2929 Vars.push_back(Var);
2930 }
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002931 SmallVector<OMPClause *, 4> Clauses;
2932 // Copy map clauses from the original mapper.
2933 for (OMPClause *C : D->clauselists()) {
2934 auto *AC = cast<OMPAllocatorClause>(C);
2935 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
2936 if (!NewE.isUsable())
2937 continue;
2938 OMPClause *IC = SemaRef.ActOnOpenMPAllocatorClause(
2939 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
2940 Clauses.push_back(IC);
2941 }
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002942
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002943 Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective(
2944 D->getLocation(), Vars, Clauses, Owner);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002945 if (Res.get().isNull())
2946 return nullptr;
2947 return Res.get().getSingleDecl();
2948}
2949
Kelvin Li1408f912018-09-26 04:28:39 +00002950Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
2951 llvm_unreachable(
2952 "Requires directive cannot be instantiated within a dependent context");
2953}
2954
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002955Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
2956 OMPDeclareReductionDecl *D) {
2957 // Instantiate type and check if it is allowed.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00002958 const bool RequiresInstantiation =
2959 D->getType()->isDependentType() ||
2960 D->getType()->isInstantiationDependentType() ||
2961 D->getType()->containsUnexpandedParameterPack();
2962 QualType SubstReductionType;
2963 if (RequiresInstantiation) {
2964 SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
2965 D->getLocation(),
2966 ParsedType::make(SemaRef.SubstType(
2967 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
2968 } else {
2969 SubstReductionType = D->getType();
2970 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002971 if (SubstReductionType.isNull())
2972 return nullptr;
2973 bool IsCorrect = !SubstReductionType.isNull();
2974 // Create instantiated copy.
2975 std::pair<QualType, SourceLocation> ReductionTypes[] = {
2976 std::make_pair(SubstReductionType, D->getLocation())};
2977 auto *PrevDeclInScope = D->getPrevDeclInScope();
2978 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
2979 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
2980 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
2981 ->get<Decl *>());
2982 }
2983 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
2984 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
2985 PrevDeclInScope);
2986 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
Alexey Bataeve6aa4692018-09-13 16:54:05 +00002987 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
2988 if (!RequiresInstantiation) {
2989 if (Expr *Combiner = D->getCombiner()) {
2990 NewDRD->setCombinerData(D->getCombinerIn(), D->getCombinerOut());
2991 NewDRD->setCombiner(Combiner);
2992 if (Expr *Init = D->getInitializer()) {
2993 NewDRD->setInitializerData(D->getInitOrig(), D->getInitPriv());
2994 NewDRD->setInitializer(Init, D->getInitializerKind());
2995 }
2996 }
2997 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
2998 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
2999 return NewDRD;
3000 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003001 Expr *SubstCombiner = nullptr;
3002 Expr *SubstInitializer = nullptr;
3003 // Combiners instantiation sequence.
3004 if (D->getCombiner()) {
3005 SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
3006 /*S=*/nullptr, NewDRD);
Alexey Bataeve6aa4692018-09-13 16:54:05 +00003007 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3008 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3009 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3010 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3011 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3012 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3013 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003014 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
Alexey Bataeve6aa4692018-09-13 16:54:05 +00003015 ThisContext);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003016 SubstCombiner = SemaRef.SubstExpr(D->getCombiner(), TemplateArgs).get();
3017 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
3018 // Initializers instantiation sequence.
3019 if (D->getInitializer()) {
Alexey Bataev070f43a2017-09-06 14:49:58 +00003020 VarDecl *OmpPrivParm =
3021 SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
3022 /*S=*/nullptr, NewDRD);
Alexey Bataeve6aa4692018-09-13 16:54:05 +00003023 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3024 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3025 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3026 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3027 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3028 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
Alexey Bataev070f43a2017-09-06 14:49:58 +00003029 if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
3030 SubstInitializer =
3031 SemaRef.SubstExpr(D->getInitializer(), TemplateArgs).get();
3032 } else {
3033 IsCorrect = IsCorrect && OmpPrivParm->hasInit();
3034 }
3035 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(
3036 NewDRD, SubstInitializer, OmpPrivParm);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003037 }
Alexey Bataev070f43a2017-09-06 14:49:58 +00003038 IsCorrect =
3039 IsCorrect && SubstCombiner &&
3040 (!D->getInitializer() ||
3041 (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit &&
3042 SubstInitializer) ||
3043 (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit &&
3044 !SubstInitializer && !SubstInitializer));
Alexey Bataeve6aa4692018-09-13 16:54:05 +00003045 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003046 IsCorrect = false;
Alexey Bataeve6aa4692018-09-13 16:54:05 +00003047 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003048
3049 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(/*S=*/nullptr, DRD,
3050 IsCorrect);
3051
3052 return NewDRD;
3053}
3054
Michael Kruse251e1482019-02-01 20:25:04 +00003055Decl *
3056TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3057 // Instantiate type and check if it is allowed.
3058 const bool RequiresInstantiation =
3059 D->getType()->isDependentType() ||
3060 D->getType()->isInstantiationDependentType() ||
3061 D->getType()->containsUnexpandedParameterPack();
3062 QualType SubstMapperTy;
3063 DeclarationName VN = D->getVarName();
3064 if (RequiresInstantiation) {
3065 SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
3066 D->getLocation(),
3067 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3068 D->getLocation(), VN)));
3069 } else {
3070 SubstMapperTy = D->getType();
3071 }
3072 if (SubstMapperTy.isNull())
3073 return nullptr;
3074 // Create an instantiated copy of mapper.
3075 auto *PrevDeclInScope = D->getPrevDeclInScope();
3076 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3077 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3078 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3079 ->get<Decl *>());
3080 }
3081 OMPDeclareMapperDecl *NewDMD = SemaRef.ActOnOpenMPDeclareMapperDirectiveStart(
3082 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3083 VN, D->getAccess(), PrevDeclInScope);
3084 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
3085 SmallVector<OMPClause *, 6> Clauses;
3086 bool IsCorrect = true;
3087 if (!RequiresInstantiation) {
3088 // Copy the mapper variable.
3089 NewDMD->setMapperVarRef(D->getMapperVarRef());
3090 // Copy map clauses from the original mapper.
3091 for (OMPClause *C : D->clauselists())
3092 Clauses.push_back(C);
3093 } else {
3094 // Instantiate the mapper variable.
3095 DeclarationNameInfo DirName;
3096 SemaRef.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, /*S=*/nullptr,
3097 (*D->clauselist_begin())->getBeginLoc());
3098 SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl(
3099 NewDMD, /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3100 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3101 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3102 cast<DeclRefExpr>(NewDMD->getMapperVarRef())->getDecl());
3103 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3104 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3105 ThisContext);
3106 // Instantiate map clauses.
3107 for (OMPClause *C : D->clauselists()) {
3108 auto *OldC = cast<OMPMapClause>(C);
3109 SmallVector<Expr *, 4> NewVars;
3110 for (Expr *OE : OldC->varlists()) {
3111 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3112 if (!NE) {
3113 IsCorrect = false;
3114 break;
3115 }
3116 NewVars.push_back(NE);
3117 }
3118 if (!IsCorrect)
3119 break;
Michael Kruse4304e9d2019-02-19 16:38:20 +00003120 NestedNameSpecifierLoc NewQualifierLoc =
3121 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3122 TemplateArgs);
3123 CXXScopeSpec SS;
3124 SS.Adopt(NewQualifierLoc);
3125 DeclarationNameInfo NewNameInfo = SemaRef.SubstDeclarationNameInfo(
3126 OldC->getMapperIdInfo(), TemplateArgs);
3127 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3128 OldC->getEndLoc());
Michael Kruse251e1482019-02-01 20:25:04 +00003129 OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00003130 OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS,
3131 NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(),
3132 OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs);
Michael Kruse251e1482019-02-01 20:25:04 +00003133 Clauses.push_back(NewC);
3134 }
3135 SemaRef.EndOpenMPDSABlock(nullptr);
3136 }
3137 (void)SemaRef.ActOnOpenMPDeclareMapperDirectiveEnd(NewDMD, /*S=*/nullptr,
3138 Clauses);
3139 if (!IsCorrect)
3140 return nullptr;
3141 return NewDMD;
3142}
3143
Alexey Bataev4244be22016-02-11 05:35:55 +00003144Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3145 OMPCapturedExprDecl * /*D*/) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00003146 llvm_unreachable("Should not be met in templates");
3147}
3148
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003149Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003150 return VisitFunctionDecl(D, nullptr);
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003151}
3152
Richard Smithbc491202017-02-17 20:05:37 +00003153Decl *
3154TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
Richard Smith2600c632018-05-30 20:24:10 +00003155 Decl *Inst = VisitFunctionDecl(D, nullptr);
3156 if (Inst && !D->getDescribedFunctionTemplate())
3157 Owner->addDecl(Inst);
3158 return Inst;
Richard Smithbc491202017-02-17 20:05:37 +00003159}
3160
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003161Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003162 return VisitCXXMethodDecl(D, nullptr);
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003163}
3164
3165Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3166 llvm_unreachable("There are only CXXRecordDecls in C++");
3167}
3168
3169Decl *
3170TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3171 ClassTemplateSpecializationDecl *D) {
Richard Smith8a0dde72013-12-14 01:04:22 +00003172 // As a MS extension, we permit class-scope explicit specialization
3173 // of member class templates.
3174 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3175 assert(ClassTemplate->getDeclContext()->isRecord() &&
3176 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3177 "can only instantiate an explicit specialization "
3178 "for a member class template");
3179
3180 // Lookup the already-instantiated declaration in the instantiation
Richard Smitha6b41d72019-05-03 23:51:38 +00003181 // of the class template.
3182 ClassTemplateDecl *InstClassTemplate =
3183 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3184 D->getLocation(), ClassTemplate, TemplateArgs));
Richard Smith8a0dde72013-12-14 01:04:22 +00003185 if (!InstClassTemplate)
Craig Topperc3ec1492014-05-26 06:22:03 +00003186 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003187
3188 // Substitute into the template arguments of the class template explicit
3189 // specialization.
3190 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
3191 castAs<TemplateSpecializationTypeLoc>();
3192 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
3193 Loc.getRAngleLoc());
3194 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
3195 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
3196 ArgLocs.push_back(Loc.getArgLoc(I));
3197 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
3198 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00003199 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003200
3201 // Check that the template argument list is well-formed for this
3202 // class template.
3203 SmallVector<TemplateArgument, 4> Converted;
3204 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
3205 D->getLocation(),
3206 InstTemplateArgs,
3207 false,
3208 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00003209 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003210
3211 // Figure out where to insert this class template explicit specialization
3212 // in the member template's set of class template explicit specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00003213 void *InsertPos = nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003214 ClassTemplateSpecializationDecl *PrevDecl =
Craig Topper7e0daca2014-06-26 04:58:53 +00003215 InstClassTemplate->findSpecialization(Converted, InsertPos);
Richard Smith8a0dde72013-12-14 01:04:22 +00003216
3217 // Check whether we've already seen a conflicting instantiation of this
3218 // declaration (for instance, if there was a prior implicit instantiation).
3219 bool Ignored;
3220 if (PrevDecl &&
3221 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
3222 D->getSpecializationKind(),
3223 PrevDecl,
3224 PrevDecl->getSpecializationKind(),
3225 PrevDecl->getPointOfInstantiation(),
3226 Ignored))
Craig Topperc3ec1492014-05-26 06:22:03 +00003227 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003228
3229 // If PrevDecl was a definition and D is also a definition, diagnose.
3230 // This happens in cases like:
3231 //
3232 // template<typename T, typename U>
3233 // struct Outer {
3234 // template<typename X> struct Inner;
3235 // template<> struct Inner<T> {};
3236 // template<> struct Inner<U> {};
3237 // };
3238 //
3239 // Outer<int, int> outer; // error: the explicit specializations of Inner
3240 // // have the same signature.
3241 if (PrevDecl && PrevDecl->getDefinition() &&
3242 D->isThisDeclarationADefinition()) {
3243 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3244 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3245 diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +00003246 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003247 }
3248
3249 // Create the class template partial specialization declaration.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003250 ClassTemplateSpecializationDecl *InstD =
3251 ClassTemplateSpecializationDecl::Create(
3252 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3253 D->getLocation(), InstClassTemplate, Converted, PrevDecl);
Richard Smith8a0dde72013-12-14 01:04:22 +00003254
3255 // Add this partial specialization to the set of class template partial
3256 // specializations.
3257 if (!PrevDecl)
3258 InstClassTemplate->AddSpecialization(InstD, InsertPos);
3259
3260 // Substitute the nested name specifier, if any.
3261 if (SubstQualifier(D, InstD))
Craig Topperc3ec1492014-05-26 06:22:03 +00003262 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003263
3264 // Build the canonical type that describes the converted template
3265 // arguments of the class template explicit specialization.
3266 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00003267 TemplateName(InstClassTemplate), Converted,
Richard Smith8a0dde72013-12-14 01:04:22 +00003268 SemaRef.Context.getRecordType(InstD));
3269
3270 // Build the fully-sugared type for this class template
3271 // specialization as the user wrote in the specialization
3272 // itself. This means that we'll pretty-print the type retrieved
3273 // from the specialization's declaration the way that the user
3274 // actually wrote the specialization, rather than formatting the
3275 // name based on the "canonical" representation used to store the
3276 // template arguments in the specialization.
3277 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3278 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
3279 CanonType);
3280
3281 InstD->setAccess(D->getAccess());
3282 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
3283 InstD->setSpecializationKind(D->getSpecializationKind());
3284 InstD->setTypeAsWritten(WrittenTy);
3285 InstD->setExternLoc(D->getExternLoc());
3286 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
3287
3288 Owner->addDecl(InstD);
3289
3290 // Instantiate the members of the class-scope explicit specialization eagerly.
3291 // We don't have support for lazy instantiation of an explicit specialization
3292 // yet, and MSVC eagerly instantiates in this case.
Richard Smitha6b41d72019-05-03 23:51:38 +00003293 // FIXME: This is wrong in standard C++.
Richard Smith8a0dde72013-12-14 01:04:22 +00003294 if (D->isThisDeclarationADefinition() &&
3295 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
3296 TSK_ImplicitInstantiation,
3297 /*Complain=*/true))
Craig Topperc3ec1492014-05-26 06:22:03 +00003298 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00003299
3300 return InstD;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003301}
3302
Larisse Voufo39a1e502013-08-06 01:03:05 +00003303Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3304 VarTemplateSpecializationDecl *D) {
3305
3306 TemplateArgumentListInfo VarTemplateArgsInfo;
3307 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
3308 assert(VarTemplate &&
3309 "A template specialization without specialized template?");
3310
Richard Smitha6b41d72019-05-03 23:51:38 +00003311 VarTemplateDecl *InstVarTemplate =
3312 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
3313 D->getLocation(), VarTemplate, TemplateArgs));
3314 if (!InstVarTemplate)
3315 return nullptr;
3316
Larisse Voufo39a1e502013-08-06 01:03:05 +00003317 // Substitute the current template arguments.
3318 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
3319 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
3320 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
3321
3322 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
3323 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00003324 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003325
3326 // Check that the template argument list is well-formed for this template.
3327 SmallVector<TemplateArgument, 4> Converted;
Richard Smitha6b41d72019-05-03 23:51:38 +00003328 if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
3329 VarTemplateArgsInfo, false, Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00003330 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003331
Richard Smitha6b41d72019-05-03 23:51:38 +00003332 // Check whether we've already seen a declaration of this specialization.
Craig Topperc3ec1492014-05-26 06:22:03 +00003333 void *InsertPos = nullptr;
Richard Smitha6b41d72019-05-03 23:51:38 +00003334 VarTemplateSpecializationDecl *PrevDecl =
3335 InstVarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003336
Richard Smitha6b41d72019-05-03 23:51:38 +00003337 // Check whether we've already seen a conflicting instantiation of this
3338 // declaration (for instance, if there was a prior implicit instantiation).
3339 bool Ignored;
3340 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
3341 D->getLocation(), D->getSpecializationKind(), PrevDecl,
3342 PrevDecl->getSpecializationKind(),
3343 PrevDecl->getPointOfInstantiation(), Ignored))
3344 return nullptr;
3345
3346 return VisitVarTemplateSpecializationDecl(
3347 InstVarTemplate, D, InsertPos, VarTemplateArgsInfo, Converted, PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003348}
3349
3350Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3351 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
3352 const TemplateArgumentListInfo &TemplateArgsInfo,
Richard Smitha6b41d72019-05-03 23:51:38 +00003353 ArrayRef<TemplateArgument> Converted,
3354 VarTemplateSpecializationDecl *PrevDecl) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003355
Larisse Voufo39a1e502013-08-06 01:03:05 +00003356 // Do substitution on the type of the declaration
3357 TypeSourceInfo *DI =
3358 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3359 D->getTypeSpecStartLoc(), D->getDeclName());
3360 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00003361 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003362
3363 if (DI->getType()->isFunctionType()) {
3364 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
3365 << D->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003366 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003367 }
3368
3369 // Build the instantiated declaration
3370 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
3371 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
David Majnemer8b622692016-07-03 21:17:51 +00003372 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003373 Var->setTemplateArgsInfo(TemplateArgsInfo);
Richard Smith8809a0c2013-09-27 20:14:12 +00003374 if (InsertPos)
3375 VarTemplate->AddSpecialization(Var, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003376
3377 // Substitute the nested name specifier, if any.
3378 if (SubstQualifier(D, Var))
Craig Topperc3ec1492014-05-26 06:22:03 +00003379 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003380
Richard Smitha6b41d72019-05-03 23:51:38 +00003381 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
3382 StartingScope, false, PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003383
3384 return Var;
3385}
3386
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003387Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
3388 llvm_unreachable("@defs is not supported in Objective-C++");
3389}
3390
3391Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
3392 // FIXME: We need to be able to instantiate FriendTemplateDecls.
3393 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
3394 DiagnosticsEngine::Error,
3395 "cannot instantiate %0 yet");
3396 SemaRef.Diag(D->getLocation(), DiagID)
3397 << D->getDeclKindName();
3398
Craig Topperc3ec1492014-05-26 06:22:03 +00003399 return nullptr;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003400}
3401
Saar Razd7aae332019-07-10 21:25:49 +00003402Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
3403 llvm_unreachable("Concept definitions cannot reside inside a template");
3404}
3405
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003406Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
3407 llvm_unreachable("Unexpected decl");
3408}
3409
John McCall76d824f2009-08-25 22:02:44 +00003410Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregor01afeef2009-08-28 20:31:08 +00003411 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord002c7b2009-05-11 23:53:27 +00003412 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor71ad4772010-02-16 19:28:15 +00003413 if (D->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00003414 return nullptr;
Douglas Gregor71ad4772010-02-16 19:28:15 +00003415
Richard Smith26a92d52019-08-26 18:18:07 +00003416 Decl *SubstD;
3417 runWithSufficientStackSpace(D->getLocation(), [&] {
3418 SubstD = Instantiator.Visit(D);
3419 });
3420 return SubstD;
Douglas Gregord7e7a512009-03-17 21:15:40 +00003421}
3422
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003423/// Instantiates a nested template parameter list in the current
John McCall87a44eb2009-08-20 01:44:21 +00003424/// instantiation context.
3425///
3426/// \param L The parameter list to instantiate
3427///
3428/// \returns NULL if there was an error
3429TemplateParameterList *
John McCall76d824f2009-08-25 22:02:44 +00003430TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCall87a44eb2009-08-20 01:44:21 +00003431 // Get errors for all the parameters before bailing out.
3432 bool Invalid = false;
3433
3434 unsigned N = L->size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003435 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCall87a44eb2009-08-20 01:44:21 +00003436 ParamVector Params;
3437 Params.reserve(N);
Davide Italiano18960b92015-07-02 19:20:11 +00003438 for (auto &P : *L) {
3439 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
John McCall87a44eb2009-08-20 01:44:21 +00003440 Params.push_back(D);
Douglas Gregore62e6a02009-11-11 19:13:48 +00003441 Invalid = Invalid || !D || D->isInvalidDecl();
John McCall87a44eb2009-08-20 01:44:21 +00003442 }
3443
3444 // Clean up if we had an error.
Douglas Gregorb412e172010-07-25 18:17:45 +00003445 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +00003446 return nullptr;
John McCall87a44eb2009-08-20 01:44:21 +00003447
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00003448 // Note: we substitute into associated constraints later
3449 Expr *const UninstantiatedRequiresClause = L->getRequiresClause();
3450
John McCall87a44eb2009-08-20 01:44:21 +00003451 TemplateParameterList *InstL
3452 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
David Majnemer902f8c62015-12-27 07:16:27 +00003453 L->getLAngleLoc(), Params,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00003454 L->getRAngleLoc(),
3455 UninstantiatedRequiresClause);
John McCall87a44eb2009-08-20 01:44:21 +00003456 return InstL;
Mike Stump11289f42009-09-09 15:08:12 +00003457}
John McCall87a44eb2009-08-20 01:44:21 +00003458
Richard Smith5d331022018-03-08 01:07:33 +00003459TemplateParameterList *
3460Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
3461 const MultiLevelTemplateArgumentList &TemplateArgs) {
3462 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3463 return Instantiator.SubstTemplateParams(Params);
3464}
3465
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003466/// Instantiate the declaration of a class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00003467/// specialization.
3468///
3469/// \param ClassTemplate the (instantiated) class template that is partially
3470// specialized by the instantiation of \p PartialSpec.
3471///
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003472/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00003473/// specialization that we are instantiating.
3474///
Douglas Gregor869853e2010-11-10 19:44:59 +00003475/// \returns The instantiated partial specialization, if successful; otherwise,
3476/// NULL to indicate an error.
3477ClassTemplatePartialSpecializationDecl *
Douglas Gregor21610382009-10-29 00:04:11 +00003478TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
3479 ClassTemplateDecl *ClassTemplate,
3480 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor954de172009-10-31 17:21:17 +00003481 // Create a local instantiation scope for this class template partial
3482 // specialization, which will contain the instantiations of the template
3483 // parameters.
John McCall19c1bfd2010-08-25 05:32:35 +00003484 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003485
Douglas Gregor21610382009-10-29 00:04:11 +00003486 // Substitute into the template parameters of the class template partial
3487 // specialization.
3488 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3489 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3490 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00003491 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003492
Douglas Gregor21610382009-10-29 00:04:11 +00003493 // Substitute into the template arguments of the class template partial
3494 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00003495 const ASTTemplateArgumentListInfo *TemplArgInfo
3496 = PartialSpec->getTemplateArgsAsWritten();
3497 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3498 TemplArgInfo->RAngleLoc);
3499 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3500 TemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00003501 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00003502 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003503
Douglas Gregor21610382009-10-29 00:04:11 +00003504 // Check that the template argument list is well-formed for this
3505 // class template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003506 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003507 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregor21610382009-10-29 00:04:11 +00003508 PartialSpec->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003509 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00003510 false,
3511 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00003512 return nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00003513
Richard Smith57aae072016-12-28 02:37:25 +00003514 // Check these arguments are valid for a template partial specialization.
3515 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3516 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
3517 Converted))
3518 return nullptr;
3519
Douglas Gregor21610382009-10-29 00:04:11 +00003520 // Figure out where to insert this class template partial specialization
3521 // in the member template's set of class template partial specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00003522 void *InsertPos = nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00003523 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00003524 = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003525
Douglas Gregor21610382009-10-29 00:04:11 +00003526 // Build the canonical type that describes the converted template
3527 // arguments of the class template partial specialization.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003528 QualType CanonType
Douglas Gregor21610382009-10-29 00:04:11 +00003529 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
David Majnemer6fbeee32016-07-07 04:43:07 +00003530 Converted);
Douglas Gregor21610382009-10-29 00:04:11 +00003531
3532 // Build the fully-sugared type for this class template
3533 // specialization as the user wrote in the specialization
3534 // itself. This means that we'll pretty-print the type retrieved
3535 // from the specialization's declaration the way that the user
3536 // actually wrote the specialization, rather than formatting the
3537 // name based on the "canonical" representation used to store the
3538 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003539 TypeSourceInfo *WrittenTy
3540 = SemaRef.Context.getTemplateSpecializationTypeInfo(
3541 TemplateName(ClassTemplate),
3542 PartialSpec->getLocation(),
John McCall6b51f282009-11-23 01:53:49 +00003543 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00003544 CanonType);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003545
Douglas Gregor21610382009-10-29 00:04:11 +00003546 if (PrevDecl) {
3547 // We've already seen a partial specialization with the same template
3548 // parameters and template arguments. This can happen, for example, when
3549 // substituting the outer template arguments ends up causing two
3550 // class template partial specializations of a member class template
3551 // to have identical forms, e.g.,
3552 //
3553 // template<typename T, typename U>
3554 // struct Outer {
3555 // template<typename X, typename Y> struct Inner;
3556 // template<typename Y> struct Inner<T, Y>;
3557 // template<typename Y> struct Inner<U, Y>;
3558 // };
3559 //
3560 // Outer<int, int> outer; // error: the partial specializations of Inner
3561 // // have the same signature.
3562 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregor869853e2010-11-10 19:44:59 +00003563 << WrittenTy->getType();
Douglas Gregor21610382009-10-29 00:04:11 +00003564 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
3565 << SemaRef.Context.getTypeDeclType(PrevDecl);
Craig Topperc3ec1492014-05-26 06:22:03 +00003566 return nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00003567 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003568
3569
Douglas Gregor21610382009-10-29 00:04:11 +00003570 // Create the class template partial specialization declaration.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003571 ClassTemplatePartialSpecializationDecl *InstPartialSpec =
3572 ClassTemplatePartialSpecializationDecl::Create(
3573 SemaRef.Context, PartialSpec->getTagKind(), Owner,
3574 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
3575 ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr);
John McCall3e11ebe2010-03-15 10:12:16 +00003576 // Substitute the nested name specifier, if any.
3577 if (SubstQualifier(PartialSpec, InstPartialSpec))
Craig Topperc3ec1492014-05-26 06:22:03 +00003578 return nullptr;
John McCall3e11ebe2010-03-15 10:12:16 +00003579
Douglas Gregor21610382009-10-29 00:04:11 +00003580 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor6044d692010-05-19 17:02:24 +00003581 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003582
Richard Smith57aae072016-12-28 02:37:25 +00003583 // Check the completed partial specialization.
3584 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3585
Douglas Gregor21610382009-10-29 00:04:11 +00003586 // Add this partial specialization to the set of class template partial
3587 // specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00003588 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
3589 /*InsertPos=*/nullptr);
Douglas Gregor869853e2010-11-10 19:44:59 +00003590 return InstPartialSpec;
Douglas Gregor21610382009-10-29 00:04:11 +00003591}
3592
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003593/// Instantiate the declaration of a variable template partial
Larisse Voufo39a1e502013-08-06 01:03:05 +00003594/// specialization.
3595///
3596/// \param VarTemplate the (instantiated) variable template that is partially
3597/// specialized by the instantiation of \p PartialSpec.
3598///
3599/// \param PartialSpec the (uninstantiated) variable template partial
3600/// specialization that we are instantiating.
3601///
3602/// \returns The instantiated partial specialization, if successful; otherwise,
3603/// NULL to indicate an error.
3604VarTemplatePartialSpecializationDecl *
3605TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
3606 VarTemplateDecl *VarTemplate,
3607 VarTemplatePartialSpecializationDecl *PartialSpec) {
3608 // Create a local instantiation scope for this variable template partial
3609 // specialization, which will contain the instantiations of the template
3610 // parameters.
3611 LocalInstantiationScope Scope(SemaRef);
3612
3613 // Substitute into the template parameters of the variable template partial
3614 // specialization.
3615 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3616 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3617 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00003618 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003619
3620 // Substitute into the template arguments of the variable template partial
3621 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00003622 const ASTTemplateArgumentListInfo *TemplArgInfo
3623 = PartialSpec->getTemplateArgsAsWritten();
3624 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3625 TemplArgInfo->RAngleLoc);
3626 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3627 TemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00003628 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00003629 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003630
3631 // Check that the template argument list is well-formed for this
3632 // class template.
3633 SmallVector<TemplateArgument, 4> Converted;
3634 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
3635 InstTemplateArgs, false, Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00003636 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003637
Richard Smith57aae072016-12-28 02:37:25 +00003638 // Check these arguments are valid for a template partial specialization.
3639 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3640 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
3641 Converted))
3642 return nullptr;
3643
Larisse Voufo39a1e502013-08-06 01:03:05 +00003644 // Figure out where to insert this variable template partial specialization
3645 // in the member template's set of variable template partial specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00003646 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003647 VarTemplateSpecializationDecl *PrevDecl =
Craig Topper7e0daca2014-06-26 04:58:53 +00003648 VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003649
3650 // Build the canonical type that describes the converted template
3651 // arguments of the variable template partial specialization.
3652 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00003653 TemplateName(VarTemplate), Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003654
3655 // Build the fully-sugared type for this variable template
3656 // specialization as the user wrote in the specialization
3657 // itself. This means that we'll pretty-print the type retrieved
3658 // from the specialization's declaration the way that the user
3659 // actually wrote the specialization, rather than formatting the
3660 // name based on the "canonical" representation used to store the
3661 // template arguments in the specialization.
3662 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3663 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
3664 CanonType);
3665
3666 if (PrevDecl) {
3667 // We've already seen a partial specialization with the same template
3668 // parameters and template arguments. This can happen, for example, when
3669 // substituting the outer template arguments ends up causing two
3670 // variable template partial specializations of a member variable template
3671 // to have identical forms, e.g.,
3672 //
3673 // template<typename T, typename U>
3674 // struct Outer {
3675 // template<typename X, typename Y> pair<X,Y> p;
3676 // template<typename Y> pair<T, Y> p;
3677 // template<typename Y> pair<U, Y> p;
3678 // };
3679 //
3680 // Outer<int, int> outer; // error: the partial specializations of Inner
3681 // // have the same signature.
3682 SemaRef.Diag(PartialSpec->getLocation(),
3683 diag::err_var_partial_spec_redeclared)
3684 << WrittenTy->getType();
3685 SemaRef.Diag(PrevDecl->getLocation(),
3686 diag::note_var_prev_partial_spec_here);
Craig Topperc3ec1492014-05-26 06:22:03 +00003687 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003688 }
3689
3690 // Do substitution on the type of the declaration
3691 TypeSourceInfo *DI = SemaRef.SubstType(
3692 PartialSpec->getTypeSourceInfo(), TemplateArgs,
3693 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
3694 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00003695 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003696
3697 if (DI->getType()->isFunctionType()) {
3698 SemaRef.Diag(PartialSpec->getLocation(),
3699 diag::err_variable_instantiates_to_function)
3700 << PartialSpec->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003701 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003702 }
3703
3704 // Create the variable template partial specialization declaration.
3705 VarTemplatePartialSpecializationDecl *InstPartialSpec =
3706 VarTemplatePartialSpecializationDecl::Create(
3707 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
3708 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
David Majnemer8b622692016-07-03 21:17:51 +00003709 DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003710
3711 // Substitute the nested name specifier, if any.
3712 if (SubstQualifier(PartialSpec, InstPartialSpec))
Craig Topperc3ec1492014-05-26 06:22:03 +00003713 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003714
3715 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3716 InstPartialSpec->setTypeAsWritten(WrittenTy);
3717
Richard Smith57aae072016-12-28 02:37:25 +00003718 // Check the completed partial specialization.
3719 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3720
Larisse Voufo39a1e502013-08-06 01:03:05 +00003721 // Add this partial specialization to the set of variable template partial
3722 // specializations. The instantiation of the initializer is not necessary.
Craig Topperc3ec1492014-05-26 06:22:03 +00003723 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
Larisse Voufo4cda4612013-08-22 00:28:27 +00003724
Larisse Voufo4cda4612013-08-22 00:28:27 +00003725 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00003726 LateAttrs, Owner, StartingScope);
Larisse Voufo4cda4612013-08-22 00:28:27 +00003727
Larisse Voufo39a1e502013-08-06 01:03:05 +00003728 return InstPartialSpec;
3729}
3730
John McCall58f10c32010-03-11 09:03:00 +00003731TypeSourceInfo*
John McCall76d824f2009-08-25 22:02:44 +00003732TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003733 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall58f10c32010-03-11 09:03:00 +00003734 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
3735 assert(OldTInfo && "substituting function without type source info");
3736 assert(Params.empty() && "parameter vector is non-empty at start");
Craig Topperc3ec1492014-05-26 06:22:03 +00003737
3738 CXXRecordDecl *ThisContext = nullptr;
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003739 Qualifiers ThisTypeQuals;
Douglas Gregor3024f072012-04-16 07:05:22 +00003740 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc3d2ebb2013-06-07 02:33:37 +00003741 ThisContext = cast<CXXRecordDecl>(Owner);
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00003742 ThisTypeQuals = Method->getMethodQualifiers();
Douglas Gregor3024f072012-04-16 07:05:22 +00003743 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003744
John McCallb29f78f2010-04-09 17:38:44 +00003745 TypeSourceInfo *NewTInfo
3746 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
3747 D->getTypeSpecStartLoc(),
Douglas Gregor3024f072012-04-16 07:05:22 +00003748 D->getDeclName(),
3749 ThisContext, ThisTypeQuals);
John McCall58f10c32010-03-11 09:03:00 +00003750 if (!NewTInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00003751 return nullptr;
Douglas Gregor21342092009-03-24 00:38:23 +00003752
Reid Klecknera09e44c2013-07-31 21:00:18 +00003753 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
3754 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
3755 if (NewTInfo != OldTInfo) {
3756 // Get parameters from the new type info.
Abramo Bagnaraa44c9022010-12-13 22:27:55 +00003757 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00003758 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith198223b2012-07-18 01:29:05 +00003759 unsigned NewIdx = 0;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003760 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
Douglas Gregorf3010112011-01-07 16:43:16 +00003761 OldIdx != NumOldParams; ++OldIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003762 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
Richard Smith198223b2012-07-18 01:29:05 +00003763 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
3764
David Blaikie05785d12013-02-20 22:23:23 +00003765 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith198223b2012-07-18 01:29:05 +00003766 if (OldParam->isParameterPack())
3767 NumArgumentsInExpansion =
3768 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
3769 TemplateArgs);
3770 if (!NumArgumentsInExpansion) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003771 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregorf3010112011-01-07 16:43:16 +00003772 // instantiated to a (still-dependent) parameter pack.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003773 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Douglas Gregorf3010112011-01-07 16:43:16 +00003774 Params.push_back(NewParam);
Richard Smith198223b2012-07-18 01:29:05 +00003775 Scope->InstantiatedLocal(OldParam, NewParam);
3776 } else {
3777 // Parameter pack expansion: make the instantiation an argument pack.
3778 Scope->MakeInstantiatedLocalArgPack(OldParam);
3779 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003780 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Richard Smith198223b2012-07-18 01:29:05 +00003781 Params.push_back(NewParam);
3782 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
3783 }
Douglas Gregorf3010112011-01-07 16:43:16 +00003784 }
Douglas Gregor95c70ec2010-05-03 15:32:18 +00003785 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00003786 } else {
3787 // The function type itself was not dependent and therefore no
3788 // substitution occurred. However, we still need to instantiate
3789 // the function parameters themselves.
3790 const FunctionProtoType *OldProto =
3791 cast<FunctionProtoType>(OldProtoLoc.getType());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003792 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
3793 ++i) {
3794 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
Reid Klecknera09e44c2013-07-31 21:00:18 +00003795 if (!OldParam) {
3796 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
Alp Toker9cacbab2014-01-20 20:26:09 +00003797 D, D->getLocation(), OldProto->getParamType(i)));
Reid Klecknera09e44c2013-07-31 21:00:18 +00003798 continue;
3799 }
3800
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003801 ParmVarDecl *Parm =
Reid Klecknera09e44c2013-07-31 21:00:18 +00003802 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
Douglas Gregor95c70ec2010-05-03 15:32:18 +00003803 if (!Parm)
Craig Topperc3ec1492014-05-26 06:22:03 +00003804 return nullptr;
Douglas Gregor95c70ec2010-05-03 15:32:18 +00003805 Params.push_back(Parm);
3806 }
Douglas Gregor940bca72010-04-12 07:48:19 +00003807 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00003808 } else {
3809 // If the type of this function, after ignoring parentheses, is not
3810 // *directly* a function type, then we're instantiating a function that
3811 // was declared via a typedef or with attributes, e.g.,
3812 //
3813 // typedef int functype(int, int);
3814 // functype func;
3815 // int __cdecl meth(int, int);
3816 //
3817 // In this case, we'll just go instantiate the ParmVarDecls that we
3818 // synthesized in the method declaration.
3819 SmallVector<QualType, 4> ParamTypes;
John McCallc8e321d2016-03-01 02:09:25 +00003820 Sema::ExtParameterInfoBuilder ExtParamInfos;
David Majnemer59f77922016-06-24 04:05:48 +00003821 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
3822 TemplateArgs, ParamTypes, &Params,
3823 ExtParamInfos))
Craig Topperc3ec1492014-05-26 06:22:03 +00003824 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00003825 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00003826
John McCall58f10c32010-03-11 09:03:00 +00003827 return NewTInfo;
Douglas Gregor21342092009-03-24 00:38:23 +00003828}
3829
Richard Smithf623c962012-04-17 00:58:00 +00003830/// Introduce the instantiated function parameters into the local
3831/// instantiation scope, and set the parameter names to those used
3832/// in the template.
Richard Smith2e321552014-11-12 02:00:47 +00003833static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
Richard Smithf623c962012-04-17 00:58:00 +00003834 const FunctionDecl *PatternDecl,
3835 LocalInstantiationScope &Scope,
3836 const MultiLevelTemplateArgumentList &TemplateArgs) {
3837 unsigned FParamIdx = 0;
3838 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
3839 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
3840 if (!PatternParam->isParameterPack()) {
3841 // Simple case: not a parameter pack.
3842 assert(FParamIdx < Function->getNumParams());
3843 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
Richard Smith2e321552014-11-12 02:00:47 +00003844 FunctionParam->setDeclName(PatternParam->getDeclName());
Richard Smithaae40582014-03-13 00:28:45 +00003845 // If the parameter's type is not dependent, update it to match the type
3846 // in the pattern. They can differ in top-level cv-qualifiers, and we want
3847 // the pattern's type here. If the type is dependent, they can't differ,
Richard Smith2e321552014-11-12 02:00:47 +00003848 // per core issue 1668. Substitute into the type from the pattern, in case
3849 // it's instantiation-dependent.
Richard Smithaae40582014-03-13 00:28:45 +00003850 // FIXME: Updating the type to work around this is at best fragile.
Richard Smith2e321552014-11-12 02:00:47 +00003851 if (!PatternDecl->getType()->isDependentType()) {
3852 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
3853 FunctionParam->getLocation(),
3854 FunctionParam->getDeclName());
3855 if (T.isNull())
3856 return true;
3857 FunctionParam->setType(T);
3858 }
Richard Smithaae40582014-03-13 00:28:45 +00003859
Richard Smithf623c962012-04-17 00:58:00 +00003860 Scope.InstantiatedLocal(PatternParam, FunctionParam);
3861 ++FParamIdx;
3862 continue;
3863 }
3864
3865 // Expand the parameter pack.
3866 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikie05785d12013-02-20 22:23:23 +00003867 Optional<unsigned> NumArgumentsInExpansion
Richard Smithf623c962012-04-17 00:58:00 +00003868 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Trieuef1e06d2019-03-15 04:26:02 +00003869 if (NumArgumentsInExpansion) {
3870 QualType PatternType =
3871 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
3872 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
3873 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3874 FunctionParam->setDeclName(PatternParam->getDeclName());
3875 if (!PatternDecl->getType()->isDependentType()) {
3876 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
3877 QualType T = S.SubstType(PatternType, TemplateArgs,
3878 FunctionParam->getLocation(),
3879 FunctionParam->getDeclName());
3880 if (T.isNull())
3881 return true;
3882 FunctionParam->setType(T);
3883 }
Richard Smith2e321552014-11-12 02:00:47 +00003884
Richard Trieuef1e06d2019-03-15 04:26:02 +00003885 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3886 ++FParamIdx;
3887 }
Richard Smithf623c962012-04-17 00:58:00 +00003888 }
3889 }
Richard Smithf623c962012-04-17 00:58:00 +00003890
Richard Smith2e321552014-11-12 02:00:47 +00003891 return false;
Richard Smithf623c962012-04-17 00:58:00 +00003892}
3893
3894void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3895 FunctionDecl *Decl) {
Richard Smithd3729422012-04-19 00:08:28 +00003896 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3897 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithf623c962012-04-17 00:58:00 +00003898 return;
3899
3900 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3901 InstantiatingTemplate::ExceptionSpecification());
Alp Tokerd4a72d52013-10-08 08:09:04 +00003902 if (Inst.isInvalid()) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003903 // We hit the instantiation depth limit. Clear the exception specification
3904 // so that our callers don't have to cope with EST_Uninstantiated.
Richard Smith8acb4282014-07-31 21:57:55 +00003905 UpdateExceptionSpec(Decl, EST_None);
Richard Smithf623c962012-04-17 00:58:00 +00003906 return;
Richard Smithd3b5c9082012-07-27 04:22:15 +00003907 }
Richard Smith54f18e82016-08-31 02:15:21 +00003908 if (Inst.isAlreadyInstantiating()) {
3909 // This exception specification indirectly depends on itself. Reject.
3910 // FIXME: Corresponding rule in the standard?
3911 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
3912 UpdateExceptionSpec(Decl, EST_None);
3913 return;
3914 }
Richard Smithf623c962012-04-17 00:58:00 +00003915
3916 // Enter the scope of this instantiation. We don't use
3917 // PushDeclContext because we don't have a scope.
3918 Sema::ContextRAII savedContext(*this, Decl);
3919 LocalInstantiationScope Scope(*this);
3920
3921 MultiLevelTemplateArgumentList TemplateArgs =
Craig Topperc3ec1492014-05-26 06:22:03 +00003922 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
Richard Smithf623c962012-04-17 00:58:00 +00003923
Richard Smithd3729422012-04-19 00:08:28 +00003924 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
Richard Smith2e321552014-11-12 02:00:47 +00003925 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
3926 TemplateArgs)) {
3927 UpdateExceptionSpec(Decl, EST_None);
3928 return;
3929 }
Richard Smithf623c962012-04-17 00:58:00 +00003930
Richard Smith2e321552014-11-12 02:00:47 +00003931 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
3932 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003933}
3934
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003935/// Initializes the common fields of an instantiation function
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003936/// declaration (New) from the corresponding fields of its template (Tmpl).
3937///
3938/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003939bool
3940TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003941 FunctionDecl *Tmpl) {
David Blaikie5a0956e2012-07-16 18:50:45 +00003942 if (Tmpl->isDeleted())
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003943 New->setDeletedAsWritten();
Mike Stump11289f42009-09-09 15:08:12 +00003944
Richard Smith32918772017-02-14 00:25:28 +00003945 New->setImplicit(Tmpl->isImplicit());
3946
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003947 // Forward the mangling number from the template to the instantiated decl.
3948 SemaRef.Context.setManglingNumber(New,
3949 SemaRef.Context.getManglingNumber(Tmpl));
3950
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003951 // If we are performing substituting explicitly-specified template arguments
3952 // or deduced template arguments into a function template and we reach this
3953 // point, we are now past the point where SFINAE applies and have committed
Mike Stump11289f42009-09-09 15:08:12 +00003954 // to keeping the new function template specialization. We therefore
3955 // convert the active template instantiation for the function template
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003956 // into a template instantiation for this specific function template
3957 // specialization, which is not a SFINAE context, so that we diagnose any
3958 // further errors in the declaration itself.
Richard Smith696e3122017-02-23 01:43:54 +00003959 typedef Sema::CodeSynthesisContext ActiveInstType;
3960 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003961 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3962 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump11289f42009-09-09 15:08:12 +00003963 if (FunctionTemplateDecl *FunTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003964 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump11289f42009-09-09 15:08:12 +00003965 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003966 "Deduction from the wrong function template?");
Daniel Dunbar54c59642009-07-16 22:10:11 +00003967 (void) FunTmpl;
Gabor Horvath207e7b12018-02-10 14:04:45 +00003968 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003969 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003970 ActiveInst.Entity = New;
Gabor Horvath207e7b12018-02-10 14:04:45 +00003971 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003972 }
3973 }
Mike Stump11289f42009-09-09 15:08:12 +00003974
Douglas Gregor049bdca2009-12-08 17:45:32 +00003975 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3976 assert(Proto && "Function template without prototype?");
3977
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003978 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalldb40c7f2010-12-14 08:05:40 +00003979 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003980
Richard Smithf623c962012-04-17 00:58:00 +00003981 // DR1330: In C++11, defer instantiation of a non-trivial
3982 // exception specification.
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003983 // DR1484: Local classes and their members are instantiated along with the
3984 // containing function.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003985 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smith8acb4282014-07-31 21:57:55 +00003986 EPI.ExceptionSpec.Type != EST_None &&
3987 EPI.ExceptionSpec.Type != EST_DynamicNone &&
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003988 EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
Serge Pavlov73c6a242015-08-23 10:22:28 +00003989 !Tmpl->isLexicallyWithinFunctionOrMethod()) {
Richard Smithd3729422012-04-19 00:08:28 +00003990 FunctionDecl *ExceptionSpecTemplate = Tmpl;
Richard Smith8acb4282014-07-31 21:57:55 +00003991 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
3992 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
Richard Smith185be182013-04-10 05:48:59 +00003993 ExceptionSpecificationType NewEST = EST_Uninstantiated;
Richard Smith8acb4282014-07-31 21:57:55 +00003994 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
Richard Smith185be182013-04-10 05:48:59 +00003995 NewEST = EST_Unevaluated;
Richard Smithd3729422012-04-19 00:08:28 +00003996
Richard Smithf623c962012-04-17 00:58:00 +00003997 // Mark the function has having an uninstantiated exception specification.
3998 const FunctionProtoType *NewProto
3999 = New->getType()->getAs<FunctionProtoType>();
4000 assert(NewProto && "Template instantiation without function prototype?");
4001 EPI = NewProto->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00004002 EPI.ExceptionSpec.Type = NewEST;
4003 EPI.ExceptionSpec.SourceDecl = New;
4004 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
Reid Kleckner896b32f2013-06-10 20:51:09 +00004005 New->setType(SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00004006 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00004007 } else {
Faisal Vali40fd4ce2017-05-09 04:17:15 +00004008 Sema::ContextRAII SwitchContext(SemaRef, New);
Richard Smith2e321552014-11-12 02:00:47 +00004009 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00004010 }
Douglas Gregor049bdca2009-12-08 17:45:32 +00004011 }
4012
Rafael Espindolaba195cf2011-07-06 15:46:09 +00004013 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithf623c962012-04-17 00:58:00 +00004014 const FunctionDecl *Definition = Tmpl;
Rafael Espindolaba195cf2011-07-06 15:46:09 +00004015 Tmpl->isDefined(Definition);
4016
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00004017 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4018 LateAttrs, StartingScope);
Douglas Gregor08329632010-06-15 17:05:35 +00004019
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004020 return false;
4021}
4022
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004023/// Initializes common fields of an instantiated method
Douglas Gregor21342092009-03-24 00:38:23 +00004024/// declaration (New) from the corresponding fields of its template
4025/// (Tmpl).
4026///
4027/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00004028bool
4029TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor21342092009-03-24 00:38:23 +00004030 CXXMethodDecl *Tmpl) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004031 if (InitFunctionInstantiation(New, Tmpl))
4032 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004033
Richard Smith5159bbad2018-09-05 22:30:37 +00004034 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4035 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4036
Douglas Gregor21342092009-03-24 00:38:23 +00004037 New->setAccess(Tmpl->getAccess());
Fariborz Jahanian6dfc1972009-12-03 18:44:40 +00004038 if (Tmpl->isVirtualAsWritten())
Douglas Gregor11c024b2010-09-28 20:50:54 +00004039 New->setVirtualAsWritten(true);
Douglas Gregor21342092009-03-24 00:38:23 +00004040
Douglas Gregor21342092009-03-24 00:38:23 +00004041 // FIXME: New needs a pointer to Tmpl
4042 return false;
4043}
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004044
Richard Smith50e291e2018-01-02 23:52:42 +00004045/// Instantiate (or find existing instantiation of) a function template with a
4046/// given set of template arguments.
4047///
4048/// Usually this should not be used, and template argument deduction should be
4049/// used in its place.
4050FunctionDecl *
4051Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
4052 const TemplateArgumentList *Args,
4053 SourceLocation Loc) {
4054 FunctionDecl *FD = FTD->getTemplatedDecl();
4055
4056 sema::TemplateDeductionInfo Info(Loc);
4057 InstantiatingTemplate Inst(
4058 *this, Loc, FTD, Args->asArray(),
4059 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
4060 if (Inst.isInvalid())
4061 return nullptr;
4062
4063 ContextRAII SavedContext(*this, FD);
4064 MultiLevelTemplateArgumentList MArgs(*Args);
4065
4066 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4067}
4068
Reid Kleckner61195e12017-01-05 01:08:22 +00004069/// In the MS ABI, we need to instantiate default arguments of dllexported
4070/// default constructors along with the constructor definition. This allows IR
4071/// gen to emit a constructor closure which calls the default constructor with
4072/// its default arguments.
4073static void InstantiateDefaultCtorDefaultArgs(Sema &S,
4074 CXXConstructorDecl *Ctor) {
4075 assert(S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4076 Ctor->isDefaultConstructor());
4077 unsigned NumParams = Ctor->getNumParams();
4078 if (NumParams == 0)
4079 return;
4080 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
4081 if (!Attr)
4082 return;
4083 for (unsigned I = 0; I != NumParams; ++I) {
4084 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
4085 Ctor->getParamDecl(I));
4086 S.DiscardCleanupsInEvaluationContext();
4087 }
4088}
4089
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004090/// Instantiate the definition of the given function from its
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004091/// template.
4092///
Douglas Gregordda7ced2009-06-30 17:20:14 +00004093/// \param PointOfInstantiation the point at which the instantiation was
4094/// required. Note that this is not precisely a "point of instantiation"
4095/// for the function, but it's close.
4096///
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004097/// \param Function the already-instantiated declaration of a
Douglas Gregordda7ced2009-06-30 17:20:14 +00004098/// function template specialization or member function of a class template
4099/// specialization.
4100///
4101/// \param Recursive if true, recursively instantiates any functions that
4102/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00004103///
4104/// \param DefinitionRequired if true, then we are performing an explicit
4105/// instantiation where the body of the function is required. Complain if
4106/// there is no such body.
Douglas Gregor85673582009-05-18 17:01:57 +00004107void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregordda7ced2009-06-30 17:20:14 +00004108 FunctionDecl *Function,
Douglas Gregora8b89d22009-10-15 14:05:49 +00004109 bool Recursive,
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00004110 bool DefinitionRequired,
4111 bool AtEndOfTU) {
Richard Smithcb189572017-10-28 01:15:00 +00004112 if (Function->isInvalidDecl() || Function->isDefined() ||
4113 isa<CXXDeductionGuideDecl>(Function))
Douglas Gregorb4850462009-05-14 23:26:13 +00004114 return;
4115
Francois Pichet00c7e6c2011-08-14 03:52:19 +00004116 // Never instantiate an explicit specialization except if it is a class scope
4117 // explicit specialization.
Richard Smithf19a8b02019-05-02 00:49:14 +00004118 TemplateSpecializationKind TSK =
4119 Function->getTemplateSpecializationKindForInstantiation();
4120 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor86d142a2009-10-08 07:24:58 +00004121 return;
Douglas Gregor69f6a362010-05-17 17:34:56 +00004122
Douglas Gregor24c332b2009-05-14 21:06:31 +00004123 // Find the function body that we'll be substituting.
Douglas Gregorafca3b42009-10-27 20:53:28 +00004124 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Alexis Hunt23f6b832011-05-27 20:00:14 +00004125 assert(PatternDecl && "instantiating a non-template");
4126
Richard Smith6f4e2e02016-08-23 19:41:39 +00004127 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
Richard Smith3f6865a82016-08-23 21:12:54 +00004128 Stmt *Pattern = nullptr;
4129 if (PatternDef) {
4130 Pattern = PatternDef->getBody(PatternDef);
Richard Smith6f4e2e02016-08-23 19:41:39 +00004131 PatternDecl = PatternDef;
Richard Smith6c7161162017-08-12 01:46:03 +00004132 if (PatternDef->willHaveBody())
4133 PatternDef = nullptr;
Richard Smith3f6865a82016-08-23 21:12:54 +00004134 }
Douglas Gregor24c332b2009-05-14 21:06:31 +00004135
Vassil Vassilevb21ee082016-08-18 22:01:25 +00004136 // FIXME: We need to track the instantiation stack in order to know which
4137 // definitions should be visible within this instantiation.
4138 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
4139 Function->getInstantiatedFromMemberFunction(),
Richard Smith6f4e2e02016-08-23 19:41:39 +00004140 PatternDecl, PatternDef, TSK,
4141 /*Complain*/DefinitionRequired)) {
4142 if (DefinitionRequired)
4143 Function->setInvalidDecl();
4144 else if (TSK == TSK_ExplicitInstantiationDefinition) {
4145 // Try again at the end of the translation unit (at which point a
4146 // definition will be required).
4147 assert(!Recursive);
Sunil Srivastava15ed2922017-06-20 22:08:44 +00004148 Function->setInstantiationIsPending(true);
Richard Smith6f4e2e02016-08-23 19:41:39 +00004149 PendingInstantiations.push_back(
4150 std::make_pair(Function, PointOfInstantiation));
4151 } else if (TSK == TSK_ImplicitInstantiation) {
Nick Lewycky2adab1b2018-01-02 19:10:12 +00004152 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004153 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
Richard Smith6f4e2e02016-08-23 19:41:39 +00004154 Diag(PointOfInstantiation, diag::warn_func_template_missing)
4155 << Function;
4156 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4157 if (getLangOpts().CPlusPlus11)
4158 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
4159 << Function;
4160 }
4161 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +00004162
Richard Smith6f4e2e02016-08-23 19:41:39 +00004163 return;
4164 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +00004165
Francois Pichet1c229c02011-04-22 22:18:13 +00004166 // Postpone late parsed template instantiations.
Alexis Hunt23f6b832011-05-27 20:00:14 +00004167 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky610128e2011-05-12 03:51:24 +00004168 !LateTemplateParser) {
Sunil Srivastava15ed2922017-06-20 22:08:44 +00004169 Function->setInstantiationIsPending(true);
Reid Kleckner24bd88c2018-03-26 18:22:47 +00004170 LateParsedInstantiations.push_back(
4171 std::make_pair(Function, PointOfInstantiation));
Francois Pichet1c229c02011-04-22 22:18:13 +00004172 return;
4173 }
4174
Anton Afanasyevd880de22019-03-30 08:42:48 +00004175 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
Lubos Lunakab8cde42019-05-12 10:39:21 +00004176 std::string Name;
4177 llvm::raw_string_ostream OS(Name);
4178 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
4179 /*Qualified=*/true);
4180 return Name;
Anton Afanasyevd880de22019-03-30 08:42:48 +00004181 });
4182
Nico Weberae4bb8c2014-08-15 23:21:41 +00004183 // If we're performing recursive template instantiation, create our own
4184 // queue of pending implicit instantiations that we will instantiate later,
4185 // while we're still within our own instantiation context.
4186 // This has to happen before LateTemplateParser below is called, so that
4187 // it marks vtables used in late parsed templates as used.
Richard Smith4f3e3812017-05-20 01:36:41 +00004188 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4189 /*Enabled=*/Recursive);
4190 LocalEagerInstantiationScope LocalInstantiations(*this);
Nico Weberae4bb8c2014-08-15 23:21:41 +00004191
David Majnemerf0a84f22013-08-16 08:29:13 +00004192 // Call the LateTemplateParser callback if there is a need to late parse
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004193 // a templated function definition.
Alexis Hunt23f6b832011-05-27 20:00:14 +00004194 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet1c229c02011-04-22 22:18:13 +00004195 LateTemplateParser) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00004196 // FIXME: Optimize to allow individual templates to be deserialized.
4197 if (PatternDecl->isFromASTFile())
4198 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
4199
Justin Lebar28f09c52016-10-10 16:26:08 +00004200 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
4201 assert(LPTIter != LateParsedTemplateMap.end() &&
4202 "missing LateParsedTemplate");
4203 LateTemplateParser(OpaqueParser, *LPTIter->second);
Francois Pichet1c229c02011-04-22 22:18:13 +00004204 Pattern = PatternDecl->getBody(PatternDecl);
4205 }
4206
Richard Smith6f4e2e02016-08-23 19:41:39 +00004207 // Note, we should never try to instantiate a deleted function template.
Ilya Biryukova27eca22017-12-20 14:32:38 +00004208 assert((Pattern || PatternDecl->isDefaulted() ||
4209 PatternDecl->hasSkippedBody()) &&
Richard Smith6f4e2e02016-08-23 19:41:39 +00004210 "unexpected kind of function template definition");
Douglas Gregor24c332b2009-05-14 21:06:31 +00004211
Richard Smith2a7d4812013-05-04 07:00:32 +00004212 // C++1y [temp.explicit]p10:
4213 // Except for inline functions, declarations with types deduced from their
4214 // initializer or return value, and class template specializations, other
4215 // explicit instantiation declarations have the effect of suppressing the
4216 // implicit instantiation of the entity to which they refer.
Vassil Vassilevb21ee082016-08-18 22:01:25 +00004217 if (TSK == TSK_ExplicitInstantiationDeclaration &&
Richard Smith2a7d4812013-05-04 07:00:32 +00004218 !PatternDecl->isInlined() &&
Alp Toker314cc812014-01-25 16:55:45 +00004219 !PatternDecl->getReturnType()->getContainedAutoType())
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00004220 return;
Mike Stump11289f42009-09-09 15:08:12 +00004221
Richard Smith195d8ef2014-05-29 03:15:31 +00004222 if (PatternDecl->isInlined()) {
4223 // Function, and all later redeclarations of it (from imported modules,
4224 // for instance), are now implicitly inline.
4225 for (auto *D = Function->getMostRecentDecl(); /**/;
4226 D = D->getPreviousDecl()) {
4227 D->setImplicitlyInline();
4228 if (D == Function)
4229 break;
4230 }
4231 }
Richard Smithf3814ad2013-01-25 00:08:28 +00004232
Douglas Gregor85673582009-05-18 17:01:57 +00004233 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
Richard Smith54f18e82016-08-31 02:15:21 +00004234 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004235 return;
Jordan Rose1e879d82018-03-23 00:07:18 +00004236 PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00004237 "instantiating function definition");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004238
Vassil Vassilevb21ee082016-08-18 22:01:25 +00004239 // The instantiation is visible here, even if it was first declared in an
4240 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00004241 Function->setVisibleDespiteOwningModule();
Vassil Vassilevb21ee082016-08-18 22:01:25 +00004242
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00004243 // Copy the inner loc start from the pattern.
4244 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
4245
Faisal Valid143a0c2017-04-01 21:30:49 +00004246 EnterExpressionEvaluationContext EvalContext(
4247 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Douglas Gregor67da0d92009-05-15 17:59:04 +00004248
Douglas Gregorb4850462009-05-14 23:26:13 +00004249 // Introduce a new scope where local variable instantiations will be
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004250 // recorded, unless we're actually a member function within a local
4251 // class, in which case we need to merge our results with the parent
4252 // scope (of the enclosing function).
4253 bool MergeWithParentScope = false;
4254 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
4255 MergeWithParentScope = Rec->isLocalClass();
4256
4257 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00004258
Richard Smithbd305122012-12-11 01:14:52 +00004259 if (PatternDecl->isDefaulted())
Alexis Hunt61ae8d32011-05-23 23:14:04 +00004260 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smithbd305122012-12-11 01:14:52 +00004261 else {
Richard Smithcc928662014-10-17 20:37:29 +00004262 MultiLevelTemplateArgumentList TemplateArgs =
4263 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
4264
4265 // Substitute into the qualifier; we can get a substitution failure here
4266 // through evil use of alias templates.
4267 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
4268 // of the) lexical context of the pattern?
4269 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
4270
Craig Topperc3ec1492014-05-26 06:22:03 +00004271 ActOnStartOfFunctionDef(nullptr, Function);
Richard Smithbd305122012-12-11 01:14:52 +00004272
4273 // Enter the scope of this instantiation. We don't use
4274 // PushDeclContext because we don't have a scope.
4275 Sema::ContextRAII savedContext(*this, Function);
4276
Richard Smith2e321552014-11-12 02:00:47 +00004277 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
4278 TemplateArgs))
4279 return;
Richard Smithbd305122012-12-11 01:14:52 +00004280
Ilya Biryukov0ee4a082018-03-14 13:18:30 +00004281 StmtResult Body;
Ilya Biryukova27eca22017-12-20 14:32:38 +00004282 if (PatternDecl->hasSkippedBody()) {
4283 ActOnSkippedFunctionBody(Function);
Ilya Biryukov0ee4a082018-03-14 13:18:30 +00004284 Body = nullptr;
Ilya Biryukova27eca22017-12-20 14:32:38 +00004285 } else {
Ilya Biryukov95f0d322017-12-28 13:05:46 +00004286 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
4287 // If this is a constructor, instantiate the member initializers.
4288 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
4289 TemplateArgs);
4290
4291 // If this is an MS ABI dllexport default constructor, instantiate any
4292 // default arguments.
4293 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4294 Ctor->isDefaultConstructor()) {
4295 InstantiateDefaultCtorDefaultArgs(*this, Ctor);
4296 }
4297 }
4298
Ilya Biryukova27eca22017-12-20 14:32:38 +00004299 // Instantiate the function body.
Ilya Biryukov0ee4a082018-03-14 13:18:30 +00004300 Body = SubstStmt(Pattern, TemplateArgs);
Alexis Hunt61ae8d32011-05-23 23:14:04 +00004301
Ilya Biryukova27eca22017-12-20 14:32:38 +00004302 if (Body.isInvalid())
4303 Function->setInvalidDecl();
Ilya Biryukova27eca22017-12-20 14:32:38 +00004304 }
Ilya Biryukov0ee4a082018-03-14 13:18:30 +00004305 // FIXME: finishing the function body while in an expression evaluation
4306 // context seems wrong. Investigate more.
4307 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
Richard Smithbd305122012-12-11 01:14:52 +00004308
4309 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
4310
Richard Smithd28ac5b2014-03-22 23:33:22 +00004311 if (auto *Listener = getASTMutationListener())
4312 Listener->FunctionDefinitionInstantiated(Function);
Richard Smith0ac1b8f2014-03-22 01:43:32 +00004313
Richard Smithbd305122012-12-11 01:14:52 +00004314 savedContext.pop();
Mike Stump11289f42009-09-09 15:08:12 +00004315 }
4316
Douglas Gregor28ad4b52009-05-26 20:50:29 +00004317 DeclGroupRef DG(Function);
4318 Consumer.HandleTopLevelDecl(DG);
Mike Stump11289f42009-09-09 15:08:12 +00004319
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004320 // This class may have local implicit instantiations that need to be
4321 // instantiation within this scope.
Richard Smith4f3e3812017-05-20 01:36:41 +00004322 LocalInstantiations.perform();
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004323 Scope.Exit();
Richard Smith4f3e3812017-05-20 01:36:41 +00004324 GlobalInstantiations.perform();
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004325}
4326
Larisse Voufo39a1e502013-08-06 01:03:05 +00004327VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
4328 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
4329 const TemplateArgumentList &TemplateArgList,
4330 const TemplateArgumentListInfo &TemplateArgsInfo,
4331 SmallVectorImpl<TemplateArgument> &Converted,
4332 SourceLocation PointOfInstantiation, void *InsertPos,
4333 LateInstantiatedAttrVec *LateAttrs,
4334 LocalInstantiationScope *StartingScope) {
4335 if (FromVar->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00004336 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004337
4338 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
Alp Tokerd4a72d52013-10-08 08:09:04 +00004339 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00004340 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004341
4342 MultiLevelTemplateArgumentList TemplateArgLists;
4343 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
4344
Richard Smith8809a0c2013-09-27 20:14:12 +00004345 // Instantiate the first declaration of the variable template: for a partial
4346 // specialization of a static data member template, the first declaration may
4347 // or may not be the declaration in the class; if it's in the class, we want
4348 // to instantiate a member in the class (a declaration), and if it's outside,
4349 // we want to instantiate a definition.
Richard Smithbeef3452014-01-16 23:39:20 +00004350 //
4351 // If we're instantiating an explicitly-specialized member template or member
4352 // partial specialization, don't do this. The member specialization completely
4353 // replaces the original declaration in this case.
4354 bool IsMemberSpec = false;
4355 if (VarTemplatePartialSpecializationDecl *PartialSpec =
4356 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
4357 IsMemberSpec = PartialSpec->isMemberSpecialization();
4358 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
4359 IsMemberSpec = FromTemplate->isMemberSpecialization();
4360 if (!IsMemberSpec)
4361 FromVar = FromVar->getFirstDecl();
Richard Smith8809a0c2013-09-27 20:14:12 +00004362
Manuel Klimek5843add2013-09-30 13:29:01 +00004363 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
4364 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
4365 MultiLevelList);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004366
4367 // TODO: Set LateAttrs and StartingScope ...
4368
4369 return cast_or_null<VarTemplateSpecializationDecl>(
4370 Instantiator.VisitVarTemplateSpecializationDecl(
4371 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
4372}
4373
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004374/// Instantiates a variable template specialization by completing it
Larisse Voufo39a1e502013-08-06 01:03:05 +00004375/// with appropriate type information and initializer.
4376VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
4377 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
4378 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smith435e6472017-12-02 02:48:42 +00004379 assert(PatternDecl->isThisDeclarationADefinition() &&
4380 "don't have a definition to instantiate from");
Larisse Voufo39a1e502013-08-06 01:03:05 +00004381
4382 // Do substitution on the type of the declaration
4383 TypeSourceInfo *DI =
Richard Smith8809a0c2013-09-27 20:14:12 +00004384 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00004385 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
4386 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00004387 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004388
4389 // Update the type of this variable template specialization.
4390 VarSpec->setType(DI->getType());
4391
Richard Smith435e6472017-12-02 02:48:42 +00004392 // Convert the declaration into a definition now.
4393 VarSpec->setCompleteDefinition();
4394
Larisse Voufo39a1e502013-08-06 01:03:05 +00004395 // Instantiate the initializer.
4396 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
4397
4398 return VarSpec;
4399}
4400
4401/// BuildVariableInstantiation - Used after a new variable has been created.
4402/// Sets basic variable data and decides whether to postpone the
4403/// variable instantiation.
4404void Sema::BuildVariableInstantiation(
4405 VarDecl *NewVar, VarDecl *OldVar,
4406 const MultiLevelTemplateArgumentList &TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00004407 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
4408 LocalInstantiationScope *StartingScope,
Richard Smitha6b41d72019-05-03 23:51:38 +00004409 bool InstantiatingVarTemplate,
4410 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
4411 // Instantiating a partial specialization to produce a partial
4412 // specialization.
4413 bool InstantiatingVarTemplatePartialSpec =
4414 isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
4415 isa<VarTemplatePartialSpecializationDecl>(NewVar);
4416 // Instantiating from a variable template (or partial specialization) to
4417 // produce a variable template specialization.
4418 bool InstantiatingSpecFromTemplate =
4419 isa<VarTemplateSpecializationDecl>(NewVar) &&
4420 (OldVar->getDescribedVarTemplate() ||
4421 isa<VarTemplatePartialSpecializationDecl>(OldVar));
Larisse Voufo39a1e502013-08-06 01:03:05 +00004422
Richard Smith541b38b2013-09-20 01:15:31 +00004423 // If we are instantiating a local extern declaration, the
4424 // instantiation belongs lexically to the containing function.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004425 // If we are instantiating a static data member defined
4426 // out-of-line, the instantiation will have the same lexical
4427 // context (which will be a namespace scope) as the template.
Richard Smith541b38b2013-09-20 01:15:31 +00004428 if (OldVar->isLocalExternDecl()) {
4429 NewVar->setLocalExternDecl();
4430 NewVar->setLexicalDeclContext(Owner);
4431 } else if (OldVar->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00004432 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
4433 NewVar->setTSCSpec(OldVar->getTSCSpec());
4434 NewVar->setInitStyle(OldVar->getInitStyle());
4435 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
George Karpenkovec38cf72018-03-29 00:56:24 +00004436 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004437 NewVar->setConstexpr(OldVar->isConstexpr());
Richard Smithbb13c9a2013-09-28 04:02:39 +00004438 NewVar->setInitCapture(OldVar->isInitCapture());
Richard Smith1c34fb72013-08-13 18:18:50 +00004439 NewVar->setPreviousDeclInSameBlockScope(
4440 OldVar->isPreviousDeclInSameBlockScope());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004441 NewVar->setAccess(OldVar->getAccess());
4442
Richard Smith0b551192013-09-23 23:12:22 +00004443 if (!OldVar->isStaticDataMember()) {
Rafael Espindolae4865d22013-10-23 16:46:34 +00004444 if (OldVar->isUsed(false))
4445 NewVar->setIsUsed();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004446 NewVar->setReferenced(OldVar->isReferenced());
4447 }
4448
4449 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
4450
Richard Smith541b38b2013-09-20 01:15:31 +00004451 LookupResult Previous(
4452 *this, NewVar->getDeclName(), NewVar->getLocation(),
4453 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
4454 : Sema::LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00004455 NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
4456 : forRedeclarationInCurContext());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004457
Argyrios Kyrtzidis91486222013-11-27 08:34:14 +00004458 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
4459 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
4460 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
Richard Smith1c34fb72013-08-13 18:18:50 +00004461 // We have a previous declaration. Use that one, so we merge with the
4462 // right type.
4463 if (NamedDecl *NewPrev = FindInstantiatedDecl(
4464 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
4465 Previous.addDecl(NewPrev);
4466 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
Richard Smitha6b41d72019-05-03 23:51:38 +00004467 OldVar->hasLinkage()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004468 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
Richard Smitha6b41d72019-05-03 23:51:38 +00004469 } else if (PrevDeclForVarTemplateSpecialization) {
4470 Previous.addDecl(PrevDeclForVarTemplateSpecialization);
4471 }
Larisse Voufo72caf2b2013-08-22 00:59:14 +00004472 CheckVariableDeclaration(NewVar, Previous);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004473
Richard Smith541b38b2013-09-20 01:15:31 +00004474 if (!InstantiatingVarTemplate) {
4475 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
4476 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
Larisse Voufo39a1e502013-08-06 01:03:05 +00004477 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
Richard Smith541b38b2013-09-20 01:15:31 +00004478 }
4479
4480 if (!OldVar->isOutOfLine()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004481 if (NewVar->getDeclContext()->isFunctionOrMethod())
4482 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
4483 }
4484
4485 // Link instantiations of static data members back to the template from
4486 // which they were instantiated.
Richard Smitha6b41d72019-05-03 23:51:38 +00004487 //
4488 // Don't do this when instantiating a template (we link the template itself
4489 // back in that case) nor when instantiating a static data member template
4490 // (that's not a member specialization).
4491 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
4492 !InstantiatingSpecFromTemplate)
Larisse Voufo39a1e502013-08-06 01:03:05 +00004493 NewVar->setInstantiationOfStaticDataMember(OldVar,
4494 TSK_ImplicitInstantiation);
4495
Richard Smitha6b41d72019-05-03 23:51:38 +00004496 // If the pattern is an (in-class) explicit specialization, then the result
4497 // is also an explicit specialization.
4498 if (VarTemplateSpecializationDecl *OldVTSD =
4499 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
4500 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
4501 !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
4502 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
4503 TSK_ExplicitSpecialization);
4504 }
4505
David Majnemerdbc0c8f2013-12-04 09:01:55 +00004506 // Forward the mangling number from the template to the instantiated decl.
4507 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
David Majnemer2206bf52014-03-05 08:57:59 +00004508 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
David Majnemerdbc0c8f2013-12-04 09:01:55 +00004509
Richard Smitha6b41d72019-05-03 23:51:38 +00004510 // Figure out whether to eagerly instantiate the initializer.
4511 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
4512 // We're producing a template. Don't instantiate the initializer yet.
4513 } else if (NewVar->getType()->isUndeducedType()) {
4514 // We need the type to complete the declaration of the variable.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004515 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
Richard Smitha6b41d72019-05-03 23:51:38 +00004516 } else if (InstantiatingSpecFromTemplate ||
4517 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
4518 !NewVar->isThisDeclarationADefinition())) {
4519 // Delay instantiation of the initializer for variable template
4520 // specializations or inline static data members until a definition of the
4521 // variable is needed.
4522 } else {
4523 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
4524 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004525
4526 // Diagnose unused local variables with dependent types, where the diagnostic
4527 // will have been deferred.
4528 if (!NewVar->isInvalidDecl() &&
Nico Weber72889432014-09-06 01:25:55 +00004529 NewVar->getDeclContext()->isFunctionOrMethod() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004530 OldVar->getType()->isDependentType())
4531 DiagnoseUnusedDecl(NewVar);
4532}
4533
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004534/// Instantiate the initializer of a variable.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004535void Sema::InstantiateVariableInitializer(
4536 VarDecl *Var, VarDecl *OldVar,
4537 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smith891fc7f2017-12-05 01:31:47 +00004538 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4539 L->VariableDefinitionInstantiated(Var);
4540
Richard Smith62f19e72016-06-25 00:15:56 +00004541 // We propagate the 'inline' flag with the initializer, because it
4542 // would otherwise imply that the variable is a definition for a
4543 // non-static data member.
4544 if (OldVar->isInlineSpecified())
4545 Var->setInlineSpecified();
4546 else if (OldVar->isInline())
4547 Var->setImplicitlyInline();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004548
Larisse Voufo39a1e502013-08-06 01:03:05 +00004549 if (OldVar->getInit()) {
Richard Smithc95d2c52017-09-22 04:25:05 +00004550 EnterExpressionEvaluationContext Evaluated(
4551 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004552
4553 // Instantiate the initializer.
Akira Hatanakab87faff2016-04-28 23:50:12 +00004554 ExprResult Init;
4555
4556 {
4557 ContextRAII SwitchContext(*this, Var->getDeclContext());
4558 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
4559 OldVar->getInitStyle() == VarDecl::CallInit);
4560 }
4561
Larisse Voufo39a1e502013-08-06 01:03:05 +00004562 if (!Init.isInvalid()) {
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00004563 Expr *InitExpr = Init.get();
4564
Richard Smith95b83e92014-07-10 20:53:43 +00004565 if (Var->hasAttr<DLLImportAttr>() &&
4566 (!InitExpr ||
4567 !InitExpr->isConstantInitializer(getASTContext(), false))) {
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00004568 // Do not dynamically initialize dllimport variables.
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00004569 } else if (InitExpr) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004570 bool DirectInit = OldVar->isDirectInit();
Richard Smith3beb7c62017-01-12 02:27:38 +00004571 AddInitializerToDecl(Var, InitExpr, DirectInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004572 } else
Richard Smith3beb7c62017-01-12 02:27:38 +00004573 ActOnUninitializedDecl(Var);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004574 } else {
4575 // FIXME: Not too happy about invalidating the declaration
4576 // because of a bogus initializer.
4577 Var->setInvalidDecl();
4578 }
Richard Smith54f18e82016-08-31 02:15:21 +00004579 } else {
George Burgess IV18b28a82018-03-20 03:27:44 +00004580 // `inline` variables are a definition and declaration all in one; we won't
4581 // pick up an initializer from anywhere else.
4582 if (Var->isStaticDataMember() && !Var->isInline()) {
Richard Smith54f18e82016-08-31 02:15:21 +00004583 if (!Var->isOutOfLine())
4584 return;
4585
4586 // If the declaration inside the class had an initializer, don't add
4587 // another one to the out-of-line definition.
4588 if (OldVar->getFirstDecl()->hasInit())
4589 return;
4590 }
4591
4592 // We'll add an initializer to a for-range declaration later.
George Karpenkovec38cf72018-03-29 00:56:24 +00004593 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
Richard Smith54f18e82016-08-31 02:15:21 +00004594 return;
4595
Richard Smith3beb7c62017-01-12 02:27:38 +00004596 ActOnUninitializedDecl(Var);
Richard Smith54f18e82016-08-31 02:15:21 +00004597 }
Artem Beleviche9fa53a2018-06-06 22:37:25 +00004598
4599 if (getLangOpts().CUDA)
4600 checkAllowedCUDAInitializer(Var);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004601}
4602
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004603/// Instantiate the definition of the given variable from its
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004604/// template.
4605///
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004606/// \param PointOfInstantiation the point at which the instantiation was
4607/// required. Note that this is not precisely a "point of instantiation"
Richard Smith891fc7f2017-12-05 01:31:47 +00004608/// for the variable, but it's close.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004609///
Richard Smith891fc7f2017-12-05 01:31:47 +00004610/// \param Var the already-instantiated declaration of a templated variable.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004611///
4612/// \param Recursive if true, recursively instantiates any functions that
4613/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00004614///
4615/// \param DefinitionRequired if true, then we are performing an explicit
Richard Smith891fc7f2017-12-05 01:31:47 +00004616/// instantiation where a definition of the variable is required. Complain
4617/// if there is no such definition.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004618void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
4619 VarDecl *Var, bool Recursive,
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00004620 bool DefinitionRequired, bool AtEndOfTU) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004621 if (Var->isInvalidDecl())
4622 return;
Mike Stump11289f42009-09-09 15:08:12 +00004623
Richard Smitha6b41d72019-05-03 23:51:38 +00004624 // Never instantiate an explicitly-specialized entity.
4625 TemplateSpecializationKind TSK =
4626 Var->getTemplateSpecializationKindForInstantiation();
4627 if (TSK == TSK_ExplicitSpecialization)
4628 return;
4629
4630 // Find the pattern and the arguments to substitute into it.
4631 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
4632 assert(PatternDecl && "no pattern for templated variable");
Richard Smith8809a0c2013-09-27 20:14:12 +00004633 MultiLevelTemplateArgumentList TemplateArgs =
4634 getTemplateInstantiationArgs(Var);
Mike Stump11289f42009-09-09 15:08:12 +00004635
Richard Smitha6b41d72019-05-03 23:51:38 +00004636 VarTemplateSpecializationDecl *VarSpec =
4637 dyn_cast<VarTemplateSpecializationDecl>(Var);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004638 if (VarSpec) {
Richard Smith8809a0c2013-09-27 20:14:12 +00004639 // If this is a variable template specialization, make sure that it is
Richard Smitha6b41d72019-05-03 23:51:38 +00004640 // non-dependent.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004641 bool InstantiationDependent = false;
4642 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
4643 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
4644 "Only instantiate variable template specializations that are "
4645 "not type-dependent");
Larisse Voufo4154f462013-08-06 03:57:41 +00004646 (void)InstantiationDependent;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004647
Richard Smith8809a0c2013-09-27 20:14:12 +00004648 // If this is a static data member template, there might be an
4649 // uninstantiated initializer on the declaration. If so, instantiate
4650 // it now.
Richard Smith891fc7f2017-12-05 01:31:47 +00004651 //
4652 // FIXME: This largely duplicates what we would do below. The difference
4653 // is that along this path we may instantiate an initializer from an
4654 // in-class declaration of the template and instantiate the definition
4655 // from a separate out-of-class definition.
Richard Smith8809a0c2013-09-27 20:14:12 +00004656 if (PatternDecl->isStaticDataMember() &&
Rafael Espindola8db352d2013-10-17 15:37:26 +00004657 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
Richard Smith8809a0c2013-09-27 20:14:12 +00004658 !Var->hasInit()) {
4659 // FIXME: Factor out the duplicated instantiation context setup/tear down
4660 // code here.
4661 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Richard Smith54f18e82016-08-31 02:15:21 +00004662 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
Richard Smith8809a0c2013-09-27 20:14:12 +00004663 return;
Jordan Rose1e879d82018-03-23 00:07:18 +00004664 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00004665 "instantiating variable initializer");
Richard Smith8809a0c2013-09-27 20:14:12 +00004666
Richard Smithedbc6e92016-10-14 21:41:24 +00004667 // The instantiation is visible here, even if it was first declared in an
4668 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00004669 Var->setVisibleDespiteOwningModule();
Richard Smithedbc6e92016-10-14 21:41:24 +00004670
Richard Smith8809a0c2013-09-27 20:14:12 +00004671 // If we're performing recursive template instantiation, create our own
4672 // queue of pending implicit instantiations that we will instantiate
4673 // later, while we're still within our own instantiation context.
Richard Smith4f3e3812017-05-20 01:36:41 +00004674 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4675 /*Enabled=*/Recursive);
Richard Smith8809a0c2013-09-27 20:14:12 +00004676 LocalInstantiationScope Local(*this);
Richard Smith4f3e3812017-05-20 01:36:41 +00004677 LocalEagerInstantiationScope LocalInstantiations(*this);
Richard Smith8809a0c2013-09-27 20:14:12 +00004678
4679 // Enter the scope of this instantiation. We don't use
4680 // PushDeclContext because we don't have a scope.
4681 ContextRAII PreviousContext(*this, Var->getDeclContext());
4682 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
4683 PreviousContext.pop();
4684
Richard Smith8809a0c2013-09-27 20:14:12 +00004685 // This variable may have local implicit instantiations that need to be
4686 // instantiated within this scope.
Richard Smith4f3e3812017-05-20 01:36:41 +00004687 LocalInstantiations.perform();
Richard Smith8809a0c2013-09-27 20:14:12 +00004688 Local.Exit();
Richard Smith4f3e3812017-05-20 01:36:41 +00004689 GlobalInstantiations.perform();
Richard Smith8809a0c2013-09-27 20:14:12 +00004690 }
Richard Smith8809a0c2013-09-27 20:14:12 +00004691 } else {
Richard Smitha6b41d72019-05-03 23:51:38 +00004692 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&
4693 "not a static data member?");
Larisse Voufo39a1e502013-08-06 01:03:05 +00004694 }
4695
Richard Smitha6b41d72019-05-03 23:51:38 +00004696 VarDecl *Def = PatternDecl->getDefinition(getASTContext());
Richard Smith6739a102016-05-05 00:56:12 +00004697
Richard Smith8809a0c2013-09-27 20:14:12 +00004698 // If we don't have a definition of the variable template, we won't perform
4699 // any instantiation. Rather, we rely on the user to instantiate this
4700 // definition (or provide a specialization for it) in another translation
4701 // unit.
Richard Smithedbc6e92016-10-14 21:41:24 +00004702 if (!Def && !DefinitionRequired) {
4703 if (TSK == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00004704 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004705 std::make_pair(Var, PointOfInstantiation));
Richard Smithedbc6e92016-10-14 21:41:24 +00004706 } else if (TSK == TSK_ImplicitInstantiation) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00004707 // Warn about missing definition at the end of translation unit.
Nick Lewycky2adab1b2018-01-02 19:10:12 +00004708 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004709 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00004710 Diag(PointOfInstantiation, diag::warn_var_template_missing)
4711 << Var;
4712 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4713 if (getLangOpts().CPlusPlus11)
4714 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
4715 }
Richard Smithedbc6e92016-10-14 21:41:24 +00004716 return;
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004717 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004718 }
4719
Richard Smithedbc6e92016-10-14 21:41:24 +00004720 // FIXME: We need to track the instantiation stack in order to know which
4721 // definitions should be visible within this instantiation.
4722 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
4723 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
4724 /*InstantiatedFromMember*/false,
4725 PatternDecl, Def, TSK,
4726 /*Complain*/DefinitionRequired))
4727 return;
4728
Larisse Voufo39a1e502013-08-06 01:03:05 +00004729 // C++11 [temp.explicit]p10:
Richard Smith4309b662017-10-18 22:45:01 +00004730 // Except for inline functions, const variables of literal types, variables
4731 // of reference types, [...] explicit instantiation declarations
Larisse Voufo39a1e502013-08-06 01:03:05 +00004732 // have the effect of suppressing the implicit instantiation of the entity
4733 // to which they refer.
Richard Smith715f7a12019-06-11 17:50:32 +00004734 //
4735 // FIXME: That's not exactly the same as "might be usable in constant
4736 // expressions", which only allows constexpr variables and const integral
4737 // types, not arbitrary const literal types.
Richard Smith4309b662017-10-18 22:45:01 +00004738 if (TSK == TSK_ExplicitInstantiationDeclaration &&
Richard Smith715f7a12019-06-11 17:50:32 +00004739 !Var->mightBeUsableInConstantExpressions(getASTContext()))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004740 return;
Mike Stump11289f42009-09-09 15:08:12 +00004741
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00004742 // Make sure to pass the instantiated variable to the consumer at the end.
4743 struct PassToConsumerRAII {
4744 ASTConsumer &Consumer;
4745 VarDecl *Var;
4746
4747 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
4748 : Consumer(Consumer), Var(Var) { }
4749
4750 ~PassToConsumerRAII() {
Richard Smith8809a0c2013-09-27 20:14:12 +00004751 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00004752 }
4753 } PassToConsumerRAII(Consumer, Var);
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00004754
Reid Klecknere07140e2015-04-15 01:08:06 +00004755 // If we already have a definition, we're done.
4756 if (VarDecl *Def = Var->getDefinition()) {
4757 // We may be explicitly instantiating something we've already implicitly
4758 // instantiated.
4759 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
4760 PointOfInstantiation);
Richard Smith8809a0c2013-09-27 20:14:12 +00004761 return;
Reid Klecknere07140e2015-04-15 01:08:06 +00004762 }
Douglas Gregor57d4f972011-06-03 03:35:07 +00004763
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004764 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Richard Smith54f18e82016-08-31 02:15:21 +00004765 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004766 return;
Jordan Rose1e879d82018-03-23 00:07:18 +00004767 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00004768 "instantiating variable definition");
Mike Stump11289f42009-09-09 15:08:12 +00004769
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004770 // If we're performing recursive template instantiation, create our own
4771 // queue of pending implicit instantiations that we will instantiate later,
4772 // while we're still within our own instantiation context.
Richard Smith4f3e3812017-05-20 01:36:41 +00004773 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4774 /*Enabled=*/Recursive);
Mike Stump11289f42009-09-09 15:08:12 +00004775
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004776 // Enter the scope of this instantiation. We don't use
4777 // PushDeclContext because we don't have a scope.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004778 ContextRAII PreviousContext(*this, Var->getDeclContext());
Douglas Gregora86bc002012-02-16 21:36:18 +00004779 LocalInstantiationScope Local(*this);
John McCall2957e3e2011-02-14 20:37:25 +00004780
Richard Smith4f3e3812017-05-20 01:36:41 +00004781 LocalEagerInstantiationScope LocalInstantiations(*this);
4782
Larisse Voufo39a1e502013-08-06 01:03:05 +00004783 VarDecl *OldVar = Var;
Richard Smith62f19e72016-06-25 00:15:56 +00004784 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
4785 // We're instantiating an inline static data member whose definition was
4786 // provided inside the class.
Richard Smith62f19e72016-06-25 00:15:56 +00004787 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4788 } else if (!VarSpec) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004789 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Richard Smith8809a0c2013-09-27 20:14:12 +00004790 TemplateArgs));
Richard Smith62f19e72016-06-25 00:15:56 +00004791 } else if (Var->isStaticDataMember() &&
4792 Var->getLexicalDeclContext()->isRecord()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00004793 // We need to instantiate the definition of a static data member template,
4794 // and all we have is the in-class declaration of it. Instantiate a separate
4795 // declaration of the definition.
4796 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
4797 TemplateArgs);
4798 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
Craig Topperc3ec1492014-05-26 06:22:03 +00004799 VarSpec->getSpecializedTemplate(), Def, nullptr,
Richard Smith8809a0c2013-09-27 20:14:12 +00004800 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
4801 if (Var) {
4802 llvm::PointerUnion<VarTemplateDecl *,
4803 VarTemplatePartialSpecializationDecl *> PatternPtr =
4804 VarSpec->getSpecializedTemplateOrPartial();
4805 if (VarTemplatePartialSpecializationDecl *Partial =
4806 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
4807 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
4808 Partial, &VarSpec->getTemplateInstantiationArgs());
4809
4810 // Merge the definition with the declaration.
4811 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
Richard Smithbecb92d2017-10-10 22:33:17 +00004812 LookupOrdinaryName, forRedeclarationInCurContext());
Richard Smith8809a0c2013-09-27 20:14:12 +00004813 R.addDecl(OldVar);
4814 MergeVarDecl(Var, R);
4815
4816 // Attach the initializer.
4817 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4818 }
4819 } else
4820 // Complete the existing variable's definition with an appropriately
4821 // substituted type and initializer.
4822 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004823
4824 PreviousContext.pop();
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004825
4826 if (Var) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004827 PassToConsumerRAII.Var = Var;
Richard Smith8809a0c2013-09-27 20:14:12 +00004828 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
4829 OldVar->getPointOfInstantiation());
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004830 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004831
4832 // This variable may have local implicit instantiations that need to be
4833 // instantiated within this scope.
Richard Smith4f3e3812017-05-20 01:36:41 +00004834 LocalInstantiations.perform();
Douglas Gregora86bc002012-02-16 21:36:18 +00004835 Local.Exit();
Richard Smith4f3e3812017-05-20 01:36:41 +00004836 GlobalInstantiations.perform();
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004837}
Douglas Gregor51783312009-05-27 05:35:12 +00004838
Anders Carlsson70553942009-08-29 05:16:22 +00004839void
4840Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
4841 const CXXConstructorDecl *Tmpl,
4842 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00004843
Richard Trieu9becef62011-09-09 03:18:59 +00004844 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith60f2e1e2012-09-25 00:23:05 +00004845 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004846
Anders Carlsson70553942009-08-29 05:16:22 +00004847 // Instantiate all the initializers.
Aaron Ballman0ad78302014-03-13 17:34:31 +00004848 for (const auto *Init : Tmpl->inits()) {
Chandler Carruthf92bd8c2010-09-03 21:54:20 +00004849 // Only instantiate written initializers, let Sema re-construct implicit
4850 // ones.
4851 if (!Init->isWritten())
4852 continue;
4853
Douglas Gregor44e7df62011-01-04 00:32:56 +00004854 SourceLocation EllipsisLoc;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004855
Douglas Gregor44e7df62011-01-04 00:32:56 +00004856 if (Init->isPackExpansion()) {
4857 // This is a pack expansion. We should expand it now.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004858 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky2c308502013-06-13 00:45:47 +00004859 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor44e7df62011-01-04 00:32:56 +00004860 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky2c308502013-06-13 00:45:47 +00004861 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor44e7df62011-01-04 00:32:56 +00004862 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004863 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00004864 Optional<unsigned> NumExpansions;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004865 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004866 BaseTL.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00004867 Unexpanded,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004868 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004869 RetainExpansion,
Douglas Gregor44e7df62011-01-04 00:32:56 +00004870 NumExpansions)) {
4871 AnyErrors = true;
4872 New->setInvalidDecl();
4873 continue;
4874 }
4875 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004876
4877 // Loop over all of the arguments in the argument pack(s),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004878 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004879 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4880
4881 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004882 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4883 /*CXXDirectInit=*/true);
4884 if (TempInit.isInvalid()) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004885 AnyErrors = true;
4886 break;
4887 }
4888
4889 // Instantiate the base type.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004890 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004891 TemplateArgs,
4892 Init->getSourceLocation(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004893 New->getDeclName());
4894 if (!BaseTInfo) {
4895 AnyErrors = true;
4896 break;
4897 }
4898
4899 // Build the initializer.
Sebastian Redla74948d2011-09-24 17:48:25 +00004900 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004901 BaseTInfo, TempInit.get(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004902 New->getParent(),
4903 SourceLocation());
4904 if (NewInit.isInvalid()) {
4905 AnyErrors = true;
4906 break;
4907 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004908
Douglas Gregor44e7df62011-01-04 00:32:56 +00004909 NewInits.push_back(NewInit.get());
Douglas Gregor44e7df62011-01-04 00:32:56 +00004910 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004911
Douglas Gregor44e7df62011-01-04 00:32:56 +00004912 continue;
4913 }
4914
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004915 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004916 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4917 /*CXXDirectInit=*/true);
4918 if (TempInit.isInvalid()) {
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004919 AnyErrors = true;
4920 continue;
Anders Carlsson70553942009-08-29 05:16:22 +00004921 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004922
Anders Carlsson70553942009-08-29 05:16:22 +00004923 MemInitResult NewInit;
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004924 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4925 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4926 TemplateArgs,
4927 Init->getSourceLocation(),
4928 New->getDeclName());
4929 if (!TInfo) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004930 AnyErrors = true;
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00004931 New->setInvalidDecl();
4932 continue;
4933 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004934
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004935 if (Init->isBaseInitializer())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004936 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004937 New->getParent(), EllipsisLoc);
4938 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004939 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004940 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson70553942009-08-29 05:16:22 +00004941 } else if (Init->isMemberInitializer()) {
Douglas Gregor55e6b312011-03-04 19:46:35 +00004942 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004943 Init->getMemberLocation(),
4944 Init->getMember(),
4945 TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00004946 if (!Member) {
4947 AnyErrors = true;
4948 New->setInvalidDecl();
4949 continue;
4950 }
Mike Stump11289f42009-09-09 15:08:12 +00004951
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004952 NewInit = BuildMemberInitializer(Member, TempInit.get(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004953 Init->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +00004954 } else if (Init->isIndirectMemberInitializer()) {
4955 IndirectFieldDecl *IndirectMember =
Douglas Gregor55e6b312011-03-04 19:46:35 +00004956 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004957 Init->getMemberLocation(),
4958 Init->getIndirectMember(), TemplateArgs));
4959
Douglas Gregor55e6b312011-03-04 19:46:35 +00004960 if (!IndirectMember) {
4961 AnyErrors = true;
4962 New->setInvalidDecl();
Sebastian Redla74948d2011-09-24 17:48:25 +00004963 continue;
Douglas Gregor55e6b312011-03-04 19:46:35 +00004964 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004965
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004966 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004967 Init->getSourceLocation());
Anders Carlsson70553942009-08-29 05:16:22 +00004968 }
4969
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004970 if (NewInit.isInvalid()) {
4971 AnyErrors = true;
Anders Carlsson70553942009-08-29 05:16:22 +00004972 New->setInvalidDecl();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004973 } else {
Richard Trieu9becef62011-09-09 03:18:59 +00004974 NewInits.push_back(NewInit.get());
Anders Carlsson70553942009-08-29 05:16:22 +00004975 }
4976 }
Mike Stump11289f42009-09-09 15:08:12 +00004977
Anders Carlsson70553942009-08-29 05:16:22 +00004978 // Assign all the initializers to the new constructor.
John McCall48871652010-08-21 09:40:31 +00004979 ActOnMemInitializers(New,
Anders Carlsson70553942009-08-29 05:16:22 +00004980 /*FIXME: ColonLoc */
4981 SourceLocation(),
David Blaikie3fc2f912013-01-17 05:26:25 +00004982 NewInits,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004983 AnyErrors);
Anders Carlsson70553942009-08-29 05:16:22 +00004984}
4985
John McCall59660882009-08-29 08:11:13 +00004986// TODO: this could be templated if the various decl types used the
4987// same method name.
4988static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4989 ClassTemplateDecl *Instance) {
4990 Pattern = Pattern->getCanonicalDecl();
4991
4992 do {
4993 Instance = Instance->getCanonicalDecl();
4994 if (Pattern == Instance) return true;
4995 Instance = Instance->getInstantiatedFromMemberTemplate();
4996 } while (Instance);
4997
4998 return false;
4999}
5000
Douglas Gregor14d1bf42009-09-28 06:34:35 +00005001static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
5002 FunctionTemplateDecl *Instance) {
5003 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005004
Douglas Gregor14d1bf42009-09-28 06:34:35 +00005005 do {
5006 Instance = Instance->getCanonicalDecl();
5007 if (Pattern == Instance) return true;
5008 Instance = Instance->getInstantiatedFromMemberTemplate();
5009 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005010
Douglas Gregor14d1bf42009-09-28 06:34:35 +00005011 return false;
5012}
5013
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005014static bool
Douglas Gregor21610382009-10-29 00:04:11 +00005015isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
5016 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005017 Pattern
Douglas Gregor21610382009-10-29 00:04:11 +00005018 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
5019 do {
5020 Instance = cast<ClassTemplatePartialSpecializationDecl>(
5021 Instance->getCanonicalDecl());
5022 if (Pattern == Instance)
5023 return true;
5024 Instance = Instance->getInstantiatedFromMember();
5025 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005026
Douglas Gregor21610382009-10-29 00:04:11 +00005027 return false;
5028}
5029
John McCall59660882009-08-29 08:11:13 +00005030static bool isInstantiationOf(CXXRecordDecl *Pattern,
5031 CXXRecordDecl *Instance) {
5032 Pattern = Pattern->getCanonicalDecl();
5033
5034 do {
5035 Instance = Instance->getCanonicalDecl();
5036 if (Pattern == Instance) return true;
5037 Instance = Instance->getInstantiatedFromMemberClass();
5038 } while (Instance);
5039
5040 return false;
5041}
5042
5043static bool isInstantiationOf(FunctionDecl *Pattern,
5044 FunctionDecl *Instance) {
5045 Pattern = Pattern->getCanonicalDecl();
5046
5047 do {
5048 Instance = Instance->getCanonicalDecl();
5049 if (Pattern == Instance) return true;
5050 Instance = Instance->getInstantiatedFromMemberFunction();
5051 } while (Instance);
5052
5053 return false;
5054}
5055
5056static bool isInstantiationOf(EnumDecl *Pattern,
5057 EnumDecl *Instance) {
5058 Pattern = Pattern->getCanonicalDecl();
5059
5060 do {
5061 Instance = Instance->getCanonicalDecl();
5062 if (Pattern == Instance) return true;
5063 Instance = Instance->getInstantiatedFromMemberEnum();
5064 } while (Instance);
5065
5066 return false;
5067}
5068
John McCallb96ec562009-12-04 22:46:56 +00005069static bool isInstantiationOf(UsingShadowDecl *Pattern,
5070 UsingShadowDecl *Instance,
5071 ASTContext &C) {
Richard Smith32952e12014-10-14 02:00:47 +00005072 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
5073 Pattern);
John McCallb96ec562009-12-04 22:46:56 +00005074}
5075
Richard Smith151c4562016-12-20 21:35:28 +00005076static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
John McCallb96ec562009-12-04 22:46:56 +00005077 ASTContext &C) {
Richard Smith32952e12014-10-14 02:00:47 +00005078 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
John McCallb96ec562009-12-04 22:46:56 +00005079}
5080
Richard Smith151c4562016-12-20 21:35:28 +00005081template<typename T>
5082static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
5083 ASTContext &Ctx) {
5084 // An unresolved using declaration can instantiate to an unresolved using
5085 // declaration, or to a using declaration or a using declaration pack.
5086 //
5087 // Multiple declarations can claim to be instantiated from an unresolved
5088 // using declaration if it's a pack expansion. We want the UsingPackDecl
5089 // in that case, not the individual UsingDecls within the pack.
5090 bool OtherIsPackExpansion;
5091 NamedDecl *OtherFrom;
5092 if (auto *OtherUUD = dyn_cast<T>(Other)) {
5093 OtherIsPackExpansion = OtherUUD->isPackExpansion();
5094 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
5095 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
5096 OtherIsPackExpansion = true;
5097 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
5098 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
5099 OtherIsPackExpansion = false;
5100 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
5101 } else {
5102 return false;
5103 }
5104 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
5105 declaresSameEntity(OtherFrom, Pattern);
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00005106}
5107
John McCall59660882009-08-29 08:11:13 +00005108static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
5109 VarDecl *Instance) {
5110 assert(Instance->isStaticDataMember());
5111
5112 Pattern = Pattern->getCanonicalDecl();
5113
5114 do {
5115 Instance = Instance->getCanonicalDecl();
5116 if (Pattern == Instance) return true;
5117 Instance = Instance->getInstantiatedFromStaticDataMember();
5118 } while (Instance);
5119
5120 return false;
5121}
5122
John McCallb96ec562009-12-04 22:46:56 +00005123// Other is the prospective instantiation
5124// D is the prospective pattern
Douglas Gregor51783312009-05-27 05:35:12 +00005125static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Richard Smith151c4562016-12-20 21:35:28 +00005126 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
5127 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
John McCalle61f2ba2009-11-18 02:36:19 +00005128
Richard Smith151c4562016-12-20 21:35:28 +00005129 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
5130 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
Douglas Gregor51783312009-05-27 05:35:12 +00005131
Richard Smith151c4562016-12-20 21:35:28 +00005132 if (D->getKind() != Other->getKind())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00005133 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005134
Richard Smithd8a9e372016-12-18 21:39:37 +00005135 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00005136 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump11289f42009-09-09 15:08:12 +00005137
Richard Smithd8a9e372016-12-18 21:39:37 +00005138 if (auto *Function = dyn_cast<FunctionDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00005139 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor51783312009-05-27 05:35:12 +00005140
Richard Smithd8a9e372016-12-18 21:39:37 +00005141 if (auto *Enum = dyn_cast<EnumDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00005142 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor51783312009-05-27 05:35:12 +00005143
Richard Smithd8a9e372016-12-18 21:39:37 +00005144 if (auto *Var = dyn_cast<VarDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00005145 if (Var->isStaticDataMember())
5146 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
5147
Richard Smithd8a9e372016-12-18 21:39:37 +00005148 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00005149 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregorf3db0032009-08-28 22:03:51 +00005150
Richard Smithd8a9e372016-12-18 21:39:37 +00005151 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
Douglas Gregor14d1bf42009-09-28 06:34:35 +00005152 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
5153
Richard Smithd8a9e372016-12-18 21:39:37 +00005154 if (auto *PartialSpec =
5155 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
Douglas Gregor21610382009-10-29 00:04:11 +00005156 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
5157 PartialSpec);
5158
Richard Smithd8a9e372016-12-18 21:39:37 +00005159 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
Anders Carlsson5da84842009-09-01 04:26:58 +00005160 if (!Field->getDeclName()) {
5161 // This is an unnamed field.
Richard Smith32952e12014-10-14 02:00:47 +00005162 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
5163 cast<FieldDecl>(D));
Anders Carlsson5da84842009-09-01 04:26:58 +00005164 }
5165 }
Mike Stump11289f42009-09-09 15:08:12 +00005166
Richard Smithd8a9e372016-12-18 21:39:37 +00005167 if (auto *Using = dyn_cast<UsingDecl>(Other))
John McCallb96ec562009-12-04 22:46:56 +00005168 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
5169
Richard Smithd8a9e372016-12-18 21:39:37 +00005170 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
John McCallb96ec562009-12-04 22:46:56 +00005171 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
5172
Richard Smithd8a9e372016-12-18 21:39:37 +00005173 return D->getDeclName() &&
5174 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
Douglas Gregor51783312009-05-27 05:35:12 +00005175}
5176
5177template<typename ForwardIterator>
Mike Stump11289f42009-09-09 15:08:12 +00005178static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor51783312009-05-27 05:35:12 +00005179 NamedDecl *D,
5180 ForwardIterator first,
5181 ForwardIterator last) {
5182 for (; first != last; ++first)
5183 if (isInstantiationOf(Ctx, D, *first))
5184 return cast<NamedDecl>(*first);
5185
Craig Topperc3ec1492014-05-26 06:22:03 +00005186 return nullptr;
Douglas Gregor51783312009-05-27 05:35:12 +00005187}
5188
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005189/// Finds the instantiation of the given declaration context
John McCallaa74a0c2009-08-28 07:59:38 +00005190/// within the current instantiation.
5191///
5192/// \returns NULL if there was an error
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005193DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregor64621e62009-09-16 18:34:49 +00005194 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCallaa74a0c2009-08-28 07:59:38 +00005195 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Richard Smith4f440e32017-06-08 01:08:50 +00005196 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
John McCallaa74a0c2009-08-28 07:59:38 +00005197 return cast_or_null<DeclContext>(ID);
5198 } else return DC;
5199}
5200
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005201/// Find the instantiation of the given declaration within the
Douglas Gregorcd3a0972009-05-27 17:54:46 +00005202/// current instantiation.
Douglas Gregor51783312009-05-27 05:35:12 +00005203///
5204/// This routine is intended to be used when \p D is a declaration
5205/// referenced from within a template, that needs to mapped into the
5206/// corresponding declaration within an instantiation. For example,
5207/// given:
5208///
5209/// \code
5210/// template<typename T>
5211/// struct X {
5212/// enum Kind {
5213/// KnownValue = sizeof(T)
5214/// };
5215///
5216/// bool getKind() const { return KnownValue; }
5217/// };
5218///
5219/// template struct X<int>;
5220/// \endcode
5221///
Erik Pilkington4cae0922019-07-30 23:38:18 +00005222/// In the instantiation of X<int>::getKind(), we need to map the \p
5223/// EnumConstantDecl for \p KnownValue (which refers to
5224/// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue).
5225/// \p FindInstantiatedDecl performs this mapping from within the instantiation
5226/// of X<int>.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005227NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Richard Smith4f440e32017-06-08 01:08:50 +00005228 const MultiLevelTemplateArgumentList &TemplateArgs,
5229 bool FindingInstantiatedContext) {
Douglas Gregor51783312009-05-27 05:35:12 +00005230 DeclContext *ParentDC = D->getDeclContext();
Fangrui Song6907ce22018-07-30 19:24:48 +00005231 // FIXME: Parmeters of pointer to functions (y below) that are themselves
Faisal Vali2cba1332013-10-23 06:44:28 +00005232 // parameters (p below) can have their ParentDC set to the translation-unit
Fangrui Song6907ce22018-07-30 19:24:48 +00005233 // - thus we can not consistently check if the ParentDC of such a parameter
Faisal Vali2cba1332013-10-23 06:44:28 +00005234 // is Dependent or/and a FunctionOrMethod.
Fangrui Song6907ce22018-07-30 19:24:48 +00005235 // For e.g. this code, during Template argument deduction tries to
Faisal Vali2cba1332013-10-23 06:44:28 +00005236 // find an instantiated decl for (T y) when the ParentDC for y is
Fangrui Song6907ce22018-07-30 19:24:48 +00005237 // the translation unit.
5238 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
Aaron Ballman36a53502014-01-16 13:03:14 +00005239 // float baz(float(*)()) { return 0.0; }
Faisal Vali2cba1332013-10-23 06:44:28 +00005240 // Foo(baz);
5241 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
5242 // it gets here, always has a FunctionOrMethod as its ParentDC??
5243 // For now:
5244 // - as long as we have a ParmVarDecl whose parent is non-dependent and
5245 // whose type is not instantiation dependent, do nothing to the decl
5246 // - otherwise find its instantiated decl.
5247 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
5248 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
5249 return D;
Rafael Espindola09b00e32013-10-23 04:12:23 +00005250 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregorb93971082010-02-05 19:54:12 +00005251 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Alexey Bataeve6aa4692018-09-13 16:54:05 +00005252 ((ParentDC->isFunctionOrMethod() ||
Michael Kruse251e1482019-02-01 20:25:04 +00005253 isa<OMPDeclareReductionDecl>(ParentDC) ||
5254 isa<OMPDeclareMapperDecl>(ParentDC)) &&
Alexey Bataeve6aa4692018-09-13 16:54:05 +00005255 ParentDC->isDependentContext()) ||
Douglas Gregora86bc002012-02-16 21:36:18 +00005256 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregorf98d9b62009-05-27 17:07:49 +00005257 // D is a local of some kind. Look into the map of local
5258 // declarations to their instantiations.
Alexey Samsonov2c0aac22014-09-03 18:45:45 +00005259 if (CurrentInstantiationScope) {
5260 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
5261 if (Decl *FD = Found->dyn_cast<Decl *>())
5262 return cast<NamedDecl>(FD);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005263
Alexey Samsonov2c0aac22014-09-03 18:45:45 +00005264 int PackIdx = ArgumentPackSubstitutionIndex;
5265 assert(PackIdx != -1 &&
5266 "found declaration pack but not pack expanding");
5267 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
5268 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
5269 }
Chris Lattnercab02a62011-02-17 20:34:02 +00005270 }
5271
Serge Pavlov7cd8f602013-07-15 06:14:07 +00005272 // If we're performing a partial substitution during template argument
5273 // deduction, we may not have values for template parameters yet. They
5274 // just map to themselves.
5275 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
5276 isa<TemplateTemplateParmDecl>(D))
5277 return D;
5278
Serge Pavlov074a5182013-08-10 12:00:21 +00005279 if (D->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00005280 return nullptr;
Serge Pavlov074a5182013-08-10 12:00:21 +00005281
Serge Pavlove7ad8312015-05-15 10:10:28 +00005282 // Normally this function only searches for already instantiated declaration
5283 // however we have to make an exclusion for local types used before
5284 // definition as in the code:
5285 //
5286 // template<typename T> void f1() {
5287 // void g1(struct x1);
5288 // struct x1 {};
5289 // }
5290 //
5291 // In this case instantiation of the type of 'g1' requires definition of
5292 // 'x1', which is defined later. Error recovery may produce an enum used
5293 // before definition. In these cases we need to instantiate relevant
5294 // declarations here.
5295 bool NeedInstantiate = false;
5296 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
5297 NeedInstantiate = RD->isLocalClass();
5298 else
5299 NeedInstantiate = isa<EnumDecl>(D);
5300 if (NeedInstantiate) {
Serge Pavlov4c511742015-05-04 16:44:39 +00005301 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
5302 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
5303 return cast<TypeDecl>(Inst);
5304 }
5305
Chris Lattnercab02a62011-02-17 20:34:02 +00005306 // If we didn't find the decl, then we must have a label decl that hasn't
5307 // been found yet. Lazily instantiate it and return it now.
5308 assert(isa<LabelDecl>(D));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005309
Chris Lattnercab02a62011-02-17 20:34:02 +00005310 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
5311 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005312
Chris Lattnercab02a62011-02-17 20:34:02 +00005313 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
5314 return cast<LabelDecl>(Inst);
Douglas Gregorf98d9b62009-05-27 17:07:49 +00005315 }
Douglas Gregor51783312009-05-27 05:35:12 +00005316
Douglas Gregor64621e62009-09-16 18:34:49 +00005317 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
5318 if (!Record->isDependentContext())
5319 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005320
Douglas Gregor4109afa2011-11-07 17:43:18 +00005321 // Determine whether this record is the "templated" declaration describing
5322 // a class template or class template partial specialization.
Douglas Gregor64621e62009-09-16 18:34:49 +00005323 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor4109afa2011-11-07 17:43:18 +00005324 if (ClassTemplate)
5325 ClassTemplate = ClassTemplate->getCanonicalDecl();
5326 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5327 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
5328 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
Larisse Voufo39a1e502013-08-06 01:03:05 +00005329
Douglas Gregor4109afa2011-11-07 17:43:18 +00005330 // Walk the current context to find either the record or an instantiation of
5331 // it.
5332 DeclContext *DC = CurContext;
5333 while (!DC->isFileContext()) {
5334 // If we're performing substitution while we're inside the template
5335 // definition, we'll find our own context. We're done.
5336 if (DC->Equals(Record))
5337 return Record;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005338
Douglas Gregor4109afa2011-11-07 17:43:18 +00005339 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
5340 // Check whether we're in the process of instantiating a class template
5341 // specialization of the template we're mapping.
5342 if (ClassTemplateSpecializationDecl *InstSpec
5343 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
5344 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
5345 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
5346 return InstRecord;
5347 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00005348
Douglas Gregor4109afa2011-11-07 17:43:18 +00005349 // Check whether we're in the process of instantiating a member class.
5350 if (isInstantiationOf(Record, InstRecord))
5351 return InstRecord;
Douglas Gregor64621e62009-09-16 18:34:49 +00005352 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00005353
Douglas Gregor4109afa2011-11-07 17:43:18 +00005354 // Move to the outer template scope.
5355 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
5356 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
5357 DC = FD->getLexicalDeclContext();
5358 continue;
5359 }
Richard Smith32918772017-02-14 00:25:28 +00005360 // An implicit deduction guide acts as if it's within the class template
5361 // specialization described by its name and first N template params.
Richard Smithbc491202017-02-17 20:05:37 +00005362 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
5363 if (Guide && Guide->isImplicit()) {
5364 TemplateDecl *TD = Guide->getDeducedTemplate();
Richard Smith0cd9c042017-02-21 08:42:39 +00005365 // Convert the arguments to an "as-written" list.
Richard Smith32918772017-02-14 00:25:28 +00005366 TemplateArgumentListInfo Args(Loc, Loc);
Richard Smith0cd9c042017-02-21 08:42:39 +00005367 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
5368 TD->getTemplateParameters()->size())) {
5369 ArrayRef<TemplateArgument> Unpacked(Arg);
5370 if (Arg.getKind() == TemplateArgument::Pack)
5371 Unpacked = Arg.pack_elements();
5372 for (TemplateArgument UnpackedArg : Unpacked)
5373 Args.addArgument(
5374 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
5375 }
Richard Smith32918772017-02-14 00:25:28 +00005376 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
5377 if (T.isNull())
5378 return nullptr;
Richard Smithe6d4b772017-06-07 02:42:27 +00005379 auto *SubstRecord = T->getAsCXXRecordDecl();
5380 assert(SubstRecord && "class template id not a class type?");
5381 // Check that this template-id names the primary template and not a
5382 // partial or explicit specialization. (In the latter cases, it's
5383 // meaningless to attempt to find an instantiation of D within the
5384 // specialization.)
5385 // FIXME: The standard doesn't say what should happen here.
Richard Smith4f440e32017-06-08 01:08:50 +00005386 if (FindingInstantiatedContext &&
5387 usesPartialOrExplicitSpecialization(
5388 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
Richard Smithe6d4b772017-06-07 02:42:27 +00005389 Diag(Loc, diag::err_specialization_not_primary_template)
5390 << T << (SubstRecord->getTemplateSpecializationKind() ==
5391 TSK_ExplicitSpecialization);
5392 return nullptr;
5393 }
5394 DC = SubstRecord;
Richard Smith32918772017-02-14 00:25:28 +00005395 continue;
5396 }
John McCall59660882009-08-29 08:11:13 +00005397 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00005398
Douglas Gregor4109afa2011-11-07 17:43:18 +00005399 DC = DC->getParent();
John McCall59660882009-08-29 08:11:13 +00005400 }
Douglas Gregord225fa02010-02-05 22:40:03 +00005401
Douglas Gregor64621e62009-09-16 18:34:49 +00005402 // Fall through to deal with other dependent record types (e.g.,
5403 // anonymous unions in class templates).
5404 }
John McCall59660882009-08-29 08:11:13 +00005405
Douglas Gregor64621e62009-09-16 18:34:49 +00005406 if (!ParentDC->isDependentContext())
5407 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005408
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005409 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00005410 if (!ParentDC)
Craig Topperc3ec1492014-05-26 06:22:03 +00005411 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005412
Douglas Gregor51783312009-05-27 05:35:12 +00005413 if (ParentDC != D->getDeclContext()) {
5414 // We performed some kind of instantiation in the parent context,
5415 // so now we need to look into the instantiated parent context to
5416 // find the instantiation of the declaration D.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005417
John McCalle78aac42010-03-10 03:28:59 +00005418 // If our context used to be dependent, we may need to instantiate
5419 // it before performing lookup into that context.
Douglas Gregor528ad932011-03-06 20:12:45 +00005420 bool IsBeingInstantiated = false;
John McCalle78aac42010-03-10 03:28:59 +00005421 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005422 if (!Spec->isDependentContext()) {
5423 QualType T = Context.getTypeDeclType(Spec);
John McCalle78aac42010-03-10 03:28:59 +00005424 const RecordType *Tag = T->getAs<RecordType>();
5425 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregor528ad932011-03-06 20:12:45 +00005426 if (Tag->isBeingDefined())
5427 IsBeingInstantiated = true;
John McCalle78aac42010-03-10 03:28:59 +00005428 if (!Tag->isBeingDefined() &&
5429 RequireCompleteType(Loc, T, diag::err_incomplete_type))
Craig Topperc3ec1492014-05-26 06:22:03 +00005430 return nullptr;
Douglas Gregor25edf432010-11-05 23:22:45 +00005431
5432 ParentDC = Tag->getDecl();
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005433 }
5434 }
5435
Craig Topperc3ec1492014-05-26 06:22:03 +00005436 NamedDecl *Result = nullptr;
Richard Smith151c4562016-12-20 21:35:28 +00005437 // FIXME: If the name is a dependent name, this lookup won't necessarily
5438 // find it. Does that ever matter?
Akira Hatanaka59e3b432017-01-31 19:53:32 +00005439 if (auto Name = D->getDeclName()) {
5440 DeclarationNameInfo NameInfo(Name, D->getLocation());
Erik Pilkington4cae0922019-07-30 23:38:18 +00005441 DeclarationNameInfo NewNameInfo =
5442 SubstDeclarationNameInfo(NameInfo, TemplateArgs);
5443 Name = NewNameInfo.getName();
Akira Hatanaka59e3b432017-01-31 19:53:32 +00005444 if (!Name)
5445 return nullptr;
5446 DeclContext::lookup_result Found = ParentDC->lookup(Name);
Erik Pilkington4cae0922019-07-30 23:38:18 +00005447
5448 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
5449 VarTemplateDecl *Templ = cast_or_null<VarTemplateDecl>(
5450 findInstantiationOf(Context, VTSD->getSpecializedTemplate(),
5451 Found.begin(), Found.end()));
5452 if (!Templ)
5453 return nullptr;
5454 Result = getVarTemplateSpecialization(
5455 Templ, &VTSD->getTemplateArgsInfo(), NewNameInfo, SourceLocation());
5456 } else
5457 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor51783312009-05-27 05:35:12 +00005458 } else {
5459 // Since we don't have a name for the entity we're looking for,
5460 // our only option is to walk through all of the declarations to
5461 // find that name. This will occur in a few cases:
5462 //
5463 // - anonymous struct/union within a template
5464 // - unnamed class/struct/union/enum within a template
5465 //
5466 // FIXME: Find a better way to find these instantiations!
Mike Stump11289f42009-09-09 15:08:12 +00005467 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005468 ParentDC->decls_begin(),
5469 ParentDC->decls_end());
Douglas Gregor51783312009-05-27 05:35:12 +00005470 }
Mike Stump11289f42009-09-09 15:08:12 +00005471
Douglas Gregor528ad932011-03-06 20:12:45 +00005472 if (!Result) {
5473 if (isa<UsingShadowDecl>(D)) {
5474 // UsingShadowDecls can instantiate to nothing because of using hiding.
5475 } else if (Diags.hasErrorOccurred()) {
5476 // We've already complained about something, so most likely this
5477 // declaration failed to instantiate. There's no point in complaining
5478 // further, since this is normal in invalid code.
5479 } else if (IsBeingInstantiated) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005480 // The class in which this member exists is currently being
Douglas Gregor528ad932011-03-06 20:12:45 +00005481 // instantiated, and we haven't gotten around to instantiating this
5482 // member yet. This can happen when the code uses forward declarations
5483 // of member classes, and introduces ordering dependencies via
5484 // template instantiation.
5485 Diag(Loc, diag::err_member_not_yet_instantiated)
5486 << D->getDeclName()
5487 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
5488 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith169f2192012-03-26 20:28:16 +00005489 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
5490 // This enumeration constant was found when the template was defined,
5491 // but can't be found in the instantiation. This can happen if an
5492 // unscoped enumeration member is explicitly specialized.
5493 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
5494 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
5495 TemplateArgs));
5496 assert(Spec->getTemplateSpecializationKind() ==
5497 TSK_ExplicitSpecialization);
5498 Diag(Loc, diag::err_enumerator_does_not_exist)
5499 << D->getDeclName()
5500 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
5501 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
5502 << Context.getTypeDeclType(Spec);
Douglas Gregor528ad932011-03-06 20:12:45 +00005503 } else {
5504 // We should have found something, but didn't.
5505 llvm_unreachable("Unable to find instantiation of declaration!");
5506 }
5507 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005508
Douglas Gregor51783312009-05-27 05:35:12 +00005509 D = Result;
5510 }
5511
Douglas Gregor51783312009-05-27 05:35:12 +00005512 return D;
5513}
Douglas Gregor77b50e12009-06-22 23:06:13 +00005514
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005515/// Performs template instantiation for all implicit template
Douglas Gregor77b50e12009-06-22 23:06:13 +00005516/// instantiations we have seen until this point.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00005517void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00005518 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth54080172010-08-25 08:44:16 +00005519 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00005520 PendingImplicitInstantiation Inst;
5521
5522 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth54080172010-08-25 08:44:16 +00005523 Inst = PendingInstantiations.front();
5524 PendingInstantiations.pop_front();
Douglas Gregor7f792cf2010-01-16 22:29:39 +00005525 } else {
5526 Inst = PendingLocalImplicitInstantiations.front();
5527 PendingLocalImplicitInstantiations.pop_front();
5528 }
Mike Stump11289f42009-09-09 15:08:12 +00005529
Douglas Gregora6ef8f02009-07-24 20:34:43 +00005530 // Instantiate function definitions
5531 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005532 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
5533 TSK_ExplicitInstantiationDefinition;
Erich Keane0fb16482018-08-13 18:33:20 +00005534 if (Function->isMultiVersion()) {
5535 getASTContext().forEachMultiversionedFunctionVersion(
5536 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
5537 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
5538 DefinitionRequired, true);
5539 if (CurFD->isDefined())
5540 CurFD->setInstantiationIsPending(false);
5541 });
5542 } else {
5543 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
5544 DefinitionRequired, true);
5545 if (Function->isDefined())
5546 Function->setInstantiationIsPending(false);
5547 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00005548 continue;
5549 }
Mike Stump11289f42009-09-09 15:08:12 +00005550
Larisse Voufo39a1e502013-08-06 01:03:05 +00005551 // Instantiate variable definitions
Douglas Gregora6ef8f02009-07-24 20:34:43 +00005552 VarDecl *Var = cast<VarDecl>(Inst.first);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005553
5554 assert((Var->isStaticDataMember() ||
5555 isa<VarTemplateSpecializationDecl>(Var)) &&
5556 "Not a static data member, nor a variable template"
5557 " specialization?");
Anders Carlsson62215c42009-09-01 05:12:24 +00005558
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005559 // Don't try to instantiate declarations if the most recent redeclaration
5560 // is invalid.
Douglas Gregorec9fd132012-01-14 16:38:05 +00005561 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005562 continue;
5563
5564 // Check if the most recent declaration has changed the specialization kind
5565 // and removed the need for implicit instantiation.
Richard Smitha6b41d72019-05-03 23:51:38 +00005566 switch (Var->getMostRecentDecl()
5567 ->getTemplateSpecializationKindForInstantiation()) {
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005568 case TSK_Undeclared:
David Blaikie83d382b2011-09-23 05:06:16 +00005569 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005570 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005571 case TSK_ExplicitSpecialization:
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005572 continue; // No longer need to instantiate this type.
5573 case TSK_ExplicitInstantiationDefinition:
5574 // We only need an instantiation if the pending instantiation *is* the
5575 // explicit instantiation.
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005576 if (Var != Var->getMostRecentDecl())
5577 continue;
5578 break;
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005579 case TSK_ImplicitInstantiation:
5580 break;
5581 }
5582
Jordan Rose1e879d82018-03-23 00:07:18 +00005583 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
Larisse Voufo39a1e502013-08-06 01:03:05 +00005584 "instantiating variable definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005585 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
5586 TSK_ExplicitInstantiationDefinition;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005587
5588 // Instantiate static data member definitions or variable template
5589 // specializations.
5590 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00005591 DefinitionRequired, true);
Douglas Gregor77b50e12009-06-22 23:06:13 +00005592 }
5593}
John McCallc62bb642010-03-24 05:22:00 +00005594
5595void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
5596 const MultiLevelTemplateArgumentList &TemplateArgs) {
Aaron Ballmanb105e492014-03-07 14:09:15 +00005597 for (auto DD : Pattern->ddiags()) {
John McCallc62bb642010-03-24 05:22:00 +00005598 switch (DD->getKind()) {
5599 case DependentDiagnostic::Access:
5600 HandleDependentAccessCheck(*DD, TemplateArgs);
5601 break;
5602 }
5603 }
5604}