blob: d75d705f8820956f675dfbd1861366a586318fb3 [file] [log] [blame]
Douglas Gregord7e7a512009-03-17 21:15:40 +00001//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation for declarations.
10//
11//===----------------------------------------------------------------------===/
John McCall83024632010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregor28ad4b52009-05-26 20:50:29 +000013#include "clang/AST/ASTConsumer.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000014#include "clang/AST/ASTContext.h"
Richard Smithd28ac5b2014-03-22 23:33:22 +000015#include "clang/AST/ASTMutationListener.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000016#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
John McCallc62bb642010-03-24 05:22:00 +000018#include "clang/AST/DependentDiagnostic.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000019#include "clang/AST/Expr.h"
Douglas Gregor6131b442009-12-12 18:16:41 +000020#include "clang/AST/ExprCXX.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"
24#include "clang/Sema/PrettyDeclStackTrace.h"
25#include "clang/Sema/Template.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000026
27using namespace clang;
28
David Majnemer192d1792013-11-27 08:20:38 +000029static bool isDeclWithinFunction(const Decl *D) {
30 const DeclContext *DC = D->getDeclContext();
31 if (DC->isFunctionOrMethod())
32 return true;
33
34 if (DC->isRecord())
35 return cast<CXXRecordDecl>(DC)->isLocalClass();
36
37 return false;
38}
39
Richard Smithcc928662014-10-17 20:37:29 +000040template<typename DeclT>
41static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
42 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor14454802011-02-25 02:25:35 +000043 if (!OldDecl->getQualifierLoc())
44 return false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000045
Richard Smithcc928662014-10-17 20:37:29 +000046 assert((NewDecl->getFriendObjectKind() ||
47 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
48 "non-friend with qualified name defined in dependent context");
49 Sema::ContextRAII SavedContext(
50 SemaRef,
51 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
52 ? NewDecl->getLexicalDeclContext()
53 : OldDecl->getLexicalDeclContext()));
54
Douglas Gregor14454802011-02-25 02:25:35 +000055 NestedNameSpecifierLoc NewQualifierLoc
Richard Smithcc928662014-10-17 20:37:29 +000056 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
57 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000058
Douglas Gregor14454802011-02-25 02:25:35 +000059 if (!NewQualifierLoc)
John McCall3e11ebe2010-03-15 10:12:16 +000060 return true;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000061
Douglas Gregor14454802011-02-25 02:25:35 +000062 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +000063 return false;
64}
65
Richard Smithcc928662014-10-17 20:37:29 +000066bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
67 DeclaratorDecl *NewDecl) {
68 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
69}
70
John McCall3e11ebe2010-03-15 10:12:16 +000071bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
72 TagDecl *NewDecl) {
Richard Smithcc928662014-10-17 20:37:29 +000073 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
John McCall3e11ebe2010-03-15 10:12:16 +000074}
75
DeLesley Hutchinsceec3062012-01-20 22:37:06 +000076// Include attribute instantiation code.
77#include "clang/Sema/AttrTemplateInstantiate.inc"
78
Richard Smith44c247f2013-02-22 08:32:16 +000079static void instantiateDependentAlignedAttr(
80 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
81 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
82 if (Aligned->isAlignmentExpr()) {
83 // The alignment expression is a constant expression.
84 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
85 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
86 if (!Result.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +000087 S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
Richard Smith44c247f2013-02-22 08:32:16 +000088 Aligned->getSpellingListIndex(), IsPackExpansion);
89 } else {
90 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
91 TemplateArgs, Aligned->getLocation(),
92 DeclarationName());
93 if (Result)
94 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
95 Aligned->getSpellingListIndex(), IsPackExpansion);
96 }
97}
98
99static void instantiateDependentAlignedAttr(
100 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
101 const AlignedAttr *Aligned, Decl *New) {
102 if (!Aligned->isPackExpansion()) {
103 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
104 return;
105 }
106
107 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
108 if (Aligned->isAlignmentExpr())
109 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
110 Unexpanded);
111 else
112 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
113 Unexpanded);
114 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
115
116 // Determine whether we can expand this attribute pack yet.
117 bool Expand = true, RetainExpansion = false;
118 Optional<unsigned> NumExpansions;
119 // FIXME: Use the actual location of the ellipsis.
120 SourceLocation EllipsisLoc = Aligned->getLocation();
121 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
122 Unexpanded, TemplateArgs, Expand,
123 RetainExpansion, NumExpansions))
124 return;
125
126 if (!Expand) {
127 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
128 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
129 } else {
130 for (unsigned I = 0; I != *NumExpansions; ++I) {
131 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
132 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
133 }
134 }
135}
136
Hal Finkelee90a222014-09-26 05:04:30 +0000137static void instantiateDependentAssumeAlignedAttr(
138 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
139 const AssumeAlignedAttr *Aligned, Decl *New) {
140 // The alignment expression is a constant expression.
141 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
142
143 Expr *E, *OE = nullptr;
144 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
145 if (Result.isInvalid())
146 return;
147 E = Result.getAs<Expr>();
148
149 if (Aligned->getOffset()) {
150 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
151 if (Result.isInvalid())
152 return;
153 OE = Result.getAs<Expr>();
154 }
155
156 S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE,
157 Aligned->getSpellingListIndex());
158}
159
Hal Finkel1b0d24e2014-10-02 21:21:25 +0000160static void instantiateDependentAlignValueAttr(
161 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
162 const AlignValueAttr *Aligned, Decl *New) {
163 // The alignment expression is a constant expression.
164 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
165 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
166 if (!Result.isInvalid())
167 S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
168 Aligned->getSpellingListIndex());
169}
170
George Burgess IV177399e2017-01-09 04:12:14 +0000171static Expr *instantiateDependentFunctionAttrCondition(
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000172 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
George Burgess IV177399e2017-01-09 04:12:14 +0000173 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000174 Expr *Cond = nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000175 {
George Burgess IV177399e2017-01-09 04:12:14 +0000176 Sema::ContextRAII SwitchContext(S, New);
Richard Smith917316f2017-01-07 19:42:26 +0000177 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
George Burgess IV177399e2017-01-09 04:12:14 +0000178 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000179 if (Result.isInvalid())
George Burgess IV177399e2017-01-09 04:12:14 +0000180 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000181 Cond = Result.getAs<Expr>();
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000182 }
George Burgess IV00431952016-11-17 01:33:54 +0000183 if (!Cond->isTypeDependent()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000184 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
185 if (Converted.isInvalid())
George Burgess IV177399e2017-01-09 04:12:14 +0000186 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000187 Cond = Converted.get();
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000188 }
189
190 SmallVector<PartialDiagnosticAt, 8> Diags;
George Burgess IV177399e2017-01-09 04:12:14 +0000191 if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
192 !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
193 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
194 for (const auto &P : Diags)
195 S.Diag(P.first, P.second);
196 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000197 }
George Burgess IV177399e2017-01-09 04:12:14 +0000198 return Cond;
199}
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000200
George Burgess IV177399e2017-01-09 04:12:14 +0000201static void instantiateDependentEnableIfAttr(
202 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
203 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
204 Expr *Cond = instantiateDependentFunctionAttrCondition(
205 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
206
207 if (Cond)
208 New->addAttr(new (S.getASTContext()) EnableIfAttr(
209 EIA->getLocation(), S.getASTContext(), Cond, EIA->getMessage(),
210 EIA->getSpellingListIndex()));
211}
212
213static void instantiateDependentDiagnoseIfAttr(
214 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
215 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
216 Expr *Cond = instantiateDependentFunctionAttrCondition(
217 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
218
219 if (Cond)
220 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
221 DIA->getLocation(), S.getASTContext(), Cond, DIA->getMessage(),
222 DIA->getDiagnosticType(), DIA->getArgDependent(), New,
223 DIA->getSpellingListIndex()));
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000224}
225
Artem Belevich7093e402015-04-21 22:55:54 +0000226// Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
227// template A as the base and arguments from TemplateArgs.
228static void instantiateDependentCUDALaunchBoundsAttr(
229 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
230 const CUDALaunchBoundsAttr &Attr, Decl *New) {
231 // The alignment expression is a constant expression.
232 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
233
234 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
235 if (Result.isInvalid())
236 return;
237 Expr *MaxThreads = Result.getAs<Expr>();
238
239 Expr *MinBlocks = nullptr;
240 if (Attr.getMinBlocks()) {
241 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
242 if (Result.isInvalid())
243 return;
244 MinBlocks = Result.getAs<Expr>();
245 }
246
247 S.AddLaunchBoundsAttr(Attr.getLocation(), New, MaxThreads, MinBlocks,
248 Attr.getSpellingListIndex());
249}
250
Denis Zobnind9e2dcd2016-02-02 13:50:39 +0000251static void
252instantiateDependentModeAttr(Sema &S,
253 const MultiLevelTemplateArgumentList &TemplateArgs,
254 const ModeAttr &Attr, Decl *New) {
255 S.AddModeAttr(Attr.getRange(), New, Attr.getMode(),
256 Attr.getSpellingListIndex(), /*InInstantiation=*/true);
257}
258
Alexey Bataev2af33e32016-04-07 12:45:37 +0000259/// Instantiation of 'declare simd' attribute and its arguments.
260static void instantiateOMPDeclareSimdDeclAttr(
261 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
262 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +0000263 // Allow 'this' in clauses with varlists.
264 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
265 New = FTD->getTemplatedDecl();
266 auto *FD = cast<FunctionDecl>(New);
267 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
Alexey Bataevecba70f2016-04-12 11:02:11 +0000268 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
269 SmallVector<unsigned, 4> LinModifiers;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +0000270
271 auto &&Subst = [&](Expr *E) -> ExprResult {
272 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
273 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
274 Sema::ContextRAII SavedContext(S, FD);
275 LocalInstantiationScope Local(S);
276 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
277 Local.InstantiatedLocal(
278 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
279 return S.SubstExpr(E, TemplateArgs);
280 }
281 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, /*TypeQuals=*/0,
282 FD->isCXXInstanceMember());
283 return S.SubstExpr(E, TemplateArgs);
284 };
285
Alexey Bataevecba70f2016-04-12 11:02:11 +0000286 ExprResult Simdlen;
287 if (auto *E = Attr.getSimdlen())
288 Simdlen = Subst(E);
289
Alexey Bataeve48a5fc2016-04-12 05:28:34 +0000290 if (Attr.uniforms_size() > 0) {
291 for(auto *E : Attr.uniforms()) {
292 ExprResult Inst = Subst(E);
293 if (Inst.isInvalid())
294 continue;
295 Uniforms.push_back(Inst.get());
296 }
Alexey Bataev2af33e32016-04-07 12:45:37 +0000297 }
298
Alexey Bataevd93d3762016-04-12 09:35:56 +0000299 auto AI = Attr.alignments_begin();
300 for (auto *E : Attr.aligneds()) {
301 ExprResult Inst = Subst(E);
302 if (Inst.isInvalid())
303 continue;
304 Aligneds.push_back(Inst.get());
305 Inst = ExprEmpty();
306 if (*AI)
307 Inst = S.SubstExpr(*AI, TemplateArgs);
308 Alignments.push_back(Inst.get());
309 ++AI;
310 }
Alexey Bataevecba70f2016-04-12 11:02:11 +0000311
312 auto SI = Attr.steps_begin();
313 for (auto *E : Attr.linears()) {
314 ExprResult Inst = Subst(E);
315 if (Inst.isInvalid())
316 continue;
317 Linears.push_back(Inst.get());
318 Inst = ExprEmpty();
319 if (*SI)
320 Inst = S.SubstExpr(*SI, TemplateArgs);
321 Steps.push_back(Inst.get());
322 ++SI;
323 }
324 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
Alexey Bataevd93d3762016-04-12 09:35:56 +0000325 (void)S.ActOnOpenMPDeclareSimdDirective(
326 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
Alexey Bataevecba70f2016-04-12 11:02:11 +0000327 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
328 Attr.getRange());
Alexey Bataev2af33e32016-04-07 12:45:37 +0000329}
330
Erich Keanea32910d2017-03-23 18:51:54 +0000331static bool DeclContainsAttr(const Decl *D, const Attr *NewAttr) {
332 if (!D->hasAttrs() || NewAttr->duplicatesAllowed())
333 return false;
334 return llvm::find_if(D->getAttrs(), [NewAttr](const Attr *Attr) {
335 return Attr->getKind() == NewAttr->getKind();
336 }) != D->getAttrs().end();
337}
338
339void Sema::InstantiateAttrsForDecl(
340 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
341 Decl *New, LateInstantiatedAttrVec *LateAttrs,
342 LocalInstantiationScope *OuterMostScope) {
343 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
344 for (const auto *TmplAttr : Tmpl->attrs()) {
345 // FIXME: If any of the special case versions from InstantiateAttrs become
346 // applicable to template declaration, we'll need to add them here.
347 CXXThisScopeRAII ThisScope(
348 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
349 /*TypeQuals*/ 0, ND->isCXXInstanceMember());
350
351 Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
352 TmplAttr, Context, *this, TemplateArgs);
353 if (NewAttr && !DeclContainsAttr(New, NewAttr))
354 New->addAttr(NewAttr);
355 }
356 }
357}
358
John McCall6602bb12010-08-01 02:01:53 +0000359void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000360 const Decl *Tmpl, Decl *New,
361 LateInstantiatedAttrVec *LateAttrs,
362 LocalInstantiationScope *OuterMostScope) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000363 for (const auto *TmplAttr : Tmpl->attrs()) {
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000364 // FIXME: This should be generalized to more than just the AlignedAttr.
Richard Smith44c247f2013-02-22 08:32:16 +0000365 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
366 if (Aligned && Aligned->isAlignmentDependent()) {
367 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
368 continue;
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000369 }
370
Hal Finkelee90a222014-09-26 05:04:30 +0000371 const AssumeAlignedAttr *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr);
372 if (AssumeAligned) {
373 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
374 continue;
375 }
376
Hal Finkel1b0d24e2014-10-02 21:21:25 +0000377 const AlignValueAttr *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr);
378 if (AlignValue) {
379 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
380 continue;
381 }
382
George Burgess IV00431952016-11-17 01:33:54 +0000383 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000384 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
George Burgess IV177399e2017-01-09 04:12:14 +0000385 cast<FunctionDecl>(New));
386 continue;
387 }
388
389 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
390 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
391 cast<FunctionDecl>(New));
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000392 continue;
393 }
394
Artem Belevich7093e402015-04-21 22:55:54 +0000395 if (const CUDALaunchBoundsAttr *CUDALaunchBounds =
396 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
397 instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
398 *CUDALaunchBounds, New);
399 continue;
400 }
401
Denis Zobnind9e2dcd2016-02-02 13:50:39 +0000402 if (const ModeAttr *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
403 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
404 continue;
405 }
406
Alexey Bataev2af33e32016-04-07 12:45:37 +0000407 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
408 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
409 continue;
410 }
411
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +0000412 // Existing DLL attribute on the instantiation takes precedence.
413 if (TmplAttr->getKind() == attr::DLLExport ||
414 TmplAttr->getKind() == attr::DLLImport) {
415 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
416 continue;
417 }
418 }
419
John McCall477f2bb2016-03-03 06:39:32 +0000420 if (auto ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
421 AddParameterABIAttr(ABIAttr->getRange(), New, ABIAttr->getABI(),
422 ABIAttr->getSpellingListIndex());
423 continue;
424 }
425
John McCall3b5a8f52016-03-03 00:10:03 +0000426 if (isa<NSConsumedAttr>(TmplAttr) || isa<CFConsumedAttr>(TmplAttr)) {
427 AddNSConsumedAttr(TmplAttr->getRange(), New,
428 TmplAttr->getSpellingListIndex(),
429 isa<NSConsumedAttr>(TmplAttr),
430 /*template instantiation*/ true);
431 continue;
432 }
433
Richard Smith44c247f2013-02-22 08:32:16 +0000434 assert(!TmplAttr->isPackExpansion());
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000435 if (TmplAttr->isLateParsed() && LateAttrs) {
436 // Late parsed attributes must be instantiated and attached after the
437 // enclosing class has been instantiated. See Sema::InstantiateClass.
Craig Topperc3ec1492014-05-26 06:22:03 +0000438 LocalInstantiationScope *Saved = nullptr;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000439 if (CurrentInstantiationScope)
440 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
441 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
442 } else {
Richard Smithc3d2ebb2013-06-07 02:33:37 +0000443 // Allow 'this' within late-parsed attributes.
444 NamedDecl *ND = dyn_cast<NamedDecl>(New);
445 CXXRecordDecl *ThisContext =
446 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
447 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
448 ND && ND->isCXXInstanceMember());
449
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +0000450 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
451 *this, TemplateArgs);
Erich Keanea32910d2017-03-23 18:51:54 +0000452
453 if (NewAttr && !DeclContainsAttr(New, NewAttr))
Rafael Espindola7f90b7d2012-05-15 14:09:55 +0000454 New->addAttr(NewAttr);
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000455 }
Anders Carlsson3d709752009-11-07 06:07:58 +0000456 }
457}
458
Richard Smith41c79d92014-10-11 00:37:16 +0000459/// Get the previous declaration of a declaration for the purposes of template
460/// instantiation. If this finds a previous declaration, then the previous
461/// declaration of the instantiation of D should be an instantiation of the
462/// result of this function.
463template<typename DeclT>
464static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
465 DeclT *Result = D->getPreviousDecl();
466
467 // If the declaration is within a class, and the previous declaration was
468 // merged from a different definition of that class, then we don't have a
469 // previous declaration for the purpose of template instantiation.
470 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
471 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
472 return nullptr;
473
474 return Result;
475}
476
Douglas Gregor8a655532009-03-25 15:45:12 +0000477Decl *
478TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000479 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000480}
481
482Decl *
Nico Weber66220292016-03-02 17:28:48 +0000483TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
484 llvm_unreachable("pragma comment cannot be instantiated");
485}
486
Nico Webercbbaeb12016-03-02 19:28:54 +0000487Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
488 PragmaDetectMismatchDecl *D) {
489 llvm_unreachable("pragma comment cannot be instantiated");
490}
491
Nico Weber66220292016-03-02 17:28:48 +0000492Decl *
Richard Smithf19e1272015-03-07 00:04:49 +0000493TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
494 llvm_unreachable("extern \"C\" context cannot be instantiated");
495}
496
497Decl *
Chris Lattnercab02a62011-02-17 20:34:02 +0000498TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
499 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
500 D->getIdentifier());
501 Owner->addDecl(Inst);
502 return Inst;
503}
504
505Decl *
Douglas Gregor8a655532009-03-25 15:45:12 +0000506TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000507 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000508}
509
John McCalld8d0d432010-02-16 06:53:13 +0000510Decl *
511TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
512 NamespaceAliasDecl *Inst
513 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
514 D->getNamespaceLoc(),
515 D->getAliasLoc(),
Douglas Gregorc05ba2e2011-02-25 17:08:07 +0000516 D->getIdentifier(),
517 D->getQualifierLoc(),
John McCalld8d0d432010-02-16 06:53:13 +0000518 D->getTargetNameLoc(),
519 D->getNamespace());
520 Owner->addDecl(Inst);
521 return Inst;
522}
523
Richard Smith3f1b5d02011-05-05 21:57:07 +0000524Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
525 bool IsTypeAlias) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000526 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000527 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000528 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000529 DI->getType()->isVariablyModifiedType()) {
John McCall703a3f82009-10-24 08:00:42 +0000530 DI = SemaRef.SubstType(DI, TemplateArgs,
531 D->getLocation(), D->getDeclName());
532 if (!DI) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000533 Invalid = true;
John McCallbcd03502009-12-07 02:54:59 +0000534 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000535 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000536 } else {
537 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000538 }
Mike Stump11289f42009-09-09 15:08:12 +0000539
Richard Smith2ddcbab2012-10-23 00:32:41 +0000540 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
541 // libstdc++ relies upon this bug in its implementation of common_type.
542 // If we happen to be processing that implementation, fake up the g++ ?:
543 // semantics. See LWG issue 2141 for more information on the bug.
544 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
545 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
546 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
547 DT->isReferenceType() &&
548 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
549 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
550 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
551 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
552 // Fold it to the (non-reference) type which g++ would have produced.
553 DI = SemaRef.Context.getTrivialTypeSourceInfo(
554 DI->getType().getNonReferenceType());
555
Douglas Gregord7e7a512009-03-17 21:15:40 +0000556 // Create the new typedef
Richard Smithdda56e42011-04-15 14:24:37 +0000557 TypedefNameDecl *Typedef;
558 if (IsTypeAlias)
559 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
560 D->getLocation(), D->getIdentifier(), DI);
561 else
562 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
563 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000564 if (Invalid)
565 Typedef->setInvalidDecl();
566
John McCall04fcd0d2011-02-01 08:20:08 +0000567 // If the old typedef was the name for linkage purposes of an anonymous
568 // tag decl, re-establish that relationship for the new typedef.
569 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
570 TagDecl *oldTag = oldTagType->getDecl();
Douglas Gregord831d952013-03-08 22:15:15 +0000571 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
John McCall04fcd0d2011-02-01 08:20:08 +0000572 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
John McCall5ea95772013-03-09 00:54:27 +0000573 assert(!newTag->hasNameForLinkage());
Richard Smithdda56e42011-04-15 14:24:37 +0000574 newTag->setTypedefNameForAnonDecl(Typedef);
John McCall04fcd0d2011-02-01 08:20:08 +0000575 }
Douglas Gregor83eb5032010-04-23 16:25:07 +0000576 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000577
Richard Smith41c79d92014-10-11 00:37:16 +0000578 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000579 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
580 TemplateArgs);
Douglas Gregor55e6b312011-03-04 19:46:35 +0000581 if (!InstPrev)
Craig Topperc3ec1492014-05-26 06:22:03 +0000582 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000583
Rafael Espindolacde2c8f2011-12-26 22:42:47 +0000584 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
585
586 // If the typedef types are not identical, reject them.
587 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
588
Rafael Espindola8db352d2013-10-17 15:37:26 +0000589 Typedef->setPreviousDecl(InstPrevTypedef);
John McCall91f1a022009-12-30 00:31:22 +0000590 }
591
John McCall6602bb12010-08-01 02:01:53 +0000592 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregor83eb5032010-04-23 16:25:07 +0000593
John McCall401982f2010-01-20 21:53:11 +0000594 Typedef->setAccess(D->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +0000595
Douglas Gregord7e7a512009-03-17 21:15:40 +0000596 return Typedef;
597}
598
Richard Smithdda56e42011-04-15 14:24:37 +0000599Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000600 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
Richard Smith41c79d92014-10-11 00:37:16 +0000601 if (Typedef)
602 Owner->addDecl(Typedef);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000603 return Typedef;
Richard Smithdda56e42011-04-15 14:24:37 +0000604}
605
606Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000607 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
Richard Smith41c79d92014-10-11 00:37:16 +0000608 if (Typedef)
609 Owner->addDecl(Typedef);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000610 return Typedef;
611}
612
613Decl *
614TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
615 // Create a local instantiation scope for this type alias template, which
616 // will contain the instantiations of the template parameters.
617 LocalInstantiationScope Scope(SemaRef);
618
619 TemplateParameterList *TempParams = D->getTemplateParameters();
620 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
621 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +0000622 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000623
624 TypeAliasDecl *Pattern = D->getTemplatedDecl();
625
Craig Topperc3ec1492014-05-26 06:22:03 +0000626 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
Richard Smith41c79d92014-10-11 00:37:16 +0000627 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000628 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000629 if (!Found.empty()) {
630 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
Richard Smith3f1b5d02011-05-05 21:57:07 +0000631 }
632 }
633
634 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
635 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
636 if (!AliasInst)
Craig Topperc3ec1492014-05-26 06:22:03 +0000637 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000638
639 TypeAliasTemplateDecl *Inst
640 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
641 D->getDeclName(), InstParams, AliasInst);
Richard Smith43ccec8e2014-08-26 03:52:16 +0000642 AliasInst->setDescribedAliasTemplate(Inst);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000643 if (PrevAliasTemplate)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000644 Inst->setPreviousDecl(PrevAliasTemplate);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000645
646 Inst->setAccess(D->getAccess());
647
648 if (!PrevAliasTemplate)
649 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000650
Richard Smith3f1b5d02011-05-05 21:57:07 +0000651 Owner->addDecl(Inst);
652
653 return Inst;
Richard Smithdda56e42011-04-15 14:24:37 +0000654}
655
Richard Smithbdb84f32016-07-22 23:36:59 +0000656Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
Richard Smith3997b1b2016-08-12 01:55:21 +0000657 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
658 D->getIdentifier());
659 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
660 return NewBD;
Richard Smithbdb84f32016-07-22 23:36:59 +0000661}
662
663Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
Richard Smith3997b1b2016-08-12 01:55:21 +0000664 // Transform the bindings first.
665 SmallVector<BindingDecl*, 16> NewBindings;
666 for (auto *OldBD : D->bindings())
667 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
668 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
669
670 auto *NewDD = cast_or_null<DecompositionDecl>(
671 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
672
673 if (!NewDD || NewDD->isInvalidDecl())
674 for (auto *NewBD : NewBindings)
675 NewBD->setInvalidDecl();
676
677 return NewDD;
Richard Smithbdb84f32016-07-22 23:36:59 +0000678}
679
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000680Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000681 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000682}
683
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000684Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
Richard Smith3997b1b2016-08-12 01:55:21 +0000685 bool InstantiatingVarTemplate,
686 ArrayRef<BindingDecl*> *Bindings) {
Larisse Voufo39a1e502013-08-06 01:03:05 +0000687
John McCall76d824f2009-08-25 22:02:44 +0000688 // Do substitution on the type of the declaration
Richard Smithee579842017-01-30 20:39:26 +0000689 TypeSourceInfo *DI = SemaRef.SubstType(
690 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
691 D->getDeclName(), /*AllowDeducedTST*/true);
John McCallf1abcdc2009-10-21 02:39:02 +0000692 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +0000693 return nullptr;
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000694
Douglas Gregor61623342010-09-12 07:37:24 +0000695 if (DI->getType()->isFunctionType()) {
696 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
697 << D->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +0000698 return nullptr;
Douglas Gregor61623342010-09-12 07:37:24 +0000699 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000700
Richard Smith541b38b2013-09-20 01:15:31 +0000701 DeclContext *DC = Owner;
702 if (D->isLocalExternDecl())
703 SemaRef.adjustContextForLocalExternDecl(DC);
704
Larisse Voufo39a1e502013-08-06 01:03:05 +0000705 // Build the instantiated declaration.
Richard Smith3997b1b2016-08-12 01:55:21 +0000706 VarDecl *Var;
707 if (Bindings)
708 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
709 D->getLocation(), DI->getType(), DI,
710 D->getStorageClass(), *Bindings);
711 else
712 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
713 D->getLocation(), D->getIdentifier(), DI->getType(),
714 DI, D->getStorageClass());
Mike Stump11289f42009-09-09 15:08:12 +0000715
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000716 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000717 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000718 SemaRef.inferObjCARCLifetime(Var))
719 Var->setInvalidDecl();
720
Larisse Voufo39a1e502013-08-06 01:03:05 +0000721 // Substitute the nested name specifier, if any.
722 if (SubstQualifier(D, Var))
Craig Topperc3ec1492014-05-26 06:22:03 +0000723 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000724
Richard Smith541b38b2013-09-20 01:15:31 +0000725 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000726 StartingScope, InstantiatingVarTemplate);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +0000727
728 if (D->isNRVOVariable()) {
729 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
730 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, false))
731 Var->setNRVOVariable(true);
732 }
733
Alexander Kornienko83a4e182014-05-27 21:29:22 +0000734 Var->setImplicit(D->isImplicit());
735
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000736 return Var;
737}
738
Abramo Bagnarad7340582010-06-05 05:09:32 +0000739Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
740 AccessSpecDecl* AD
741 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
742 D->getAccessSpecifierLoc(), D->getColonLoc());
743 Owner->addHiddenDecl(AD);
744 return AD;
745}
746
Douglas Gregord7e7a512009-03-17 21:15:40 +0000747Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
748 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000749 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000750 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000751 DI->getType()->isVariablyModifiedType()) {
John McCall90459c52009-10-22 23:33:21 +0000752 DI = SemaRef.SubstType(DI, TemplateArgs,
753 D->getLocation(), D->getDeclName());
754 if (!DI) {
John McCallbcd03502009-12-07 02:54:59 +0000755 DI = D->getTypeSourceInfo();
John McCall90459c52009-10-22 23:33:21 +0000756 Invalid = true;
757 } else if (DI->getType()->isFunctionType()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000758 // C++ [temp.arg.type]p3:
759 // If a declaration acquires a function type through a type
760 // dependent on a template-parameter and this causes a
761 // declaration that does not use the syntactic form of a
762 // function declarator to have function type, the program is
763 // ill-formed.
764 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall90459c52009-10-22 23:33:21 +0000765 << DI->getType();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000766 Invalid = true;
767 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000768 } else {
769 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000770 }
771
772 Expr *BitWidth = D->getBitWidth();
773 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +0000774 BitWidth = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000775 else if (BitWidth) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000776 // The bit-width expression is a constant expression.
777 EnterExpressionEvaluationContext Unevaluated(SemaRef,
778 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000779
John McCalldadc5752010-08-24 06:29:42 +0000780 ExprResult InstantiatedBitWidth
John McCall76d824f2009-08-25 22:02:44 +0000781 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000782 if (InstantiatedBitWidth.isInvalid()) {
783 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +0000784 BitWidth = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000785 } else
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000786 BitWidth = InstantiatedBitWidth.getAs<Expr>();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000787 }
788
John McCall90459c52009-10-22 23:33:21 +0000789 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
790 DI->getType(), DI,
Mike Stump11289f42009-09-09 15:08:12 +0000791 cast<RecordDecl>(Owner),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000792 D->getLocation(),
793 D->isMutable(),
794 BitWidth,
Richard Smith2b013182012-06-10 03:12:00 +0000795 D->getInClassInitStyle(),
Richard Smith47ad0172012-05-23 04:22:22 +0000796 D->getInnerLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000797 D->getAccess(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000798 nullptr);
Douglas Gregor3c74d412009-10-14 20:14:33 +0000799 if (!Field) {
800 cast<Decl>(Owner)->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +0000801 return nullptr;
Douglas Gregor3c74d412009-10-14 20:14:33 +0000802 }
Mike Stump11289f42009-09-09 15:08:12 +0000803
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000804 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000805
Richard Smith848e1f12013-02-01 08:12:08 +0000806 if (Field->hasAttrs())
807 SemaRef.CheckAlignasUnderalignment(Field);
808
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000809 if (Invalid)
810 Field->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000811
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000812 if (!Field->getDeclName()) {
813 // Keep track of where this decl came from.
814 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000815 }
Douglas Gregor04163182010-05-21 00:31:19 +0000816 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
817 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl50c68252010-08-31 00:36:30 +0000818 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor04163182010-05-21 00:31:19 +0000819 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000820 }
Mike Stump11289f42009-09-09 15:08:12 +0000821
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000822 Field->setImplicit(D->isImplicit());
John McCall401982f2010-01-20 21:53:11 +0000823 Field->setAccess(D->getAccess());
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000824 Owner->addDecl(Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000825
826 return Field;
827}
828
John McCall5e77d762013-04-16 07:28:30 +0000829Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
830 bool Invalid = false;
831 TypeSourceInfo *DI = D->getTypeSourceInfo();
832
833 if (DI->getType()->isVariablyModifiedType()) {
834 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
Aaron Ballman1bda4592014-01-03 01:09:27 +0000835 << D;
John McCall5e77d762013-04-16 07:28:30 +0000836 Invalid = true;
837 } else if (DI->getType()->isInstantiationDependentType()) {
838 DI = SemaRef.SubstType(DI, TemplateArgs,
839 D->getLocation(), D->getDeclName());
840 if (!DI) {
841 DI = D->getTypeSourceInfo();
842 Invalid = true;
843 } else if (DI->getType()->isFunctionType()) {
844 // C++ [temp.arg.type]p3:
845 // If a declaration acquires a function type through a type
846 // dependent on a template-parameter and this causes a
847 // declaration that does not use the syntactic form of a
848 // function declarator to have function type, the program is
849 // ill-formed.
850 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
851 << DI->getType();
852 Invalid = true;
853 }
854 } else {
855 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
856 }
857
Richard Smithf7981722013-11-22 09:01:48 +0000858 MSPropertyDecl *Property = MSPropertyDecl::Create(
859 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
860 DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
John McCall5e77d762013-04-16 07:28:30 +0000861
862 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
863 StartingScope);
864
865 if (Invalid)
866 Property->setInvalidDecl();
867
868 Property->setAccess(D->getAccess());
869 Owner->addDecl(Property);
870
871 return Property;
872}
873
Francois Pichet783dd6e2010-11-21 06:08:52 +0000874Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
875 NamedDecl **NamedChain =
876 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
877
878 int i = 0;
Aaron Ballman29c94602014-03-07 18:36:15 +0000879 for (auto *PI : D->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +0000880 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
Douglas Gregor55e6b312011-03-04 19:46:35 +0000881 TemplateArgs);
882 if (!Next)
Craig Topperc3ec1492014-05-26 06:22:03 +0000883 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000884
Douglas Gregor55e6b312011-03-04 19:46:35 +0000885 NamedChain[i++] = Next;
886 }
Francois Pichet783dd6e2010-11-21 06:08:52 +0000887
Francois Pichetdbafc192010-12-09 10:07:54 +0000888 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Aaron Ballman260995b2014-10-15 16:58:18 +0000889 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
890 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
David Majnemer59f77922016-06-24 04:05:48 +0000891 {NamedChain, D->getChainingSize()});
Francois Pichet783dd6e2010-11-21 06:08:52 +0000892
NAKAMURA Takumi729be142014-10-27 12:37:26 +0000893 for (const auto *Attr : D->attrs())
894 IndirectField->addAttr(Attr->clone(SemaRef.Context));
Francois Pichet783dd6e2010-11-21 06:08:52 +0000895
896 IndirectField->setImplicit(D->isImplicit());
897 IndirectField->setAccess(D->getAccess());
898 Owner->addDecl(IndirectField);
899 return IndirectField;
900}
901
John McCallaa74a0c2009-08-28 07:59:38 +0000902Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCallaa74a0c2009-08-28 07:59:38 +0000903 // Handle friend type expressions by simply substituting template
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000904 // parameters into the pattern type and checking the result.
John McCall15ad0962010-03-25 18:04:51 +0000905 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth08836322011-05-01 00:51:33 +0000906 TypeSourceInfo *InstTy;
907 // If this is an unsupported friend, don't bother substituting template
908 // arguments into it. The actual type referred to won't be used by any
909 // parts of Clang, and may not be valid for instantiating. Just use the
910 // same info for the instantiated friend.
911 if (D->isUnsupportedFriend()) {
912 InstTy = Ty;
913 } else {
914 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
915 D->getLocation(), DeclarationName());
916 }
917 if (!InstTy)
Craig Topperc3ec1492014-05-26 06:22:03 +0000918 return nullptr;
John McCallaa74a0c2009-08-28 07:59:38 +0000919
Richard Smitha31a89a2012-09-20 01:31:00 +0000920 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
Abramo Bagnara254b6302011-10-29 20:52:52 +0000921 D->getFriendLoc(), InstTy);
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000922 if (!FD)
Craig Topperc3ec1492014-05-26 06:22:03 +0000923 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000924
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000925 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000926 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000927 Owner->addDecl(FD);
928 return FD;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000929 }
930
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000931 NamedDecl *ND = D->getFriendDecl();
932 assert(ND && "friend decl must be a decl or a type!");
933
John McCallb9c78482010-04-08 09:05:18 +0000934 // All of the Visit implementations for the various potential friend
935 // declarations have to be carefully written to work for friend
936 // objects, with the most important detail being that the target
937 // decl should almost certainly not be placed in Owner.
938 Decl *NewND = Visit(ND);
Craig Topperc3ec1492014-05-26 06:22:03 +0000939 if (!NewND) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000940
John McCallaa74a0c2009-08-28 07:59:38 +0000941 FriendDecl *FD =
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000942 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000943 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall75c03bb2009-08-29 03:50:18 +0000944 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000945 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCallaa74a0c2009-08-28 07:59:38 +0000946 Owner->addDecl(FD);
947 return FD;
John McCall58de3582009-08-14 02:03:10 +0000948}
949
Douglas Gregord7e7a512009-03-17 21:15:40 +0000950Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
951 Expr *AssertExpr = D->getAssertExpr();
Mike Stump11289f42009-09-09 15:08:12 +0000952
Richard Smith764d2fe2011-12-20 02:08:33 +0000953 // The expression in a static assertion is a constant expression.
954 EnterExpressionEvaluationContext Unevaluated(SemaRef,
955 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000956
John McCalldadc5752010-08-24 06:29:42 +0000957 ExprResult InstantiatedAssertExpr
John McCall76d824f2009-08-25 22:02:44 +0000958 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000959 if (InstantiatedAssertExpr.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +0000960 return nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000961
Richard Smithded9c2e2012-07-11 22:37:56 +0000962 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCallb268a282010-08-23 23:25:46 +0000963 InstantiatedAssertExpr.get(),
Richard Smithded9c2e2012-07-11 22:37:56 +0000964 D->getMessage(),
965 D->getRParenLoc(),
966 D->isFailed());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000967}
968
969Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000970 EnumDecl *PrevDecl = nullptr;
Richard Smith41c79d92014-10-11 00:37:16 +0000971 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
Richard Smith2e6610a2012-03-26 04:58:10 +0000972 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Richard Smith41c79d92014-10-11 00:37:16 +0000973 PatternPrev,
Richard Smith2e6610a2012-03-26 04:58:10 +0000974 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +0000975 if (!Prev) return nullptr;
Richard Smith2e6610a2012-03-26 04:58:10 +0000976 PrevDecl = cast<EnumDecl>(Prev);
977 }
978
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000979 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000980 D->getLocation(), D->getIdentifier(),
Richard Smith2e6610a2012-03-26 04:58:10 +0000981 PrevDecl, D->isScoped(),
Abramo Bagnara0e05e242010-12-03 18:54:17 +0000982 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor0bf31402010-10-08 23:50:27 +0000983 if (D->isFixed()) {
Richard Smith4b38ded2012-03-14 23:13:10 +0000984 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000985 // If we have type source information for the underlying type, it means it
986 // has been explicitly set by the user. Perform substitution on it before
987 // moving on.
988 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smith4b38ded2012-03-14 23:13:10 +0000989 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
990 DeclarationName());
991 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor0bf31402010-10-08 23:50:27 +0000992 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smith4b38ded2012-03-14 23:13:10 +0000993 else
994 Enum->setIntegerTypeSourceInfo(NewTI);
995 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000996 assert(!D->getIntegerType()->isDependentType()
997 && "Dependent type without type source info");
998 Enum->setIntegerType(D->getIntegerType());
999 }
1000 }
1001
John McCall811a0f52010-10-22 23:36:17 +00001002 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1003
Richard Smith4b38ded2012-03-14 23:13:10 +00001004 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor6c2adff2009-03-25 22:00:53 +00001005 Enum->setAccess(D->getAccess());
David Majnemerdbc0c8f2013-12-04 09:01:55 +00001006 // Forward the mangling number from the template to the instantiated decl.
1007 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
David Majnemer00350522015-08-31 18:48:39 +00001008 // See if the old tag was defined along with a declarator.
1009 // If it did, mark the new tag as being associated with that declarator.
1010 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1011 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1012 // See if the old tag was defined along with a typedef.
1013 // If it did, mark the new tag as being associated with that typedef.
1014 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1015 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
Craig Topperc3ec1492014-05-26 06:22:03 +00001016 if (SubstQualifier(D, Enum)) return nullptr;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001017 Owner->addDecl(Enum);
Richard Smith4b38ded2012-03-14 23:13:10 +00001018
Richard Smith258a7442012-03-26 04:08:46 +00001019 EnumDecl *Def = D->getDefinition();
1020 if (Def && Def != D) {
1021 // If this is an out-of-line definition of an enum member template, check
1022 // that the underlying types match in the instantiation of both
1023 // declarations.
1024 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1025 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1026 QualType DefnUnderlying =
1027 SemaRef.SubstType(TI->getType(), TemplateArgs,
1028 UnderlyingLoc, DeclarationName());
1029 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
David Majnemerdc9be212015-10-08 10:04:46 +00001030 DefnUnderlying,
1031 /*EnumUnderlyingIsImplicit=*/false, Enum);
Richard Smith258a7442012-03-26 04:08:46 +00001032 }
1033 }
Douglas Gregord7e7a512009-03-17 21:15:40 +00001034
Richard Smith4b38ded2012-03-14 23:13:10 +00001035 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1036 // specialization causes the implicit instantiation of the declarations, but
1037 // not the definitions of scoped member enumerations.
David Majnemer192d1792013-11-27 08:20:38 +00001038 //
1039 // DR1484 clarifies that enumeration definitions inside of a template
1040 // declaration aren't considered entities that can be separately instantiated
1041 // from the rest of the entity they are declared inside of.
1042 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1043 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
Richard Smith258a7442012-03-26 04:08:46 +00001044 InstantiateEnumDefinition(Enum, Def);
David Majnemer192d1792013-11-27 08:20:38 +00001045 }
Richard Smith4b38ded2012-03-14 23:13:10 +00001046
1047 return Enum;
1048}
1049
1050void TemplateDeclInstantiator::InstantiateEnumDefinition(
1051 EnumDecl *Enum, EnumDecl *Pattern) {
1052 Enum->startDefinition();
1053
Richard Smith7d137e32012-03-23 03:33:32 +00001054 // Update the location to refer to the definition.
1055 Enum->setLocation(Pattern->getLocation());
1056
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001057 SmallVector<Decl*, 4> Enumerators;
Douglas Gregord7e7a512009-03-17 21:15:40 +00001058
Craig Topperc3ec1492014-05-26 06:22:03 +00001059 EnumConstantDecl *LastEnumConst = nullptr;
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001060 for (auto *EC : Pattern->enumerators()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +00001061 // The specified value for the enumerator.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001062 ExprResult Value((Expr *)nullptr);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00001063 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smith764d2fe2011-12-20 02:08:33 +00001064 // The enumerator's value expression is a constant expression.
Mike Stump11289f42009-09-09 15:08:12 +00001065 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Richard Smith764d2fe2011-12-20 02:08:33 +00001066 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +00001067
John McCall76d824f2009-08-25 22:02:44 +00001068 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00001069 }
Douglas Gregord7e7a512009-03-17 21:15:40 +00001070
1071 // Drop the initial value and continue.
1072 bool isInvalid = false;
1073 if (Value.isInvalid()) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001074 Value = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +00001075 isInvalid = true;
1076 }
1077
Mike Stump11289f42009-09-09 15:08:12 +00001078 EnumConstantDecl *EnumConst
Douglas Gregord7e7a512009-03-17 21:15:40 +00001079 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1080 EC->getLocation(), EC->getIdentifier(),
John McCallb268a282010-08-23 23:25:46 +00001081 Value.get());
Douglas Gregord7e7a512009-03-17 21:15:40 +00001082
1083 if (isInvalid) {
1084 if (EnumConst)
1085 EnumConst->setInvalidDecl();
1086 Enum->setInvalidDecl();
1087 }
1088
1089 if (EnumConst) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001090 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
John McCall811a0f52010-10-22 23:36:17 +00001091
John McCallf9b528c2010-01-23 22:37:59 +00001092 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001093 Enum->addDecl(EnumConst);
John McCall48871652010-08-21 09:40:31 +00001094 Enumerators.push_back(EnumConst);
Douglas Gregord7e7a512009-03-17 21:15:40 +00001095 LastEnumConst = EnumConst;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001096
Richard Smith4b38ded2012-03-14 23:13:10 +00001097 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1098 !Enum->isScoped()) {
Douglas Gregoraff9c1a2010-03-01 19:00:07 +00001099 // If the enumeration is within a function or method, record the enum
1100 // constant as a local.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00001101 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
Douglas Gregoraff9c1a2010-03-01 19:00:07 +00001102 }
Douglas Gregord7e7a512009-03-17 21:15:40 +00001103 }
1104 }
Mike Stump11289f42009-09-09 15:08:12 +00001105
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00001106 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +00001107 Enumerators,
Craig Topperc3ec1492014-05-26 06:22:03 +00001108 nullptr, nullptr);
Douglas Gregord7e7a512009-03-17 21:15:40 +00001109}
1110
Douglas Gregor9106b822009-03-25 15:04:13 +00001111Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +00001112 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor9106b822009-03-25 15:04:13 +00001113}
1114
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001115Decl *
1116TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1117 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1118}
1119
John McCall87a44eb2009-08-20 01:44:21 +00001120Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall598b4402010-03-25 06:39:04 +00001121 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1122
Douglas Gregor954de172009-10-31 17:21:17 +00001123 // Create a local instantiation scope for this class template, which
1124 // will contain the instantiations of the template parameters.
John McCall19c1bfd2010-08-25 05:32:35 +00001125 LocalInstantiationScope Scope(SemaRef);
John McCall87a44eb2009-08-20 01:44:21 +00001126 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCall76d824f2009-08-25 22:02:44 +00001127 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +00001128 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001129 return nullptr;
John McCall87a44eb2009-08-20 01:44:21 +00001130
1131 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall598b4402010-03-25 06:39:04 +00001132
1133 // Instantiate the qualifier. We have to do this first in case
1134 // we're a friend declaration, because if we are then we need to put
1135 // the new declaration in the appropriate context.
Douglas Gregor14454802011-02-25 02:25:35 +00001136 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1137 if (QualifierLoc) {
1138 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1139 TemplateArgs);
1140 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00001141 return nullptr;
John McCall598b4402010-03-25 06:39:04 +00001142 }
1143
Craig Topperc3ec1492014-05-26 06:22:03 +00001144 CXXRecordDecl *PrevDecl = nullptr;
1145 ClassTemplateDecl *PrevClassTemplate = nullptr;
John McCall598b4402010-03-25 06:39:04 +00001146
Richard Smith41c79d92014-10-11 00:37:16 +00001147 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
Nick Lewycky61478912010-11-08 23:29:42 +00001148 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00001149 if (!Found.empty()) {
1150 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky61478912010-11-08 23:29:42 +00001151 if (PrevClassTemplate)
1152 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1153 }
1154 }
1155
John McCall598b4402010-03-25 06:39:04 +00001156 // If this isn't a friend, then it's a member template, in which
1157 // case we just want to build the instantiation in the
1158 // specialization. If it is a friend, we want to build it in
1159 // the appropriate context.
1160 DeclContext *DC = Owner;
1161 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +00001162 if (QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +00001163 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001164 SS.Adopt(QualifierLoc);
John McCall598b4402010-03-25 06:39:04 +00001165 DC = SemaRef.computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +00001166 if (!DC) return nullptr;
John McCall598b4402010-03-25 06:39:04 +00001167 } else {
1168 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1169 Pattern->getDeclContext(),
1170 TemplateArgs);
1171 }
1172
1173 // Look for a previous declaration of the template in the owning
1174 // context.
1175 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1176 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1177 SemaRef.LookupQualifiedName(R, DC);
1178
1179 if (R.isSingleResult()) {
1180 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1181 if (PrevClassTemplate)
1182 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1183 }
1184
Douglas Gregor14454802011-02-25 02:25:35 +00001185 if (!PrevClassTemplate && QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +00001186 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregorf5af3582010-03-31 23:17:41 +00001187 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregor14454802011-02-25 02:25:35 +00001188 << QualifierLoc.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001189 return nullptr;
John McCall598b4402010-03-25 06:39:04 +00001190 }
1191
Douglas Gregor01e09d92010-04-08 18:16:15 +00001192 bool AdoptedPreviousTemplateParams = false;
John McCall598b4402010-03-25 06:39:04 +00001193 if (PrevClassTemplate) {
Douglas Gregor01e09d92010-04-08 18:16:15 +00001194 bool Complain = true;
1195
1196 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
1197 // template for struct std::tr1::__detail::_Map_base, where the
1198 // template parameters of the friend declaration don't match the
1199 // template parameters of the original declaration. In this one
1200 // case, we don't complain about the ill-formed friend
1201 // declaration.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001202 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregor01e09d92010-04-08 18:16:15 +00001203 Pattern->getIdentifier()->isStr("_Map_base") &&
1204 DC->isNamespace() &&
1205 cast<NamespaceDecl>(DC)->getIdentifier() &&
1206 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
1207 DeclContext *DCParent = DC->getParent();
1208 if (DCParent->isNamespace() &&
1209 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
1210 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
Richard Trieuc771d5d2014-05-28 02:16:01 +00001211 if (cast<Decl>(DCParent)->isInStdNamespace())
Douglas Gregor01e09d92010-04-08 18:16:15 +00001212 Complain = false;
1213 }
1214 }
1215
John McCall598b4402010-03-25 06:39:04 +00001216 TemplateParameterList *PrevParams
1217 = PrevClassTemplate->getTemplateParameters();
1218
1219 // Make sure the parameter lists match.
1220 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001221 Complain,
Douglas Gregor01e09d92010-04-08 18:16:15 +00001222 Sema::TPL_TemplateMatch)) {
1223 if (Complain)
Craig Topperc3ec1492014-05-26 06:22:03 +00001224 return nullptr;
Douglas Gregor01e09d92010-04-08 18:16:15 +00001225
1226 AdoptedPreviousTemplateParams = true;
1227 InstParams = PrevParams;
1228 }
John McCall598b4402010-03-25 06:39:04 +00001229
1230 // Do some additional validation, then merge default arguments
1231 // from the existing declarations.
Douglas Gregor01e09d92010-04-08 18:16:15 +00001232 if (!AdoptedPreviousTemplateParams &&
1233 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall598b4402010-03-25 06:39:04 +00001234 Sema::TPC_ClassTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00001235 return nullptr;
John McCall598b4402010-03-25 06:39:04 +00001236 }
1237 }
1238
John McCall87a44eb2009-08-20 01:44:21 +00001239 CXXRecordDecl *RecordInst
John McCall598b4402010-03-25 06:39:04 +00001240 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001241 Pattern->getLocStart(), Pattern->getLocation(),
1242 Pattern->getIdentifier(), PrevDecl,
Douglas Gregoref06ccf2009-10-12 23:11:44 +00001243 /*DelayTypeCreation=*/true);
John McCall87a44eb2009-08-20 01:44:21 +00001244
Douglas Gregor14454802011-02-25 02:25:35 +00001245 if (QualifierLoc)
1246 RecordInst->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001247
John McCall87a44eb2009-08-20 01:44:21 +00001248 ClassTemplateDecl *Inst
John McCall598b4402010-03-25 06:39:04 +00001249 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
Vassil Vassilev352e4412017-01-12 09:16:26 +00001250 D->getIdentifier(), InstParams, RecordInst);
1251 assert(!(isFriend && Owner->isDependentContext()));
1252 Inst->setPreviousDecl(PrevClassTemplate);
1253
John McCall87a44eb2009-08-20 01:44:21 +00001254 RecordInst->setDescribedClassTemplate(Inst);
John McCall17762b82010-04-08 20:25:50 +00001255
John McCall598b4402010-03-25 06:39:04 +00001256 if (isFriend) {
John McCall17762b82010-04-08 20:25:50 +00001257 if (PrevClassTemplate)
1258 Inst->setAccess(PrevClassTemplate->getAccess());
1259 else
1260 Inst->setAccess(D->getAccess());
1261
Richard Smith64017682013-07-17 23:53:16 +00001262 Inst->setObjectOfFriendDecl();
John McCall598b4402010-03-25 06:39:04 +00001263 // TODO: do we want to track the instantiation progeny of this
1264 // friend target decl?
1265 } else {
Douglas Gregor412e8bc2009-10-30 21:07:27 +00001266 Inst->setAccess(D->getAccess());
Nick Lewycky61478912010-11-08 23:29:42 +00001267 if (!PrevClassTemplate)
1268 Inst->setInstantiatedFromMemberTemplate(D);
John McCall598b4402010-03-25 06:39:04 +00001269 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001270
Douglas Gregoref06ccf2009-10-12 23:11:44 +00001271 // Trigger creation of the type for the instantiation.
John McCalle78aac42010-03-10 03:28:59 +00001272 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor9961ce92010-07-08 18:37:38 +00001273 Inst->getInjectedClassNameSpecialization());
John McCall17762b82010-04-08 20:25:50 +00001274
Douglas Gregorbb3b46e2009-10-30 22:42:42 +00001275 // Finish handling of friends.
John McCall598b4402010-03-25 06:39:04 +00001276 if (isFriend) {
Richard Smith05afe5e2012-03-13 03:12:56 +00001277 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +00001278 Inst->setLexicalDeclContext(Owner);
1279 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregor412e8bc2009-10-30 21:07:27 +00001280 return Inst;
Douglas Gregorbb3b46e2009-10-30 22:42:42 +00001281 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001282
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +00001283 if (D->isOutOfLine()) {
1284 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1285 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1286 }
1287
John McCall87a44eb2009-08-20 01:44:21 +00001288 Owner->addDecl(Inst);
Douglas Gregor869853e2010-11-10 19:44:59 +00001289
1290 if (!PrevClassTemplate) {
1291 // Queue up any out-of-line partial specializations of this member
1292 // class template; the client will force their instantiation once
1293 // the enclosing class has been instantiated.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001294 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor869853e2010-11-10 19:44:59 +00001295 D->getPartialSpecializations(PartialSpecs);
1296 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +00001297 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Douglas Gregor869853e2010-11-10 19:44:59 +00001298 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1299 }
1300
John McCall87a44eb2009-08-20 01:44:21 +00001301 return Inst;
1302}
1303
Douglas Gregore704c9d2009-08-27 16:57:43 +00001304Decl *
Douglas Gregore4b05162009-10-07 17:21:34 +00001305TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1306 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregor21610382009-10-29 00:04:11 +00001307 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001308
Douglas Gregor21610382009-10-29 00:04:11 +00001309 // Lookup the already-instantiated declaration in the instantiation
1310 // of the class template and return that.
1311 DeclContext::lookup_result Found
1312 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00001313 if (Found.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00001314 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001315
Douglas Gregor21610382009-10-29 00:04:11 +00001316 ClassTemplateDecl *InstClassTemplate
David Blaikieff7d47a2012-12-19 00:45:41 +00001317 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregor21610382009-10-29 00:04:11 +00001318 if (!InstClassTemplate)
Craig Topperc3ec1492014-05-26 06:22:03 +00001319 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001320
Douglas Gregor869853e2010-11-10 19:44:59 +00001321 if (ClassTemplatePartialSpecializationDecl *Result
1322 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1323 return Result;
1324
1325 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregore4b05162009-10-07 17:21:34 +00001326}
1327
Larisse Voufo39a1e502013-08-06 01:03:05 +00001328Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1329 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1330 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001331
1332 // Create a local instantiation scope for this variable template, which
1333 // will contain the instantiations of the template parameters.
1334 LocalInstantiationScope Scope(SemaRef);
1335 TemplateParameterList *TempParams = D->getTemplateParameters();
1336 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1337 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001338 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001339
1340 VarDecl *Pattern = D->getTemplatedDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001341 VarTemplateDecl *PrevVarTemplate = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001342
Richard Smith41c79d92014-10-11 00:37:16 +00001343 if (getPreviousDeclForInstantiation(Pattern)) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00001344 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1345 if (!Found.empty())
1346 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1347 }
1348
Richard Smith1c34fb72013-08-13 18:18:50 +00001349 VarDecl *VarInst =
Larisse Voufo72caf2b2013-08-22 00:59:14 +00001350 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1351 /*InstantiatingVarTemplate=*/true));
Nick Lewycky6ca07ca2015-08-10 21:54:08 +00001352 if (!VarInst) return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001353
1354 DeclContext *DC = Owner;
1355
Larisse Voufo39a1e502013-08-06 01:03:05 +00001356 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1357 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
Richard Smithbeef3452014-01-16 23:39:20 +00001358 VarInst);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001359 VarInst->setDescribedVarTemplate(Inst);
Richard Smithbeef3452014-01-16 23:39:20 +00001360 Inst->setPreviousDecl(PrevVarTemplate);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001361
1362 Inst->setAccess(D->getAccess());
1363 if (!PrevVarTemplate)
1364 Inst->setInstantiatedFromMemberTemplate(D);
1365
1366 if (D->isOutOfLine()) {
1367 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1368 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1369 }
1370
1371 Owner->addDecl(Inst);
1372
1373 if (!PrevVarTemplate) {
1374 // Queue up any out-of-line partial specializations of this member
1375 // variable template; the client will force their instantiation once
1376 // the enclosing class has been instantiated.
1377 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1378 D->getPartialSpecializations(PartialSpecs);
1379 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +00001380 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00001381 OutOfLineVarPartialSpecs.push_back(
1382 std::make_pair(Inst, PartialSpecs[I]));
1383 }
1384
1385 return Inst;
1386}
1387
1388Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1389 VarTemplatePartialSpecializationDecl *D) {
1390 assert(D->isStaticDataMember() &&
1391 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001392
1393 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1394
1395 // Lookup the already-instantiated declaration and return that.
1396 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1397 assert(!Found.empty() && "Instantiation found nothing?");
1398
1399 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1400 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1401
1402 if (VarTemplatePartialSpecializationDecl *Result =
1403 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1404 return Result;
1405
1406 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1407}
1408
Douglas Gregore4b05162009-10-07 17:21:34 +00001409Decl *
Douglas Gregore704c9d2009-08-27 16:57:43 +00001410TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor954de172009-10-31 17:21:17 +00001411 // Create a local instantiation scope for this function template, which
1412 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001413 // merged with the local instantiation scope for the function template
Douglas Gregor954de172009-10-31 17:21:17 +00001414 // itself.
John McCall19c1bfd2010-08-25 05:32:35 +00001415 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor14cf7522010-04-30 18:55:50 +00001416
Douglas Gregore704c9d2009-08-27 16:57:43 +00001417 TemplateParameterList *TempParams = D->getTemplateParameters();
1418 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +00001419 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001420 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001421
Craig Topperc3ec1492014-05-26 06:22:03 +00001422 FunctionDecl *Instantiated = nullptr;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001423 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001424 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001425 InstParams));
1426 else
1427 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001428 D->getTemplatedDecl(),
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001429 InstParams));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001430
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001431 if (!Instantiated)
Craig Topperc3ec1492014-05-26 06:22:03 +00001432 return nullptr;
Douglas Gregore704c9d2009-08-27 16:57:43 +00001433
Mike Stump11289f42009-09-09 15:08:12 +00001434 // Link the instantiated function template declaration to the function
Douglas Gregore704c9d2009-08-27 16:57:43 +00001435 // template from which it was instantiated.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001436 FunctionTemplateDecl *InstTemplate
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001437 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregorca027af2009-10-12 22:27:17 +00001438 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001439 assert(InstTemplate &&
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001440 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCall2079d0b2009-12-14 23:19:40 +00001441
John McCall30837102010-03-26 23:10:15 +00001442 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1443
John McCall2079d0b2009-12-14 23:19:40 +00001444 // Link the instantiation back to the pattern *unless* this is a
1445 // non-definition friend declaration.
1446 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCall30837102010-03-26 23:10:15 +00001447 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001448 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001449
John McCall30837102010-03-26 23:10:15 +00001450 // Make declarations visible in the appropriate context.
John McCalla0a96892012-08-10 03:15:35 +00001451 if (!isFriend) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001452 Owner->addDecl(InstTemplate);
John McCalla0a96892012-08-10 03:15:35 +00001453 } else if (InstTemplate->getDeclContext()->isRecord() &&
Richard Smith41c79d92014-10-11 00:37:16 +00001454 !getPreviousDeclForInstantiation(D)) {
John McCalla0a96892012-08-10 03:15:35 +00001455 SemaRef.CheckFriendAccess(InstTemplate);
1456 }
John McCall30837102010-03-26 23:10:15 +00001457
Douglas Gregore704c9d2009-08-27 16:57:43 +00001458 return InstTemplate;
1459}
1460
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001461Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001462 CXXRecordDecl *PrevDecl = nullptr;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001463 if (D->isInjectedClassName())
1464 PrevDecl = cast<CXXRecordDecl>(Owner);
Richard Smith41c79d92014-10-11 00:37:16 +00001465 else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001466 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Richard Smith41c79d92014-10-11 00:37:16 +00001467 PatternPrev,
John McCalle9f92a02009-12-15 22:29:06 +00001468 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +00001469 if (!Prev) return nullptr;
John McCalle9f92a02009-12-15 22:29:06 +00001470 PrevDecl = cast<CXXRecordDecl>(Prev);
1471 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001472
1473 CXXRecordDecl *Record
Mike Stump11289f42009-09-09 15:08:12 +00001474 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001475 D->getLocStart(), D->getLocation(),
1476 D->getIdentifier(), PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00001477
1478 // Substitute the nested name specifier, if any.
1479 if (SubstQualifier(D, Record))
Craig Topperc3ec1492014-05-26 06:22:03 +00001480 return nullptr;
John McCall3e11ebe2010-03-15 10:12:16 +00001481
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001482 Record->setImplicit(D->isImplicit());
Eli Friedmanbda4ef12009-08-27 19:11:42 +00001483 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1484 // the tag decls introduced by friend class declarations don't have an access
1485 // specifier. Remove once this area of the code gets sorted out.
1486 if (D->getAccess() != AS_none)
1487 Record->setAccess(D->getAccess());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001488 if (!D->isInjectedClassName())
Douglas Gregorbbe8f462009-10-08 15:14:33 +00001489 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001490
John McCallaa74a0c2009-08-28 07:59:38 +00001491 // If the original function was part of a friend declaration,
1492 // inherit its namespace state.
Richard Smith64017682013-07-17 23:53:16 +00001493 if (D->getFriendObjectKind())
1494 Record->setObjectOfFriendDecl();
John McCallaa74a0c2009-08-28 07:59:38 +00001495
Douglas Gregor04163182010-05-21 00:31:19 +00001496 // Make sure that anonymous structs and unions are recorded.
David Majnemer192d1792013-11-27 08:20:38 +00001497 if (D->isAnonymousStructOrUnion())
Douglas Gregor04163182010-05-21 00:31:19 +00001498 Record->setAnonymousStructOrUnion(true);
David Majnemer192d1792013-11-27 08:20:38 +00001499
1500 if (D->isLocalClass())
1501 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
Anders Carlsson5da84842009-09-01 04:26:58 +00001502
David Majnemerdbc0c8f2013-12-04 09:01:55 +00001503 // Forward the mangling number from the template to the instantiated decl.
1504 SemaRef.Context.setManglingNumber(Record,
1505 SemaRef.Context.getManglingNumber(D));
1506
David Majnemer00350522015-08-31 18:48:39 +00001507 // See if the old tag was defined along with a declarator.
1508 // If it did, mark the new tag as being associated with that declarator.
1509 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1510 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1511
1512 // See if the old tag was defined along with a typedef.
1513 // If it did, mark the new tag as being associated with that typedef.
1514 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1515 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1516
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001517 Owner->addDecl(Record);
David Majnemer192d1792013-11-27 08:20:38 +00001518
1519 // DR1484 clarifies that the members of a local class are instantiated as part
1520 // of the instantiation of their enclosing entity.
1521 if (D->isCompleteDefinition() && D->isLocalClass()) {
Richard Smithb0b68012015-05-11 23:09:06 +00001522 Sema::SavePendingLocalImplicitInstantiationsRAII
1523 SavedPendingLocalImplicitInstantiations(SemaRef);
1524
David Majnemera64cb5a2014-02-22 00:17:46 +00001525 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1526 TSK_ImplicitInstantiation,
1527 /*Complain=*/true);
Richard Smithb0b68012015-05-11 23:09:06 +00001528
Richard Smithece47582017-01-04 23:45:01 +00001529 // For nested local classes, we will instantiate the members when we
1530 // reach the end of the outermost (non-nested) local class.
1531 if (!D->isCXXClassMember())
1532 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1533 TSK_ImplicitInstantiation);
Richard Smithb0b68012015-05-11 23:09:06 +00001534
1535 // This class may have local implicit instantiations that need to be
1536 // performed within this scope.
1537 SemaRef.PerformPendingInstantiations(/*LocalOnly=*/true);
David Majnemer192d1792013-11-27 08:20:38 +00001538 }
Nico Weber72889432014-09-06 01:25:55 +00001539
1540 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1541
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001542 return Record;
1543}
1544
Douglas Gregor89f593a2012-09-13 21:56:43 +00001545/// \brief Adjust the given function type for an instantiation of the
1546/// given declaration, to cope with modifications to the function's type that
1547/// aren't reflected in the type-source information.
1548///
1549/// \param D The declaration we're instantiating.
1550/// \param TInfo The already-instantiated type.
1551static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1552 FunctionDecl *D,
1553 TypeSourceInfo *TInfo) {
Douglas Gregor1af8ad42012-09-13 22:01:49 +00001554 const FunctionProtoType *OrigFunc
1555 = D->getType()->castAs<FunctionProtoType>();
1556 const FunctionProtoType *NewFunc
1557 = TInfo->getType()->castAs<FunctionProtoType>();
1558 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1559 return TInfo->getType();
1560
1561 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1562 NewEPI.ExtInfo = OrigFunc->getExtInfo();
Alp Toker314cc812014-01-25 16:55:45 +00001563 return Context.getFunctionType(NewFunc->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00001564 NewFunc->getParamTypes(), NewEPI);
Douglas Gregor89f593a2012-09-13 21:56:43 +00001565}
1566
John McCallaa74a0c2009-08-28 07:59:38 +00001567/// Normal class members are of more specific types and therefore
1568/// don't make it here. This function serves two purposes:
1569/// 1) instantiating function templates
1570/// 2) substituting friend declarations
Douglas Gregor33636e62009-12-24 20:56:24 +00001571Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001572 TemplateParameterList *TemplateParams) {
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001573 // Check whether there is already a function template specialization for
1574 // this declaration.
1575 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCall2f88d7d2010-03-27 05:57:59 +00001576 if (FunctionTemplate && !TemplateParams) {
Richard Smith47752e42013-05-03 23:46:09 +00001577 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001578
Craig Topperc3ec1492014-05-26 06:22:03 +00001579 void *InsertPos = nullptr;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001580 FunctionDecl *SpecFunc
Craig Topper7e0daca2014-06-26 04:58:53 +00001581 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001582
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001583 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001584 if (SpecFunc)
1585 return SpecFunc;
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001586 }
Mike Stump11289f42009-09-09 15:08:12 +00001587
John McCall2f88d7d2010-03-27 05:57:59 +00001588 bool isFriend;
1589 if (FunctionTemplate)
1590 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1591 else
1592 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1593
Craig Topperc3ec1492014-05-26 06:22:03 +00001594 bool MergeWithParentScope = (TemplateParams != nullptr) ||
Douglas Gregor9f44d142010-05-21 21:25:08 +00001595 Owner->isFunctionOrMethod() ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001596 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001597 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001598 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00001599
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001600 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie4d142962011-11-10 05:42:04 +00001601 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001602 if (!TInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00001603 return nullptr;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001604 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCall58de3582009-08-14 02:03:10 +00001605
Douglas Gregor14454802011-02-25 02:25:35 +00001606 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1607 if (QualifierLoc) {
1608 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1609 TemplateArgs);
1610 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00001611 return nullptr;
John McCalle0b2ddb2010-03-26 04:53:08 +00001612 }
1613
John McCallce410662010-02-06 01:50:47 +00001614 // If we're instantiating a local function declaration, put the result
Richard Smith541b38b2013-09-20 01:15:31 +00001615 // in the enclosing namespace; otherwise we need to find the instantiated
1616 // context.
John McCallce410662010-02-06 01:50:47 +00001617 DeclContext *DC;
Richard Smith541b38b2013-09-20 01:15:31 +00001618 if (D->isLocalExternDecl()) {
John McCallce410662010-02-06 01:50:47 +00001619 DC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001620 SemaRef.adjustContextForLocalExternDecl(DC);
1621 } else if (isFriend && QualifierLoc) {
John McCalle0b2ddb2010-03-26 04:53:08 +00001622 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001623 SS.Adopt(QualifierLoc);
John McCalle0b2ddb2010-03-26 04:53:08 +00001624 DC = SemaRef.computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +00001625 if (!DC) return nullptr;
John McCalle0b2ddb2010-03-26 04:53:08 +00001626 } else {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001627 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001628 TemplateArgs);
John McCalle0b2ddb2010-03-26 04:53:08 +00001629 }
John McCallce410662010-02-06 01:50:47 +00001630
Richard Smithbc491202017-02-17 20:05:37 +00001631 FunctionDecl *Function;
1632 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D))
1633 Function = CXXDeductionGuideDecl::Create(
1634 SemaRef.Context, DC, D->getInnerLocStart(), DGuide->isExplicit(),
1635 D->getNameInfo(), T, TInfo, D->getSourceRange().getEnd());
1636 else {
1637 Function = FunctionDecl::Create(
1638 SemaRef.Context, DC, D->getInnerLocStart(), D->getNameInfo(), T, TInfo,
1639 D->getCanonicalDecl()->getStorageClass(), D->isInlineSpecified(),
1640 D->hasWrittenPrototype(), D->isConstexpr());
1641 Function->setRangeEnd(D->getSourceRange().getEnd());
1642 }
John McCall3e11ebe2010-03-15 10:12:16 +00001643
Richard Smithf3814ad2013-01-25 00:08:28 +00001644 if (D->isInlined())
1645 Function->setImplicitlyInline();
1646
Douglas Gregor14454802011-02-25 02:25:35 +00001647 if (QualifierLoc)
1648 Function->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001649
Richard Smith541b38b2013-09-20 01:15:31 +00001650 if (D->isLocalExternDecl())
1651 Function->setLocalExternDecl();
1652
John McCall30837102010-03-26 23:10:15 +00001653 DeclContext *LexicalDC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001654 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
John McCall30837102010-03-26 23:10:15 +00001655 assert(D->getDeclContext()->isFileContext());
1656 LexicalDC = D->getDeclContext();
1657 }
1658
1659 Function->setLexicalDeclContext(LexicalDC);
Mike Stump11289f42009-09-09 15:08:12 +00001660
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001661 // Attach the parameters
Reid Klecknera09e44c2013-07-31 21:00:18 +00001662 for (unsigned P = 0; P < Params.size(); ++P)
1663 if (Params[P])
1664 Params[P]->setOwningFunction(Function);
David Blaikie9c70e042011-09-21 18:16:56 +00001665 Function->setParams(Params);
John McCallaa74a0c2009-08-28 07:59:38 +00001666
Douglas Gregor1cd6ea02010-05-17 16:38:00 +00001667 SourceLocation InstantiateAtPOI;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001668 if (TemplateParams) {
1669 // Our resulting instantiation is actually a function template, since we
1670 // are substituting only the outer template parameters. For example, given
1671 //
1672 // template<typename T>
1673 // struct X {
1674 // template<typename U> friend void f(T, U);
1675 // };
1676 //
1677 // X<int> x;
1678 //
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001679 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001680 // which means substituting int for T, but leaving "f" as a friend function
1681 // template.
1682 // Build the function template itself.
John McCalle0b2ddb2010-03-26 04:53:08 +00001683 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001684 Function->getLocation(),
1685 Function->getDeclName(),
1686 TemplateParams, Function);
1687 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCall30837102010-03-26 23:10:15 +00001688
1689 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalle0b2ddb2010-03-26 04:53:08 +00001690
1691 if (isFriend && D->isThisDeclarationADefinition()) {
John McCalle0b2ddb2010-03-26 04:53:08 +00001692 FunctionTemplate->setInstantiatedFromMemberTemplate(
1693 D->getDescribedFunctionTemplate());
1694 }
Douglas Gregorffe14e32009-11-14 01:20:54 +00001695 } else if (FunctionTemplate) {
1696 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001697 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001698 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001699 TemplateArgumentList::CreateCopy(SemaRef.Context,
David Majnemer8b622692016-07-03 21:17:51 +00001700 Innermost),
Craig Topperc3ec1492014-05-26 06:22:03 +00001701 /*InsertPos=*/nullptr);
Richard Smith152bcd22017-01-28 02:56:07 +00001702 } else if (isFriend && D->isThisDeclarationADefinition()) {
1703 // Do not connect the friend to the template unless it's actually a
1704 // definition. We don't want non-template functions to be marked as being
1705 // template instantiations.
John McCalle0b2ddb2010-03-26 04:53:08 +00001706 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCallaa74a0c2009-08-28 07:59:38 +00001707 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001708
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001709 if (InitFunctionInstantiation(Function, D))
1710 Function->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001711
John McCallb9c78482010-04-08 09:05:18 +00001712 bool isExplicitSpecialization = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001713
Richard Smith541b38b2013-09-20 01:15:31 +00001714 LookupResult Previous(
1715 SemaRef, Function->getDeclName(), SourceLocation(),
1716 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1717 : Sema::LookupOrdinaryName,
1718 Sema::ForRedeclaration);
John McCall1f82f242009-11-18 22:49:29 +00001719
John McCallb9c78482010-04-08 09:05:18 +00001720 if (DependentFunctionTemplateSpecializationInfo *Info
1721 = D->getDependentSpecializationInfo()) {
1722 assert(isFriend && "non-friend has dependent specialization info?");
1723
1724 // This needs to be set now for future sanity.
Richard Smith64017682013-07-17 23:53:16 +00001725 Function->setObjectOfFriendDecl();
John McCallb9c78482010-04-08 09:05:18 +00001726
1727 // Instantiate the explicit template arguments.
1728 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1729 Info->getRAngleLoc());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001730 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1731 ExplicitArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00001732 return nullptr;
John McCallb9c78482010-04-08 09:05:18 +00001733
1734 // Map the candidate templates to their instantiations.
1735 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1736 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1737 Info->getTemplate(I),
1738 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +00001739 if (!Temp) return nullptr;
John McCallb9c78482010-04-08 09:05:18 +00001740
1741 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1742 }
1743
1744 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1745 &ExplicitArgs,
1746 Previous))
1747 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001748
John McCallb9c78482010-04-08 09:05:18 +00001749 isExplicitSpecialization = true;
1750
1751 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001752 // Look only into the namespace where the friend would be declared to
1753 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001754 // as described in ActOnFriendFunctionDecl.
John McCall1f82f242009-11-18 22:49:29 +00001755 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001756
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001757 // In C++, the previous declaration we find might be a tag type
1758 // (class or enum). In this case, the new declaration will hide the
1759 // tag type. Note that this does does not apply if we're declaring a
1760 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001761 if (Previous.isSingleTagDecl())
1762 Previous.clear();
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001763 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001764
Craig Topperc3ec1492014-05-26 06:22:03 +00001765 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001766 isExplicitSpecialization);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001767
John McCallb9467b62010-04-24 01:30:58 +00001768 NamedDecl *PrincipalDecl = (TemplateParams
1769 ? cast<NamedDecl>(FunctionTemplate)
1770 : Function);
1771
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001772 // If the original function was part of a friend declaration,
1773 // inherit its namespace state and add it to the owner.
John McCalle0b2ddb2010-03-26 04:53:08 +00001774 if (isFriend) {
Richard Smith64017682013-07-17 23:53:16 +00001775 PrincipalDecl->setObjectOfFriendDecl();
Richard Smith05afe5e2012-03-13 03:12:56 +00001776 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greif718d5152010-08-30 21:10:05 +00001777
Richard Smith91dfaac2014-02-03 02:37:59 +00001778 bool QueuedInstantiation = false;
Gabor Greif718d5152010-08-30 21:10:05 +00001779
Richard Smith91dfaac2014-02-03 02:37:59 +00001780 // C++11 [temp.friend]p4 (DR329):
1781 // When a function is defined in a friend function declaration in a class
1782 // template, the function is instantiated when the function is odr-used.
1783 // The same restrictions on multiple declarations and definitions that
1784 // apply to non-template function declarations and definitions also apply
1785 // to these implicit definitions.
1786 if (D->isThisDeclarationADefinition()) {
Douglas Gregorb92ea592010-05-18 05:45:02 +00001787 // Check for a function body.
Craig Topperc3ec1492014-05-26 06:22:03 +00001788 const FunctionDecl *Definition = nullptr;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001789 if (Function->isDefined(Definition) &&
Douglas Gregorb92ea592010-05-18 05:45:02 +00001790 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smith91dfaac2014-02-03 02:37:59 +00001791 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1792 << Function->getDeclName();
Douglas Gregorb92ea592010-05-18 05:45:02 +00001793 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001794 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001795 // Check for redefinitions due to other instantiations of this or
1796 // a similar friend function.
Aaron Ballman86c93902014-03-06 23:45:36 +00001797 else for (auto R : Function->redecls()) {
1798 if (R == Function)
Gabor Greif122f1eb2010-08-28 15:42:30 +00001799 continue;
Richard Smith91dfaac2014-02-03 02:37:59 +00001800
1801 // If some prior declaration of this function has been used, we need
1802 // to instantiate its definition.
1803 if (!QueuedInstantiation && R->isUsed(false)) {
1804 if (MemberSpecializationInfo *MSInfo =
1805 Function->getMemberSpecializationInfo()) {
1806 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1807 SourceLocation Loc = R->getLocation(); // FIXME
1808 MSInfo->setPointOfInstantiation(Loc);
1809 SemaRef.PendingLocalImplicitInstantiations.push_back(
1810 std::make_pair(Function, Loc));
1811 QueuedInstantiation = true;
Gabor Greif718d5152010-08-30 21:10:05 +00001812 }
1813 }
Richard Smith91dfaac2014-02-03 02:37:59 +00001814 }
1815
1816 // If some prior declaration of this function was a friend with an
1817 // uninstantiated definition, reject it.
1818 if (R->getFriendObjectKind()) {
1819 if (const FunctionDecl *RPattern =
1820 R->getTemplateInstantiationPattern()) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001821 if (RPattern->isDefined(RPattern)) {
Richard Smith91dfaac2014-02-03 02:37:59 +00001822 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
Douglas Gregorb92ea592010-05-18 05:45:02 +00001823 << Function->getDeclName();
Gabor Greifae849e42010-08-28 15:46:56 +00001824 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregorb92ea592010-05-18 05:45:02 +00001825 break;
1826 }
Richard Smith91dfaac2014-02-03 02:37:59 +00001827 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001828 }
1829 }
1830 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001831 }
1832
Richard Smith541b38b2013-09-20 01:15:31 +00001833 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1834 DC->makeDeclVisibleInContext(PrincipalDecl);
1835
John McCallb9467b62010-04-24 01:30:58 +00001836 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1837 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1838 PrincipalDecl->setNonMemberOperator();
1839
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001840 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001841 return Function;
1842}
1843
Douglas Gregore704c9d2009-08-27 16:57:43 +00001844Decl *
1845TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001846 TemplateParameterList *TemplateParams,
1847 bool IsClassScopeSpecialization) {
Douglas Gregor97628d62009-08-21 00:16:32 +00001848 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregore704c9d2009-08-27 16:57:43 +00001849 if (FunctionTemplate && !TemplateParams) {
Mike Stump11289f42009-09-09 15:08:12 +00001850 // We are creating a function template specialization from a function
1851 // template. Check whether there is already a function template
Douglas Gregore704c9d2009-08-27 16:57:43 +00001852 // specialization for this particular set of template arguments.
Richard Smith47752e42013-05-03 23:46:09 +00001853 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001854
Craig Topperc3ec1492014-05-26 06:22:03 +00001855 void *InsertPos = nullptr;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001856 FunctionDecl *SpecFunc
Craig Topper7e0daca2014-06-26 04:58:53 +00001857 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001858
Douglas Gregor97628d62009-08-21 00:16:32 +00001859 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001860 if (SpecFunc)
1861 return SpecFunc;
Douglas Gregor97628d62009-08-21 00:16:32 +00001862 }
1863
John McCall2f88d7d2010-03-27 05:57:59 +00001864 bool isFriend;
1865 if (FunctionTemplate)
1866 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1867 else
1868 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1869
Craig Topperc3ec1492014-05-26 06:22:03 +00001870 bool MergeWithParentScope = (TemplateParams != nullptr) ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001871 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001872 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001873 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor37256522009-05-14 21:44:34 +00001874
John McCalld0e23ec2010-10-19 02:26:41 +00001875 // Instantiate enclosing template arguments for friends.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001876 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCalld0e23ec2010-10-19 02:26:41 +00001877 unsigned NumTempParamLists = 0;
1878 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
Benjamin Kramer9dc549b2015-08-04 14:46:06 +00001879 TempParamLists.resize(NumTempParamLists);
John McCalld0e23ec2010-10-19 02:26:41 +00001880 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1881 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1882 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1883 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001884 return nullptr;
John McCalld0e23ec2010-10-19 02:26:41 +00001885 TempParamLists[I] = InstParams;
1886 }
1887 }
1888
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001889 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramer1dd48bc2012-01-20 14:42:32 +00001890 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001891 if (!TInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00001892 return nullptr;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001893 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001894
Douglas Gregor14454802011-02-25 02:25:35 +00001895 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1896 if (QualifierLoc) {
1897 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCall2f88d7d2010-03-27 05:57:59 +00001898 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001899 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00001900 return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00001901 }
1902
1903 DeclContext *DC = Owner;
1904 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +00001905 if (QualifierLoc) {
John McCall2f88d7d2010-03-27 05:57:59 +00001906 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001907 SS.Adopt(QualifierLoc);
John McCall2f88d7d2010-03-27 05:57:59 +00001908 DC = SemaRef.computeDeclContext(SS);
John McCall1a1b53e2010-10-19 05:01:53 +00001909
1910 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
Craig Topperc3ec1492014-05-26 06:22:03 +00001911 return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00001912 } else {
1913 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1914 D->getDeclContext(),
1915 TemplateArgs);
1916 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001917 if (!DC) return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00001918 }
1919
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001920 // Build the instantiated method declaration.
John McCall2f88d7d2010-03-27 05:57:59 +00001921 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Craig Topperc3ec1492014-05-26 06:22:03 +00001922 CXXMethodDecl *Method = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001923
Abramo Bagnaradff19302011-03-08 08:55:46 +00001924 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001925 DeclarationNameInfo NameInfo
1926 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregore8394862009-08-21 22:43:28 +00001927 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00001928 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001929 StartLoc, NameInfo, T, TInfo,
Mike Stump11289f42009-09-09 15:08:12 +00001930 Constructor->isExplicit(),
Reid Kleckner0f764e52015-04-07 20:46:51 +00001931 Constructor->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001932 false, Constructor->isConstexpr());
Malcolm Parsons57ae8572016-11-28 11:11:34 +00001933 Method->setRangeEnd(Constructor->getLocEnd());
Douglas Gregore8394862009-08-21 22:43:28 +00001934 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregore8394862009-08-21 22:43:28 +00001935 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001936 StartLoc, NameInfo, T, TInfo,
Reid Kleckner0f764e52015-04-07 20:46:51 +00001937 Destructor->isInlineSpecified(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001938 false);
Malcolm Parsons57ae8572016-11-28 11:11:34 +00001939 Method->setRangeEnd(Destructor->getLocEnd());
Douglas Gregor05155d82009-08-21 23:19:43 +00001940 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001941 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001942 StartLoc, NameInfo, T, TInfo,
Reid Kleckner0f764e52015-04-07 20:46:51 +00001943 Conversion->isInlineSpecified(),
Douglas Gregorf2f08062011-03-08 17:10:18 +00001944 Conversion->isExplicit(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001945 Conversion->isConstexpr(),
Richard Smitheb3c10c2011-10-01 02:31:28 +00001946 Conversion->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001947 } else {
Rafael Espindola29cda592013-04-15 12:38:20 +00001948 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001949 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001950 StartLoc, NameInfo, T, TInfo,
Reid Kleckner0f764e52015-04-07 20:46:51 +00001951 SC, D->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001952 D->isConstexpr(), D->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001953 }
Douglas Gregor97628d62009-08-21 00:16:32 +00001954
Richard Smithf3814ad2013-01-25 00:08:28 +00001955 if (D->isInlined())
1956 Method->setImplicitlyInline();
1957
Douglas Gregor14454802011-02-25 02:25:35 +00001958 if (QualifierLoc)
1959 Method->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001960
Douglas Gregore704c9d2009-08-27 16:57:43 +00001961 if (TemplateParams) {
1962 // Our resulting instantiation is actually a function template, since we
1963 // are substituting only the outer template parameters. For example, given
Mike Stump11289f42009-09-09 15:08:12 +00001964 //
Douglas Gregore704c9d2009-08-27 16:57:43 +00001965 // template<typename T>
1966 // struct X {
1967 // template<typename U> void f(T, U);
1968 // };
1969 //
1970 // X<int> x;
1971 //
1972 // We are instantiating the member template "f" within X<int>, which means
1973 // substituting int for T, but leaving "f" as a member function template.
1974 // Build the function template itself.
1975 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1976 Method->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001977 Method->getDeclName(),
Douglas Gregore704c9d2009-08-27 16:57:43 +00001978 TemplateParams, Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001979 if (isFriend) {
1980 FunctionTemplate->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001981 FunctionTemplate->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001982 } else if (D->isOutOfLine())
Mike Stump11289f42009-09-09 15:08:12 +00001983 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregore704c9d2009-08-27 16:57:43 +00001984 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001985 } else if (FunctionTemplate) {
1986 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001987 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001988 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001989 TemplateArgumentList::CreateCopy(SemaRef.Context,
David Majnemer8b622692016-07-03 21:17:51 +00001990 Innermost),
Craig Topperc3ec1492014-05-26 06:22:03 +00001991 /*InsertPos=*/nullptr);
John McCall2f88d7d2010-03-27 05:57:59 +00001992 } else if (!isFriend) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00001993 // Record that this is an instantiation of a member function.
Douglas Gregord801b062009-10-07 23:56:10 +00001994 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001995 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001996
Mike Stump11289f42009-09-09 15:08:12 +00001997 // If we are instantiating a member function defined
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001998 // out-of-line, the instantiation will have the same lexical
1999 // context (which will be a namespace scope) as the template.
John McCall2f88d7d2010-03-27 05:57:59 +00002000 if (isFriend) {
John McCalld0e23ec2010-10-19 02:26:41 +00002001 if (NumTempParamLists)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00002002 Method->setTemplateParameterListsInfo(
2003 SemaRef.Context,
2004 llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
John McCalld0e23ec2010-10-19 02:26:41 +00002005
John McCall2f88d7d2010-03-27 05:57:59 +00002006 Method->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00002007 Method->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00002008 } else if (D->isOutOfLine())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002009 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00002010
Douglas Gregor21342092009-03-24 00:38:23 +00002011 // Attach the parameters
2012 for (unsigned P = 0; P < Params.size(); ++P)
2013 Params[P]->setOwningFunction(Method);
David Blaikie9c70e042011-09-21 18:16:56 +00002014 Method->setParams(Params);
Douglas Gregor21342092009-03-24 00:38:23 +00002015
2016 if (InitMethodInstantiation(Method, D))
2017 Method->setInvalidDecl();
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002018
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002019 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
2020 Sema::ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00002021
John McCall2f88d7d2010-03-27 05:57:59 +00002022 if (!FunctionTemplate || TemplateParams || isFriend) {
2023 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump11289f42009-09-09 15:08:12 +00002024
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002025 // In C++, the previous declaration we find might be a tag type
2026 // (class or enum). In this case, the new declaration will hide the
2027 // tag type. Note that this does does not apply if we're declaring a
2028 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00002029 if (Previous.isSingleTagDecl())
2030 Previous.clear();
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002031 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002032
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002033 if (!IsClassScopeSpecialization)
Craig Topperc3ec1492014-05-26 06:22:03 +00002034 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, false);
Douglas Gregor05155d82009-08-21 23:19:43 +00002035
Douglas Gregor21920e372009-12-01 17:24:26 +00002036 if (D->isPure())
2037 SemaRef.CheckPureMethod(Method, SourceRange());
2038
John McCalla0a96892012-08-10 03:15:35 +00002039 // Propagate access. For a non-friend declaration, the access is
2040 // whatever we're propagating from. For a friend, it should be the
2041 // previous declaration we just found.
2042 if (isFriend && Method->getPreviousDecl())
2043 Method->setAccess(Method->getPreviousDecl()->getAccess());
2044 else
2045 Method->setAccess(D->getAccess());
2046 if (FunctionTemplate)
2047 FunctionTemplate->setAccess(Method->getAccess());
John McCall401982f2010-01-20 21:53:11 +00002048
Anders Carlsson7c812f52011-01-20 06:52:44 +00002049 SemaRef.CheckOverrideControl(Method);
2050
Eli Friedman41340732011-11-15 22:39:08 +00002051 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smith92f241f2012-12-08 02:53:02 +00002052 if (D->isExplicitlyDefaulted())
2053 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00002054 if (D->isDeletedAsWritten())
Richard Smith92f241f2012-12-08 02:53:02 +00002055 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00002056
John McCalla0a96892012-08-10 03:15:35 +00002057 // If there's a function template, let our caller handle it.
John McCall2f88d7d2010-03-27 05:57:59 +00002058 if (FunctionTemplate) {
John McCalla0a96892012-08-10 03:15:35 +00002059 // do nothing
2060
2061 // Don't hide a (potentially) valid declaration with an invalid one.
John McCall2f88d7d2010-03-27 05:57:59 +00002062 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCalla0a96892012-08-10 03:15:35 +00002063 // do nothing
2064
2065 // Otherwise, check access to friends and make them visible.
2066 } else if (isFriend) {
2067 // We only need to re-check access for methods which we didn't
2068 // manage to match during parsing.
2069 if (!D->getPreviousDecl())
2070 SemaRef.CheckFriendAccess(Method);
2071
2072 Record->makeDeclVisibleInContext(Method);
2073
2074 // Otherwise, add the declaration. We don't need to do this for
2075 // class-scope specializations because we'll have matched them with
2076 // the appropriate template.
2077 } else if (!IsClassScopeSpecialization) {
2078 Owner->addDecl(Method);
John McCall2f88d7d2010-03-27 05:57:59 +00002079 }
Alexis Hunt1fb4e762011-05-23 21:07:59 +00002080
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002081 return Method;
2082}
2083
Douglas Gregor4044d992009-03-24 16:43:20 +00002084Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002085 return VisitCXXMethodDecl(D);
Douglas Gregor4044d992009-03-24 16:43:20 +00002086}
2087
Douglas Gregor654b07e2009-03-24 00:15:49 +00002088Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore8394862009-08-21 22:43:28 +00002089 return VisitCXXMethodDecl(D);
Douglas Gregor654b07e2009-03-24 00:15:49 +00002090}
2091
Douglas Gregor1880ba52009-03-25 00:34:44 +00002092Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002093 return VisitCXXMethodDecl(D);
Douglas Gregor1880ba52009-03-25 00:34:44 +00002094}
2095
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002096Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie7a30dc52013-02-21 01:47:18 +00002097 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
2098 /*ExpectParameterPack=*/ false);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002099}
2100
John McCall87a44eb2009-08-20 01:44:21 +00002101Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2102 TemplateTypeParmDecl *D) {
2103 // TODO: don't always clone when decls are refcounted.
Chandler Carruth08836322011-05-01 00:51:33 +00002104 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump11289f42009-09-09 15:08:12 +00002105
Richard Smithb4f96252017-02-21 06:30:38 +00002106 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
2107 SemaRef.Context, Owner, D->getLocStart(), D->getLocation(),
2108 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2109 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack());
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002110 Inst->setAccess(AS_public);
John McCall87a44eb2009-08-20 01:44:21 +00002111
Richard Smith52933792015-06-16 21:57:05 +00002112 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
David Majnemer89189202013-08-28 23:48:32 +00002113 TypeSourceInfo *InstantiatedDefaultArg =
2114 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2115 D->getDefaultArgumentLoc(), D->getDeclName());
2116 if (InstantiatedDefaultArg)
Richard Smith1469b912015-06-10 00:29:03 +00002117 Inst->setDefaultArgument(InstantiatedDefaultArg);
David Majnemer89189202013-08-28 23:48:32 +00002118 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002119
2120 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00002121 // scope.
2122 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002123
John McCall87a44eb2009-08-20 01:44:21 +00002124 return Inst;
2125}
2126
Douglas Gregor6b815c82009-10-23 23:25:44 +00002127Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2128 NonTypeTemplateParmDecl *D) {
2129 // Substitute into the type of the non-type template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002130 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002131 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2132 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002133 bool IsExpandedParameterPack = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002134 TypeSourceInfo *DI;
Douglas Gregor6b815c82009-10-23 23:25:44 +00002135 QualType T;
Douglas Gregor6b815c82009-10-23 23:25:44 +00002136 bool Invalid = false;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002137
2138 if (D->isExpandedParameterPack()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002139 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002140 // expansion of types. Substitute into each of the expanded types.
2141 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2142 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2143 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
Richard Smith15361a22016-12-28 06:27:18 +00002144 TypeSourceInfo *NewDI =
2145 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2146 D->getLocation(), D->getDeclName());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002147 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002148 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002149
Richard Smith15361a22016-12-28 06:27:18 +00002150 QualType NewT =
2151 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002152 if (NewT.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00002153 return nullptr;
Richard Smith15361a22016-12-28 06:27:18 +00002154
2155 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002156 ExpandedParameterPackTypes.push_back(NewT);
2157 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002158
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002159 IsExpandedParameterPack = true;
2160 DI = D->getTypeSourceInfo();
2161 T = DI->getType();
Richard Smith1fde8ec2012-09-07 02:06:42 +00002162 } else if (D->isPackExpansion()) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002163 // The non-type template parameter pack's type is a pack expansion of types.
2164 // Determine whether we need to expand this parameter pack into separate
2165 // types.
David Blaikie6adc78e2013-02-18 22:06:02 +00002166 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002167 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002168 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002169 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002170
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002171 // Determine whether the set of unexpanded parameter packs can and should
2172 // be expanded.
2173 bool Expand = true;
2174 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00002175 Optional<unsigned> OrigNumExpansions
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002176 = Expansion.getTypePtr()->getNumExpansions();
David Blaikie05785d12013-02-20 22:23:23 +00002177 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002178 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2179 Pattern.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00002180 Unexpanded,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002181 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002182 Expand, RetainExpansion,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002183 NumExpansions))
Craig Topperc3ec1492014-05-26 06:22:03 +00002184 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002185
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002186 if (Expand) {
2187 for (unsigned I = 0; I != *NumExpansions; ++I) {
2188 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2189 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002190 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002191 D->getDeclName());
2192 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002193 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002194
Richard Smith15361a22016-12-28 06:27:18 +00002195 QualType NewT =
2196 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002197 if (NewT.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00002198 return nullptr;
Richard Smith15361a22016-12-28 06:27:18 +00002199
2200 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002201 ExpandedParameterPackTypes.push_back(NewT);
2202 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002203
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002204 // Note that we have an expanded parameter pack. The "type" of this
2205 // expanded parameter pack is the original expansion type, but callers
2206 // will end up using the expanded parameter pack types for type-checking.
2207 IsExpandedParameterPack = true;
2208 DI = D->getTypeSourceInfo();
2209 T = DI->getType();
2210 } else {
2211 // We cannot fully expand the pack expansion now, so substitute into the
2212 // pattern and create a new pack expansion type.
2213 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2214 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002215 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002216 D->getDeclName());
2217 if (!NewPattern)
Craig Topperc3ec1492014-05-26 06:22:03 +00002218 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002219
Richard Smith15361a22016-12-28 06:27:18 +00002220 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002221 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2222 NumExpansions);
2223 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002224 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002225
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002226 T = DI->getType();
2227 }
2228 } else {
2229 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002230 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002231 D->getLocation(), D->getDeclName());
2232 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002233 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002234
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002235 // Check that this type is acceptable for a non-type template parameter.
Richard Smith15361a22016-12-28 06:27:18 +00002236 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002237 if (T.isNull()) {
2238 T = SemaRef.Context.IntTy;
2239 Invalid = true;
2240 }
Douglas Gregor6b815c82009-10-23 23:25:44 +00002241 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002242
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002243 NonTypeTemplateParmDecl *Param;
2244 if (IsExpandedParameterPack)
David Majnemerdfecf1a2016-07-06 04:19:16 +00002245 Param = NonTypeTemplateParmDecl::Create(
2246 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
Richard Smithb4f96252017-02-21 06:30:38 +00002247 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2248 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
David Majnemerdfecf1a2016-07-06 04:19:16 +00002249 ExpandedParameterPackTypesAsWritten);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002250 else
Richard Smithb4f96252017-02-21 06:30:38 +00002251 Param = NonTypeTemplateParmDecl::Create(
2252 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2253 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2254 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002255
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002256 Param->setAccess(AS_public);
Douglas Gregor6b815c82009-10-23 23:25:44 +00002257 if (Invalid)
2258 Param->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002259
Richard Smith52933792015-06-16 21:57:05 +00002260 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
Manman Renc445d382016-02-24 23:05:43 +00002261 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
2262 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00002263 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2264 if (!Value.isInvalid())
Richard Smith1469b912015-06-10 00:29:03 +00002265 Param->setDefaultArgument(Value.get());
David Majnemer89189202013-08-28 23:48:32 +00002266 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002267
2268 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00002269 // scope.
2270 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor6b815c82009-10-23 23:25:44 +00002271 return Param;
2272}
2273
Richard Smith1fde8ec2012-09-07 02:06:42 +00002274static void collectUnexpandedParameterPacks(
2275 Sema &S,
2276 TemplateParameterList *Params,
2277 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Davide Italiano18960b92015-07-02 19:20:11 +00002278 for (const auto &P : *Params) {
2279 if (P->isTemplateParameterPack())
Richard Smith1fde8ec2012-09-07 02:06:42 +00002280 continue;
Davide Italiano18960b92015-07-02 19:20:11 +00002281 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
Richard Smith1fde8ec2012-09-07 02:06:42 +00002282 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2283 Unexpanded);
Davide Italiano18960b92015-07-02 19:20:11 +00002284 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
Richard Smith1fde8ec2012-09-07 02:06:42 +00002285 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2286 Unexpanded);
2287 }
2288}
2289
Anders Carlsson4bd78752009-08-28 15:18:15 +00002290Decl *
Douglas Gregor38fee962009-11-11 16:58:32 +00002291TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2292 TemplateTemplateParmDecl *D) {
2293 // Instantiate the template parameter list of the template template parameter.
2294 TemplateParameterList *TempParams = D->getTemplateParameters();
2295 TemplateParameterList *InstParams;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002296 SmallVector<TemplateParameterList*, 8> ExpandedParams;
2297
2298 bool IsExpandedParameterPack = false;
2299
2300 if (D->isExpandedParameterPack()) {
2301 // The template template parameter pack is an already-expanded pack
2302 // expansion of template parameters. Substitute into each of the expanded
2303 // parameters.
2304 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2305 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2306 I != N; ++I) {
2307 LocalInstantiationScope Scope(SemaRef);
2308 TemplateParameterList *Expansion =
2309 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2310 if (!Expansion)
Craig Topperc3ec1492014-05-26 06:22:03 +00002311 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002312 ExpandedParams.push_back(Expansion);
2313 }
2314
2315 IsExpandedParameterPack = true;
2316 InstParams = TempParams;
2317 } else if (D->isPackExpansion()) {
2318 // The template template parameter pack expands to a pack of template
2319 // template parameters. Determine whether we need to expand this parameter
2320 // pack into separate parameters.
2321 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2322 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2323 Unexpanded);
2324
2325 // Determine whether the set of unexpanded parameter packs can and should
2326 // be expanded.
2327 bool Expand = true;
2328 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00002329 Optional<unsigned> NumExpansions;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002330 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2331 TempParams->getSourceRange(),
2332 Unexpanded,
2333 TemplateArgs,
2334 Expand, RetainExpansion,
2335 NumExpansions))
Craig Topperc3ec1492014-05-26 06:22:03 +00002336 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002337
2338 if (Expand) {
2339 for (unsigned I = 0; I != *NumExpansions; ++I) {
2340 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2341 LocalInstantiationScope Scope(SemaRef);
2342 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2343 if (!Expansion)
Craig Topperc3ec1492014-05-26 06:22:03 +00002344 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002345 ExpandedParams.push_back(Expansion);
2346 }
2347
2348 // Note that we have an expanded parameter pack. The "type" of this
2349 // expanded parameter pack is the original expansion type, but callers
2350 // will end up using the expanded parameter pack types for type-checking.
2351 IsExpandedParameterPack = true;
2352 InstParams = TempParams;
2353 } else {
2354 // We cannot fully expand the pack expansion now, so just substitute
2355 // into the pattern.
2356 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2357
2358 LocalInstantiationScope Scope(SemaRef);
2359 InstParams = SubstTemplateParams(TempParams);
2360 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002361 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002362 }
2363 } else {
Douglas Gregor38fee962009-11-11 16:58:32 +00002364 // Perform the actual substitution of template parameters within a new,
2365 // local instantiation scope.
John McCall19c1bfd2010-08-25 05:32:35 +00002366 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor38fee962009-11-11 16:58:32 +00002367 InstParams = SubstTemplateParams(TempParams);
2368 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002369 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002370 }
2371
Douglas Gregor38fee962009-11-11 16:58:32 +00002372 // Build the template template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002373 TemplateTemplateParmDecl *Param;
2374 if (IsExpandedParameterPack)
Richard Smithb4f96252017-02-21 06:30:38 +00002375 Param = TemplateTemplateParmDecl::Create(
2376 SemaRef.Context, Owner, D->getLocation(),
2377 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2378 D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
Richard Smith1fde8ec2012-09-07 02:06:42 +00002379 else
Richard Smithb4f96252017-02-21 06:30:38 +00002380 Param = TemplateTemplateParmDecl::Create(
2381 SemaRef.Context, Owner, D->getLocation(),
2382 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2383 D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
Richard Smith52933792015-06-16 21:57:05 +00002384 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
David Majnemer89189202013-08-28 23:48:32 +00002385 NestedNameSpecifierLoc QualifierLoc =
2386 D->getDefaultArgument().getTemplateQualifierLoc();
2387 QualifierLoc =
2388 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2389 TemplateName TName = SemaRef.SubstTemplateName(
2390 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2391 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2392 if (!TName.isNull())
2393 Param->setDefaultArgument(
Richard Smith1469b912015-06-10 00:29:03 +00002394 SemaRef.Context,
David Majnemer89189202013-08-28 23:48:32 +00002395 TemplateArgumentLoc(TemplateArgument(TName),
2396 D->getDefaultArgument().getTemplateQualifierLoc(),
Richard Smith1469b912015-06-10 00:29:03 +00002397 D->getDefaultArgument().getTemplateNameLoc()));
David Majnemer89189202013-08-28 23:48:32 +00002398 }
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002399 Param->setAccess(AS_public);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002400
2401 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor38fee962009-11-11 16:58:32 +00002402 // scope.
2403 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002404
Douglas Gregor38fee962009-11-11 16:58:32 +00002405 return Param;
2406}
2407
Douglas Gregore0b28662009-11-17 06:07:40 +00002408Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregor12441b32011-02-25 16:33:46 +00002409 // Using directives are never dependent (and never contain any types or
2410 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002411
Douglas Gregore0b28662009-11-17 06:07:40 +00002412 UsingDirectiveDecl *Inst
2413 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002414 D->getNamespaceKeyLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00002415 D->getQualifierLoc(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002416 D->getIdentLocation(),
2417 D->getNominatedNamespace(),
Douglas Gregore0b28662009-11-17 06:07:40 +00002418 D->getCommonAncestor());
Abramo Bagnara8843f9f2012-09-05 09:55:10 +00002419
2420 // Add the using directive to its declaration context
2421 // only if this is not a function or method.
2422 if (!Owner->isFunctionOrMethod())
2423 Owner->addDecl(Inst);
2424
Douglas Gregore0b28662009-11-17 06:07:40 +00002425 return Inst;
2426}
2427
John McCallb96ec562009-12-04 22:46:56 +00002428Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorac2e4302010-09-29 17:58:28 +00002429
2430 // The nested name specifier may be dependent, for example
2431 // template <typename T> struct t {
2432 // struct s1 { T f1(); };
2433 // struct s2 : s1 { using s1::f1; };
2434 // };
2435 // template struct t<int>;
2436 // Here, in using s1::f1, s1 refers to t<T>::s1;
2437 // we need to substitute for t<int>::s1.
Douglas Gregor0499ab62011-02-25 15:54:31 +00002438 NestedNameSpecifierLoc QualifierLoc
2439 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2440 TemplateArgs);
2441 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002442 return nullptr;
Douglas Gregorac2e4302010-09-29 17:58:28 +00002443
Richard Smith5179eb72016-06-28 19:03:57 +00002444 // For an inheriting constructor declaration, the name of the using
2445 // declaration is the name of a constructor in this class, not in the
2446 // base class.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002447 DeclarationNameInfo NameInfo = D->getNameInfo();
Richard Smith5179eb72016-06-28 19:03:57 +00002448 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2449 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
2450 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
2451 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
John McCallb96ec562009-12-04 22:46:56 +00002452
John McCall84d87672009-12-10 09:41:52 +00002453 // We only need to do redeclaration lookups if we're in a class
2454 // scope (in fact, it's not really even possible in non-class
2455 // scopes).
2456 bool CheckRedeclaration = Owner->isRecord();
2457
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002458 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2459 Sema::ForRedeclaration);
John McCall84d87672009-12-10 09:41:52 +00002460
John McCallb96ec562009-12-04 22:46:56 +00002461 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002462 D->getUsingLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002463 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002464 NameInfo,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002465 D->hasTypename());
John McCallb96ec562009-12-04 22:46:56 +00002466
Douglas Gregor0499ab62011-02-25 15:54:31 +00002467 CXXScopeSpec SS;
2468 SS.Adopt(QualifierLoc);
John McCall84d87672009-12-10 09:41:52 +00002469 if (CheckRedeclaration) {
2470 Prev.setHideTags(false);
2471 SemaRef.LookupQualifiedName(Prev, Owner);
2472
2473 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002474 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2475 D->hasTypename(), SS,
John McCall84d87672009-12-10 09:41:52 +00002476 D->getLocation(), Prev))
2477 NewUD->setInvalidDecl();
2478
2479 }
2480
2481 if (!NewUD->isInvalidDecl() &&
Richard Smithd8a9e372016-12-18 21:39:37 +00002482 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(),
2483 SS, NameInfo, D->getLocation()))
John McCallb96ec562009-12-04 22:46:56 +00002484 NewUD->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00002485
John McCallb96ec562009-12-04 22:46:56 +00002486 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2487 NewUD->setAccess(D->getAccess());
2488 Owner->addDecl(NewUD);
2489
John McCall84d87672009-12-10 09:41:52 +00002490 // Don't process the shadow decls for an invalid decl.
2491 if (NewUD->isInvalidDecl())
2492 return NewUD;
2493
Richard Smith5179eb72016-06-28 19:03:57 +00002494 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
Richard Smith09d5b3a2014-05-01 00:35:04 +00002495 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
Richard Smith23d55872012-04-02 01:30:27 +00002496
John McCalla1d85502009-12-22 22:26:37 +00002497 bool isFunctionScope = Owner->isFunctionOrMethod();
2498
John McCall84d87672009-12-10 09:41:52 +00002499 // Process the shadow decls.
Aaron Ballman91cdc282014-03-13 18:07:29 +00002500 for (auto *Shadow : D->shadows()) {
Richard Smith5179eb72016-06-28 19:03:57 +00002501 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
2502 // reconstruct it in the case where it matters.
2503 NamedDecl *OldTarget = Shadow->getTargetDecl();
2504 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
2505 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
2506 OldTarget = BaseShadow;
2507
John McCall84d87672009-12-10 09:41:52 +00002508 NamedDecl *InstTarget =
Richard Smithfd8634a2013-10-23 02:17:46 +00002509 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
Richard Smith5179eb72016-06-28 19:03:57 +00002510 Shadow->getLocation(), OldTarget, TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00002511 if (!InstTarget)
Craig Topperc3ec1492014-05-26 06:22:03 +00002512 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00002513
Craig Topperc3ec1492014-05-26 06:22:03 +00002514 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00002515 if (CheckRedeclaration) {
2516 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2517 continue;
Richard Smith41c79d92014-10-11 00:37:16 +00002518 } else if (UsingShadowDecl *OldPrev =
2519 getPreviousDeclForInstantiation(Shadow)) {
Richard Smithfd8634a2013-10-23 02:17:46 +00002520 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2521 Shadow->getLocation(), OldPrev, TemplateArgs));
2522 }
John McCall84d87672009-12-10 09:41:52 +00002523
Richard Smithfd8634a2013-10-23 02:17:46 +00002524 UsingShadowDecl *InstShadow =
Craig Topperc3ec1492014-05-26 06:22:03 +00002525 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2526 PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00002527 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCalla1d85502009-12-22 22:26:37 +00002528
2529 if (isFunctionScope)
2530 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall84d87672009-12-10 09:41:52 +00002531 }
John McCallb96ec562009-12-04 22:46:56 +00002532
2533 return NewUD;
2534}
2535
2536Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall84d87672009-12-10 09:41:52 +00002537 // Ignore these; we handle them in bulk when processing the UsingDecl.
Craig Topperc3ec1492014-05-26 06:22:03 +00002538 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00002539}
2540
Richard Smith5179eb72016-06-28 19:03:57 +00002541Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
2542 ConstructorUsingShadowDecl *D) {
2543 // Ignore these; we handle them in bulk when processing the UsingDecl.
2544 return nullptr;
2545}
2546
Richard Smith151c4562016-12-20 21:35:28 +00002547template <typename T>
2548Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
2549 T *D, bool InstantiatingPackElement) {
2550 // If this is a pack expansion, expand it now.
2551 if (D->isPackExpansion() && !InstantiatingPackElement) {
2552 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2553 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
2554 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
2555
2556 // Determine whether the set of unexpanded parameter packs can and should
2557 // be expanded.
2558 bool Expand = true;
2559 bool RetainExpansion = false;
2560 Optional<unsigned> NumExpansions;
2561 if (SemaRef.CheckParameterPacksForExpansion(
2562 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
2563 Expand, RetainExpansion, NumExpansions))
2564 return nullptr;
2565
2566 // This declaration cannot appear within a function template signature,
2567 // so we can't have a partial argument list for a parameter pack.
2568 assert(!RetainExpansion &&
2569 "should never need to retain an expansion for UsingPackDecl");
2570
2571 if (!Expand) {
2572 // We cannot fully expand the pack expansion now, so substitute into the
2573 // pattern and create a new pack expansion.
2574 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2575 return instantiateUnresolvedUsingDecl(D, true);
2576 }
2577
2578 // Within a function, we don't have any normal way to check for conflicts
2579 // between shadow declarations from different using declarations in the
2580 // same pack expansion, but this is always ill-formed because all expansions
2581 // must produce (conflicting) enumerators.
2582 //
2583 // Sadly we can't just reject this in the template definition because it
2584 // could be valid if the pack is empty or has exactly one expansion.
2585 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
2586 SemaRef.Diag(D->getEllipsisLoc(),
2587 diag::err_using_decl_redeclaration_expansion);
2588 return nullptr;
2589 }
2590
2591 // Instantiate the slices of this pack and build a UsingPackDecl.
2592 SmallVector<NamedDecl*, 8> Expansions;
2593 for (unsigned I = 0; I != *NumExpansions; ++I) {
2594 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2595 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
2596 if (!Slice)
2597 return nullptr;
2598 // Note that we can still get unresolved using declarations here, if we
2599 // had arguments for all packs but the pattern also contained other
2600 // template arguments (this only happens during partial substitution, eg
2601 // into the body of a generic lambda in a function template).
2602 Expansions.push_back(cast<NamedDecl>(Slice));
2603 }
2604
2605 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2606 if (isDeclWithinFunction(D))
2607 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2608 return NewD;
2609 }
2610
2611 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
2612 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
2613
Douglas Gregor0499ab62011-02-25 15:54:31 +00002614 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002615 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002616 TemplateArgs);
2617 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002618 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002619
Anders Carlsson4bd78752009-08-28 15:18:15 +00002620 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002621 SS.Adopt(QualifierLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002622
Daniel Jasper9949ead2016-12-19 10:09:25 +00002623 DeclarationNameInfo NameInfo
2624 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2625
Richard Smith151c4562016-12-20 21:35:28 +00002626 // Produce a pack expansion only if we're not instantiating a particular
2627 // slice of a pack expansion.
2628 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
2629 SemaRef.ArgumentPackSubstitutionIndex != -1;
2630 SourceLocation EllipsisLoc =
2631 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
2632
2633 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
2634 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
2635 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc, nullptr,
2636 /*IsInstantiation*/ true);
Daniel Jasper9949ead2016-12-19 10:09:25 +00002637 if (UD)
2638 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
2639
2640 return UD;
Richard Smith22a250c2016-12-19 04:08:53 +00002641}
2642
Richard Smith151c4562016-12-20 21:35:28 +00002643Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
2644 UnresolvedUsingTypenameDecl *D) {
2645 return instantiateUnresolvedUsingDecl(D);
2646}
2647
2648Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
2649 UnresolvedUsingValueDecl *D) {
2650 return instantiateUnresolvedUsingDecl(D);
2651}
2652
2653Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
2654 SmallVector<NamedDecl*, 8> Expansions;
2655 for (auto *UD : D->expansions()) {
2656 if (auto *NewUD =
2657 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
2658 Expansions.push_back(cast<NamedDecl>(NewUD));
2659 else
2660 return nullptr;
2661 }
2662
2663 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2664 if (isDeclWithinFunction(D))
2665 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2666 return NewD;
2667}
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002668
2669Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2670 ClassScopeFunctionSpecializationDecl *Decl) {
2671 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nick Lewycky0b727732015-01-02 01:33:12 +00002672 CXXMethodDecl *NewFD =
2673 cast_or_null<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, nullptr, true));
2674 if (!NewFD)
2675 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002676
2677 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2678 Sema::ForRedeclaration);
2679
Nico Weber7b5a7162012-06-25 17:21:05 +00002680 TemplateArgumentListInfo TemplateArgs;
Craig Topperc3ec1492014-05-26 06:22:03 +00002681 TemplateArgumentListInfo *TemplateArgsPtr = nullptr;
Nico Weber7b5a7162012-06-25 17:21:05 +00002682 if (Decl->hasExplicitTemplateArgs()) {
2683 TemplateArgs = Decl->templateArgs();
2684 TemplateArgsPtr = &TemplateArgs;
2685 }
2686
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002687 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber7b5a7162012-06-25 17:21:05 +00002688 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2689 Previous)) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002690 NewFD->setInvalidDecl();
2691 return NewFD;
2692 }
2693
2694 // Associate the specialization with the pattern.
2695 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2696 assert(Specialization && "Class scope Specialization is null");
2697 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2698
2699 return NewFD;
2700}
2701
Alexey Bataeva769e072013-03-22 06:34:35 +00002702Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2703 OMPThreadPrivateDecl *D) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002704 SmallVector<Expr *, 5> Vars;
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002705 for (auto *I : D->varlists()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002706 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
Alexey Bataeva769e072013-03-22 06:34:35 +00002707 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002708 Vars.push_back(Var);
Alexey Bataeva769e072013-03-22 06:34:35 +00002709 }
2710
2711 OMPThreadPrivateDecl *TD =
2712 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2713
Alexey Bataevd3db6ac2014-03-07 09:46:29 +00002714 TD->setAccess(AS_public);
2715 Owner->addDecl(TD);
2716
Alexey Bataeva769e072013-03-22 06:34:35 +00002717 return TD;
2718}
2719
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002720Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
2721 OMPDeclareReductionDecl *D) {
2722 // Instantiate type and check if it is allowed.
2723 QualType SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
2724 D->getLocation(),
2725 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
2726 D->getLocation(), DeclarationName())));
2727 if (SubstReductionType.isNull())
2728 return nullptr;
2729 bool IsCorrect = !SubstReductionType.isNull();
2730 // Create instantiated copy.
2731 std::pair<QualType, SourceLocation> ReductionTypes[] = {
2732 std::make_pair(SubstReductionType, D->getLocation())};
2733 auto *PrevDeclInScope = D->getPrevDeclInScope();
2734 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
2735 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
2736 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
2737 ->get<Decl *>());
2738 }
2739 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
2740 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
2741 PrevDeclInScope);
2742 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
2743 if (isDeclWithinFunction(NewDRD))
2744 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
2745 Expr *SubstCombiner = nullptr;
2746 Expr *SubstInitializer = nullptr;
2747 // Combiners instantiation sequence.
2748 if (D->getCombiner()) {
2749 SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
2750 /*S=*/nullptr, NewDRD);
2751 const char *Names[] = {"omp_in", "omp_out"};
2752 for (auto &Name : Names) {
2753 DeclarationName DN(&SemaRef.Context.Idents.get(Name));
2754 auto OldLookup = D->lookup(DN);
2755 auto Lookup = NewDRD->lookup(DN);
2756 if (!OldLookup.empty() && !Lookup.empty()) {
2757 assert(Lookup.size() == 1 && OldLookup.size() == 1);
2758 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldLookup.front(),
2759 Lookup.front());
2760 }
2761 }
2762 SubstCombiner = SemaRef.SubstExpr(D->getCombiner(), TemplateArgs).get();
2763 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
2764 // Initializers instantiation sequence.
2765 if (D->getInitializer()) {
2766 SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
2767 /*S=*/nullptr, NewDRD);
2768 const char *Names[] = {"omp_orig", "omp_priv"};
2769 for (auto &Name : Names) {
2770 DeclarationName DN(&SemaRef.Context.Idents.get(Name));
2771 auto OldLookup = D->lookup(DN);
2772 auto Lookup = NewDRD->lookup(DN);
2773 if (!OldLookup.empty() && !Lookup.empty()) {
2774 assert(Lookup.size() == 1 && OldLookup.size() == 1);
2775 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
2776 OldLookup.front(), Lookup.front());
2777 }
2778 }
2779 SubstInitializer =
2780 SemaRef.SubstExpr(D->getInitializer(), TemplateArgs).get();
2781 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD,
2782 SubstInitializer);
2783 }
2784 IsCorrect = IsCorrect && SubstCombiner &&
2785 (!D->getInitializer() || SubstInitializer);
2786 } else
2787 IsCorrect = false;
2788
2789 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(/*S=*/nullptr, DRD,
2790 IsCorrect);
2791
2792 return NewDRD;
2793}
2794
Alexey Bataev4244be22016-02-11 05:35:55 +00002795Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
2796 OMPCapturedExprDecl * /*D*/) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00002797 llvm_unreachable("Should not be met in templates");
2798}
2799
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002800Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002801 return VisitFunctionDecl(D, nullptr);
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002802}
2803
Richard Smithbc491202017-02-17 20:05:37 +00002804Decl *
2805TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
2806 return VisitFunctionDecl(D, nullptr);
2807}
2808
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002809Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002810 return VisitCXXMethodDecl(D, nullptr);
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002811}
2812
2813Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2814 llvm_unreachable("There are only CXXRecordDecls in C++");
2815}
2816
2817Decl *
2818TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2819 ClassTemplateSpecializationDecl *D) {
Richard Smith8a0dde72013-12-14 01:04:22 +00002820 // As a MS extension, we permit class-scope explicit specialization
2821 // of member class templates.
2822 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2823 assert(ClassTemplate->getDeclContext()->isRecord() &&
2824 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2825 "can only instantiate an explicit specialization "
2826 "for a member class template");
2827
2828 // Lookup the already-instantiated declaration in the instantiation
2829 // of the class template. FIXME: Diagnose or assert if this fails?
2830 DeclContext::lookup_result Found
2831 = Owner->lookup(ClassTemplate->getDeclName());
2832 if (Found.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00002833 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002834 ClassTemplateDecl *InstClassTemplate
2835 = dyn_cast<ClassTemplateDecl>(Found.front());
2836 if (!InstClassTemplate)
Craig Topperc3ec1492014-05-26 06:22:03 +00002837 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002838
2839 // Substitute into the template arguments of the class template explicit
2840 // specialization.
2841 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
2842 castAs<TemplateSpecializationTypeLoc>();
2843 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2844 Loc.getRAngleLoc());
2845 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
2846 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2847 ArgLocs.push_back(Loc.getArgLoc(I));
2848 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2849 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00002850 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002851
2852 // Check that the template argument list is well-formed for this
2853 // class template.
2854 SmallVector<TemplateArgument, 4> Converted;
2855 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2856 D->getLocation(),
2857 InstTemplateArgs,
2858 false,
2859 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00002860 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002861
2862 // Figure out where to insert this class template explicit specialization
2863 // in the member template's set of class template explicit specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00002864 void *InsertPos = nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002865 ClassTemplateSpecializationDecl *PrevDecl =
Craig Topper7e0daca2014-06-26 04:58:53 +00002866 InstClassTemplate->findSpecialization(Converted, InsertPos);
Richard Smith8a0dde72013-12-14 01:04:22 +00002867
2868 // Check whether we've already seen a conflicting instantiation of this
2869 // declaration (for instance, if there was a prior implicit instantiation).
2870 bool Ignored;
2871 if (PrevDecl &&
2872 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
2873 D->getSpecializationKind(),
2874 PrevDecl,
2875 PrevDecl->getSpecializationKind(),
2876 PrevDecl->getPointOfInstantiation(),
2877 Ignored))
Craig Topperc3ec1492014-05-26 06:22:03 +00002878 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002879
2880 // If PrevDecl was a definition and D is also a definition, diagnose.
2881 // This happens in cases like:
2882 //
2883 // template<typename T, typename U>
2884 // struct Outer {
2885 // template<typename X> struct Inner;
2886 // template<> struct Inner<T> {};
2887 // template<> struct Inner<U> {};
2888 // };
2889 //
2890 // Outer<int, int> outer; // error: the explicit specializations of Inner
2891 // // have the same signature.
2892 if (PrevDecl && PrevDecl->getDefinition() &&
2893 D->isThisDeclarationADefinition()) {
2894 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
2895 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
2896 diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +00002897 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002898 }
2899
2900 // Create the class template partial specialization declaration.
2901 ClassTemplateSpecializationDecl *InstD
2902 = ClassTemplateSpecializationDecl::Create(SemaRef.Context,
2903 D->getTagKind(),
2904 Owner,
2905 D->getLocStart(),
2906 D->getLocation(),
2907 InstClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00002908 Converted,
Richard Smith8a0dde72013-12-14 01:04:22 +00002909 PrevDecl);
2910
2911 // Add this partial specialization to the set of class template partial
2912 // specializations.
2913 if (!PrevDecl)
2914 InstClassTemplate->AddSpecialization(InstD, InsertPos);
2915
2916 // Substitute the nested name specifier, if any.
2917 if (SubstQualifier(D, InstD))
Craig Topperc3ec1492014-05-26 06:22:03 +00002918 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002919
2920 // Build the canonical type that describes the converted template
2921 // arguments of the class template explicit specialization.
2922 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00002923 TemplateName(InstClassTemplate), Converted,
Richard Smith8a0dde72013-12-14 01:04:22 +00002924 SemaRef.Context.getRecordType(InstD));
2925
2926 // Build the fully-sugared type for this class template
2927 // specialization as the user wrote in the specialization
2928 // itself. This means that we'll pretty-print the type retrieved
2929 // from the specialization's declaration the way that the user
2930 // actually wrote the specialization, rather than formatting the
2931 // name based on the "canonical" representation used to store the
2932 // template arguments in the specialization.
2933 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2934 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
2935 CanonType);
2936
2937 InstD->setAccess(D->getAccess());
2938 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2939 InstD->setSpecializationKind(D->getSpecializationKind());
2940 InstD->setTypeAsWritten(WrittenTy);
2941 InstD->setExternLoc(D->getExternLoc());
2942 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
2943
2944 Owner->addDecl(InstD);
2945
2946 // Instantiate the members of the class-scope explicit specialization eagerly.
2947 // We don't have support for lazy instantiation of an explicit specialization
2948 // yet, and MSVC eagerly instantiates in this case.
2949 if (D->isThisDeclarationADefinition() &&
2950 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
2951 TSK_ImplicitInstantiation,
2952 /*Complain=*/true))
Craig Topperc3ec1492014-05-26 06:22:03 +00002953 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002954
2955 return InstD;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002956}
2957
Larisse Voufo39a1e502013-08-06 01:03:05 +00002958Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2959 VarTemplateSpecializationDecl *D) {
2960
2961 TemplateArgumentListInfo VarTemplateArgsInfo;
2962 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2963 assert(VarTemplate &&
2964 "A template specialization without specialized template?");
2965
2966 // Substitute the current template arguments.
2967 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2968 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2969 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2970
2971 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2972 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00002973 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002974
2975 // Check that the template argument list is well-formed for this template.
2976 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002977 if (SemaRef.CheckTemplateArgumentList(
2978 VarTemplate, VarTemplate->getLocStart(),
2979 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002980 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00002981 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002982
2983 // Find the variable template specialization declaration that
2984 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002985 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002986 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +00002987 Converted, InsertPos))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002988 // If we already have a variable template specialization, return it.
2989 return VarSpec;
2990
2991 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2992 VarTemplateArgsInfo, Converted);
2993}
2994
2995Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2996 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2997 const TemplateArgumentListInfo &TemplateArgsInfo,
Craig Topper00bbdcf2014-06-28 23:22:23 +00002998 ArrayRef<TemplateArgument> Converted) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002999
Larisse Voufo39a1e502013-08-06 01:03:05 +00003000 // Do substitution on the type of the declaration
3001 TypeSourceInfo *DI =
3002 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3003 D->getTypeSpecStartLoc(), D->getDeclName());
3004 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00003005 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003006
3007 if (DI->getType()->isFunctionType()) {
3008 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
3009 << D->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003010 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003011 }
3012
3013 // Build the instantiated declaration
3014 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
3015 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
David Majnemer8b622692016-07-03 21:17:51 +00003016 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003017 Var->setTemplateArgsInfo(TemplateArgsInfo);
Richard Smith8809a0c2013-09-27 20:14:12 +00003018 if (InsertPos)
3019 VarTemplate->AddSpecialization(Var, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003020
3021 // Substitute the nested name specifier, if any.
3022 if (SubstQualifier(D, Var))
Craig Topperc3ec1492014-05-26 06:22:03 +00003023 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003024
3025 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
Richard Smith541b38b2013-09-20 01:15:31 +00003026 Owner, StartingScope);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003027
3028 return Var;
3029}
3030
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003031Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
3032 llvm_unreachable("@defs is not supported in Objective-C++");
3033}
3034
3035Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
3036 // FIXME: We need to be able to instantiate FriendTemplateDecls.
3037 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
3038 DiagnosticsEngine::Error,
3039 "cannot instantiate %0 yet");
3040 SemaRef.Diag(D->getLocation(), DiagID)
3041 << D->getDeclKindName();
3042
Craig Topperc3ec1492014-05-26 06:22:03 +00003043 return nullptr;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003044}
3045
3046Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
3047 llvm_unreachable("Unexpected decl");
3048}
3049
John McCall76d824f2009-08-25 22:02:44 +00003050Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregor01afeef2009-08-28 20:31:08 +00003051 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord002c7b2009-05-11 23:53:27 +00003052 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor71ad4772010-02-16 19:28:15 +00003053 if (D->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00003054 return nullptr;
Douglas Gregor71ad4772010-02-16 19:28:15 +00003055
Douglas Gregord7e7a512009-03-17 21:15:40 +00003056 return Instantiator.Visit(D);
3057}
3058
John McCall87a44eb2009-08-20 01:44:21 +00003059/// \brief Instantiates a nested template parameter list in the current
3060/// instantiation context.
3061///
3062/// \param L The parameter list to instantiate
3063///
3064/// \returns NULL if there was an error
3065TemplateParameterList *
John McCall76d824f2009-08-25 22:02:44 +00003066TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCall87a44eb2009-08-20 01:44:21 +00003067 // Get errors for all the parameters before bailing out.
3068 bool Invalid = false;
3069
3070 unsigned N = L->size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003071 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCall87a44eb2009-08-20 01:44:21 +00003072 ParamVector Params;
3073 Params.reserve(N);
Davide Italiano18960b92015-07-02 19:20:11 +00003074 for (auto &P : *L) {
3075 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
John McCall87a44eb2009-08-20 01:44:21 +00003076 Params.push_back(D);
Douglas Gregore62e6a02009-11-11 19:13:48 +00003077 Invalid = Invalid || !D || D->isInvalidDecl();
John McCall87a44eb2009-08-20 01:44:21 +00003078 }
3079
3080 // Clean up if we had an error.
Douglas Gregorb412e172010-07-25 18:17:45 +00003081 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +00003082 return nullptr;
John McCall87a44eb2009-08-20 01:44:21 +00003083
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00003084 // Note: we substitute into associated constraints later
3085 Expr *const UninstantiatedRequiresClause = L->getRequiresClause();
3086
John McCall87a44eb2009-08-20 01:44:21 +00003087 TemplateParameterList *InstL
3088 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
David Majnemer902f8c62015-12-27 07:16:27 +00003089 L->getLAngleLoc(), Params,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00003090 L->getRAngleLoc(),
3091 UninstantiatedRequiresClause);
John McCall87a44eb2009-08-20 01:44:21 +00003092 return InstL;
Mike Stump11289f42009-09-09 15:08:12 +00003093}
John McCall87a44eb2009-08-20 01:44:21 +00003094
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003095/// \brief Instantiate the declaration of a class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00003096/// specialization.
3097///
3098/// \param ClassTemplate the (instantiated) class template that is partially
3099// specialized by the instantiation of \p PartialSpec.
3100///
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003101/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00003102/// specialization that we are instantiating.
3103///
Douglas Gregor869853e2010-11-10 19:44:59 +00003104/// \returns The instantiated partial specialization, if successful; otherwise,
3105/// NULL to indicate an error.
3106ClassTemplatePartialSpecializationDecl *
Douglas Gregor21610382009-10-29 00:04:11 +00003107TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
3108 ClassTemplateDecl *ClassTemplate,
3109 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor954de172009-10-31 17:21:17 +00003110 // Create a local instantiation scope for this class template partial
3111 // specialization, which will contain the instantiations of the template
3112 // parameters.
John McCall19c1bfd2010-08-25 05:32:35 +00003113 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003114
Douglas Gregor21610382009-10-29 00:04:11 +00003115 // Substitute into the template parameters of the class template partial
3116 // specialization.
3117 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3118 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3119 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00003120 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003121
Douglas Gregor21610382009-10-29 00:04:11 +00003122 // Substitute into the template arguments of the class template partial
3123 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00003124 const ASTTemplateArgumentListInfo *TemplArgInfo
3125 = PartialSpec->getTemplateArgsAsWritten();
3126 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3127 TemplArgInfo->RAngleLoc);
3128 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3129 TemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00003130 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00003131 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003132
Douglas Gregor21610382009-10-29 00:04:11 +00003133 // Check that the template argument list is well-formed for this
3134 // class template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003135 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003136 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregor21610382009-10-29 00:04:11 +00003137 PartialSpec->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003138 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00003139 false,
3140 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00003141 return nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00003142
Richard Smith57aae072016-12-28 02:37:25 +00003143 // Check these arguments are valid for a template partial specialization.
3144 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3145 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
3146 Converted))
3147 return nullptr;
3148
Douglas Gregor21610382009-10-29 00:04:11 +00003149 // Figure out where to insert this class template partial specialization
3150 // in the member template's set of class template partial specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00003151 void *InsertPos = nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00003152 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00003153 = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003154
Douglas Gregor21610382009-10-29 00:04:11 +00003155 // Build the canonical type that describes the converted template
3156 // arguments of the class template partial specialization.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003157 QualType CanonType
Douglas Gregor21610382009-10-29 00:04:11 +00003158 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
David Majnemer6fbeee32016-07-07 04:43:07 +00003159 Converted);
Douglas Gregor21610382009-10-29 00:04:11 +00003160
3161 // Build the fully-sugared type for this class template
3162 // specialization as the user wrote in the specialization
3163 // itself. This means that we'll pretty-print the type retrieved
3164 // from the specialization's declaration the way that the user
3165 // actually wrote the specialization, rather than formatting the
3166 // name based on the "canonical" representation used to store the
3167 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003168 TypeSourceInfo *WrittenTy
3169 = SemaRef.Context.getTemplateSpecializationTypeInfo(
3170 TemplateName(ClassTemplate),
3171 PartialSpec->getLocation(),
John McCall6b51f282009-11-23 01:53:49 +00003172 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00003173 CanonType);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003174
Douglas Gregor21610382009-10-29 00:04:11 +00003175 if (PrevDecl) {
3176 // We've already seen a partial specialization with the same template
3177 // parameters and template arguments. This can happen, for example, when
3178 // substituting the outer template arguments ends up causing two
3179 // class template partial specializations of a member class template
3180 // to have identical forms, e.g.,
3181 //
3182 // template<typename T, typename U>
3183 // struct Outer {
3184 // template<typename X, typename Y> struct Inner;
3185 // template<typename Y> struct Inner<T, Y>;
3186 // template<typename Y> struct Inner<U, Y>;
3187 // };
3188 //
3189 // Outer<int, int> outer; // error: the partial specializations of Inner
3190 // // have the same signature.
3191 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregor869853e2010-11-10 19:44:59 +00003192 << WrittenTy->getType();
Douglas Gregor21610382009-10-29 00:04:11 +00003193 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
3194 << SemaRef.Context.getTypeDeclType(PrevDecl);
Craig Topperc3ec1492014-05-26 06:22:03 +00003195 return nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00003196 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003197
3198
Douglas Gregor21610382009-10-29 00:04:11 +00003199 // Create the class template partial specialization declaration.
3200 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003201 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregore9029562010-05-06 00:28:52 +00003202 PartialSpec->getTagKind(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003203 Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003204 PartialSpec->getLocStart(),
3205 PartialSpec->getLocation(),
Douglas Gregor21610382009-10-29 00:04:11 +00003206 InstParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003207 ClassTemplate,
David Majnemer8b622692016-07-03 21:17:51 +00003208 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003209 InstTemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003210 CanonType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003211 nullptr);
John McCall3e11ebe2010-03-15 10:12:16 +00003212 // Substitute the nested name specifier, if any.
3213 if (SubstQualifier(PartialSpec, InstPartialSpec))
Craig Topperc3ec1492014-05-26 06:22:03 +00003214 return nullptr;
John McCall3e11ebe2010-03-15 10:12:16 +00003215
Douglas Gregor21610382009-10-29 00:04:11 +00003216 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor6044d692010-05-19 17:02:24 +00003217 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003218
Richard Smith57aae072016-12-28 02:37:25 +00003219 // Check the completed partial specialization.
3220 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3221
Douglas Gregor21610382009-10-29 00:04:11 +00003222 // Add this partial specialization to the set of class template partial
3223 // specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00003224 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
3225 /*InsertPos=*/nullptr);
Douglas Gregor869853e2010-11-10 19:44:59 +00003226 return InstPartialSpec;
Douglas Gregor21610382009-10-29 00:04:11 +00003227}
3228
Larisse Voufo39a1e502013-08-06 01:03:05 +00003229/// \brief Instantiate the declaration of a variable template partial
3230/// specialization.
3231///
3232/// \param VarTemplate the (instantiated) variable template that is partially
3233/// specialized by the instantiation of \p PartialSpec.
3234///
3235/// \param PartialSpec the (uninstantiated) variable template partial
3236/// specialization that we are instantiating.
3237///
3238/// \returns The instantiated partial specialization, if successful; otherwise,
3239/// NULL to indicate an error.
3240VarTemplatePartialSpecializationDecl *
3241TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
3242 VarTemplateDecl *VarTemplate,
3243 VarTemplatePartialSpecializationDecl *PartialSpec) {
3244 // Create a local instantiation scope for this variable template partial
3245 // specialization, which will contain the instantiations of the template
3246 // parameters.
3247 LocalInstantiationScope Scope(SemaRef);
3248
3249 // Substitute into the template parameters of the variable template partial
3250 // specialization.
3251 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3252 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3253 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00003254 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003255
3256 // Substitute into the template arguments of the variable template partial
3257 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00003258 const ASTTemplateArgumentListInfo *TemplArgInfo
3259 = PartialSpec->getTemplateArgsAsWritten();
3260 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3261 TemplArgInfo->RAngleLoc);
3262 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3263 TemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00003264 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00003265 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003266
3267 // Check that the template argument list is well-formed for this
3268 // class template.
3269 SmallVector<TemplateArgument, 4> Converted;
3270 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
3271 InstTemplateArgs, false, Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00003272 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003273
Richard Smith57aae072016-12-28 02:37:25 +00003274 // Check these arguments are valid for a template partial specialization.
3275 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3276 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
3277 Converted))
3278 return nullptr;
3279
Larisse Voufo39a1e502013-08-06 01:03:05 +00003280 // Figure out where to insert this variable template partial specialization
3281 // in the member template's set of variable template partial specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00003282 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003283 VarTemplateSpecializationDecl *PrevDecl =
Craig Topper7e0daca2014-06-26 04:58:53 +00003284 VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003285
3286 // Build the canonical type that describes the converted template
3287 // arguments of the variable template partial specialization.
3288 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00003289 TemplateName(VarTemplate), Converted);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003290
3291 // Build the fully-sugared type for this variable template
3292 // specialization as the user wrote in the specialization
3293 // itself. This means that we'll pretty-print the type retrieved
3294 // from the specialization's declaration the way that the user
3295 // actually wrote the specialization, rather than formatting the
3296 // name based on the "canonical" representation used to store the
3297 // template arguments in the specialization.
3298 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3299 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
3300 CanonType);
3301
3302 if (PrevDecl) {
3303 // We've already seen a partial specialization with the same template
3304 // parameters and template arguments. This can happen, for example, when
3305 // substituting the outer template arguments ends up causing two
3306 // variable template partial specializations of a member variable template
3307 // to have identical forms, e.g.,
3308 //
3309 // template<typename T, typename U>
3310 // struct Outer {
3311 // template<typename X, typename Y> pair<X,Y> p;
3312 // template<typename Y> pair<T, Y> p;
3313 // template<typename Y> pair<U, Y> p;
3314 // };
3315 //
3316 // Outer<int, int> outer; // error: the partial specializations of Inner
3317 // // have the same signature.
3318 SemaRef.Diag(PartialSpec->getLocation(),
3319 diag::err_var_partial_spec_redeclared)
3320 << WrittenTy->getType();
3321 SemaRef.Diag(PrevDecl->getLocation(),
3322 diag::note_var_prev_partial_spec_here);
Craig Topperc3ec1492014-05-26 06:22:03 +00003323 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003324 }
3325
3326 // Do substitution on the type of the declaration
3327 TypeSourceInfo *DI = SemaRef.SubstType(
3328 PartialSpec->getTypeSourceInfo(), TemplateArgs,
3329 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
3330 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00003331 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003332
3333 if (DI->getType()->isFunctionType()) {
3334 SemaRef.Diag(PartialSpec->getLocation(),
3335 diag::err_variable_instantiates_to_function)
3336 << PartialSpec->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003337 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003338 }
3339
3340 // Create the variable template partial specialization declaration.
3341 VarTemplatePartialSpecializationDecl *InstPartialSpec =
3342 VarTemplatePartialSpecializationDecl::Create(
3343 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
3344 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
David Majnemer8b622692016-07-03 21:17:51 +00003345 DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003346
3347 // Substitute the nested name specifier, if any.
3348 if (SubstQualifier(PartialSpec, InstPartialSpec))
Craig Topperc3ec1492014-05-26 06:22:03 +00003349 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003350
3351 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3352 InstPartialSpec->setTypeAsWritten(WrittenTy);
3353
Richard Smith57aae072016-12-28 02:37:25 +00003354 // Check the completed partial specialization.
3355 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3356
Larisse Voufo39a1e502013-08-06 01:03:05 +00003357 // Add this partial specialization to the set of variable template partial
3358 // specializations. The instantiation of the initializer is not necessary.
Craig Topperc3ec1492014-05-26 06:22:03 +00003359 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
Larisse Voufo4cda4612013-08-22 00:28:27 +00003360
Larisse Voufo4cda4612013-08-22 00:28:27 +00003361 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00003362 LateAttrs, Owner, StartingScope);
Larisse Voufo4cda4612013-08-22 00:28:27 +00003363
Larisse Voufo39a1e502013-08-06 01:03:05 +00003364 return InstPartialSpec;
3365}
3366
John McCall58f10c32010-03-11 09:03:00 +00003367TypeSourceInfo*
John McCall76d824f2009-08-25 22:02:44 +00003368TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003369 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall58f10c32010-03-11 09:03:00 +00003370 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
3371 assert(OldTInfo && "substituting function without type source info");
3372 assert(Params.empty() && "parameter vector is non-empty at start");
Craig Topperc3ec1492014-05-26 06:22:03 +00003373
3374 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00003375 unsigned ThisTypeQuals = 0;
3376 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc3d2ebb2013-06-07 02:33:37 +00003377 ThisContext = cast<CXXRecordDecl>(Owner);
Douglas Gregor3024f072012-04-16 07:05:22 +00003378 ThisTypeQuals = Method->getTypeQualifiers();
3379 }
3380
John McCallb29f78f2010-04-09 17:38:44 +00003381 TypeSourceInfo *NewTInfo
3382 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
3383 D->getTypeSpecStartLoc(),
Douglas Gregor3024f072012-04-16 07:05:22 +00003384 D->getDeclName(),
3385 ThisContext, ThisTypeQuals);
John McCall58f10c32010-03-11 09:03:00 +00003386 if (!NewTInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00003387 return nullptr;
Douglas Gregor21342092009-03-24 00:38:23 +00003388
Reid Klecknera09e44c2013-07-31 21:00:18 +00003389 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
3390 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
3391 if (NewTInfo != OldTInfo) {
3392 // Get parameters from the new type info.
Abramo Bagnaraa44c9022010-12-13 22:27:55 +00003393 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00003394 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith198223b2012-07-18 01:29:05 +00003395 unsigned NewIdx = 0;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003396 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
Douglas Gregorf3010112011-01-07 16:43:16 +00003397 OldIdx != NumOldParams; ++OldIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003398 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
Richard Smith198223b2012-07-18 01:29:05 +00003399 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
3400
David Blaikie05785d12013-02-20 22:23:23 +00003401 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith198223b2012-07-18 01:29:05 +00003402 if (OldParam->isParameterPack())
3403 NumArgumentsInExpansion =
3404 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
3405 TemplateArgs);
3406 if (!NumArgumentsInExpansion) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003407 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregorf3010112011-01-07 16:43:16 +00003408 // instantiated to a (still-dependent) parameter pack.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003409 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Douglas Gregorf3010112011-01-07 16:43:16 +00003410 Params.push_back(NewParam);
Richard Smith198223b2012-07-18 01:29:05 +00003411 Scope->InstantiatedLocal(OldParam, NewParam);
3412 } else {
3413 // Parameter pack expansion: make the instantiation an argument pack.
3414 Scope->MakeInstantiatedLocalArgPack(OldParam);
3415 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003416 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Richard Smith198223b2012-07-18 01:29:05 +00003417 Params.push_back(NewParam);
3418 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
3419 }
Douglas Gregorf3010112011-01-07 16:43:16 +00003420 }
Douglas Gregor95c70ec2010-05-03 15:32:18 +00003421 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00003422 } else {
3423 // The function type itself was not dependent and therefore no
3424 // substitution occurred. However, we still need to instantiate
3425 // the function parameters themselves.
3426 const FunctionProtoType *OldProto =
3427 cast<FunctionProtoType>(OldProtoLoc.getType());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003428 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
3429 ++i) {
3430 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
Reid Klecknera09e44c2013-07-31 21:00:18 +00003431 if (!OldParam) {
3432 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
Alp Toker9cacbab2014-01-20 20:26:09 +00003433 D, D->getLocation(), OldProto->getParamType(i)));
Reid Klecknera09e44c2013-07-31 21:00:18 +00003434 continue;
3435 }
3436
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003437 ParmVarDecl *Parm =
Reid Klecknera09e44c2013-07-31 21:00:18 +00003438 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
Douglas Gregor95c70ec2010-05-03 15:32:18 +00003439 if (!Parm)
Craig Topperc3ec1492014-05-26 06:22:03 +00003440 return nullptr;
Douglas Gregor95c70ec2010-05-03 15:32:18 +00003441 Params.push_back(Parm);
3442 }
Douglas Gregor940bca72010-04-12 07:48:19 +00003443 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00003444 } else {
3445 // If the type of this function, after ignoring parentheses, is not
3446 // *directly* a function type, then we're instantiating a function that
3447 // was declared via a typedef or with attributes, e.g.,
3448 //
3449 // typedef int functype(int, int);
3450 // functype func;
3451 // int __cdecl meth(int, int);
3452 //
3453 // In this case, we'll just go instantiate the ParmVarDecls that we
3454 // synthesized in the method declaration.
3455 SmallVector<QualType, 4> ParamTypes;
John McCallc8e321d2016-03-01 02:09:25 +00003456 Sema::ExtParameterInfoBuilder ExtParamInfos;
David Majnemer59f77922016-06-24 04:05:48 +00003457 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
3458 TemplateArgs, ParamTypes, &Params,
3459 ExtParamInfos))
Craig Topperc3ec1492014-05-26 06:22:03 +00003460 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00003461 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00003462
John McCall58f10c32010-03-11 09:03:00 +00003463 return NewTInfo;
Douglas Gregor21342092009-03-24 00:38:23 +00003464}
3465
Richard Smithf623c962012-04-17 00:58:00 +00003466/// Introduce the instantiated function parameters into the local
3467/// instantiation scope, and set the parameter names to those used
3468/// in the template.
Richard Smith2e321552014-11-12 02:00:47 +00003469static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
Richard Smithf623c962012-04-17 00:58:00 +00003470 const FunctionDecl *PatternDecl,
3471 LocalInstantiationScope &Scope,
3472 const MultiLevelTemplateArgumentList &TemplateArgs) {
3473 unsigned FParamIdx = 0;
3474 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
3475 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
3476 if (!PatternParam->isParameterPack()) {
3477 // Simple case: not a parameter pack.
3478 assert(FParamIdx < Function->getNumParams());
3479 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
Richard Smith2e321552014-11-12 02:00:47 +00003480 FunctionParam->setDeclName(PatternParam->getDeclName());
Richard Smithaae40582014-03-13 00:28:45 +00003481 // If the parameter's type is not dependent, update it to match the type
3482 // in the pattern. They can differ in top-level cv-qualifiers, and we want
3483 // the pattern's type here. If the type is dependent, they can't differ,
Richard Smith2e321552014-11-12 02:00:47 +00003484 // per core issue 1668. Substitute into the type from the pattern, in case
3485 // it's instantiation-dependent.
Richard Smithaae40582014-03-13 00:28:45 +00003486 // FIXME: Updating the type to work around this is at best fragile.
Richard Smith2e321552014-11-12 02:00:47 +00003487 if (!PatternDecl->getType()->isDependentType()) {
3488 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
3489 FunctionParam->getLocation(),
3490 FunctionParam->getDeclName());
3491 if (T.isNull())
3492 return true;
3493 FunctionParam->setType(T);
3494 }
Richard Smithaae40582014-03-13 00:28:45 +00003495
Richard Smithf623c962012-04-17 00:58:00 +00003496 Scope.InstantiatedLocal(PatternParam, FunctionParam);
3497 ++FParamIdx;
3498 continue;
3499 }
3500
3501 // Expand the parameter pack.
3502 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikie05785d12013-02-20 22:23:23 +00003503 Optional<unsigned> NumArgumentsInExpansion
Richard Smithf623c962012-04-17 00:58:00 +00003504 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith198223b2012-07-18 01:29:05 +00003505 assert(NumArgumentsInExpansion &&
3506 "should only be called when all template arguments are known");
Richard Smith2e321552014-11-12 02:00:47 +00003507 QualType PatternType =
3508 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
Richard Smith198223b2012-07-18 01:29:05 +00003509 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithf623c962012-04-17 00:58:00 +00003510 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
NAKAMURA Takumi23224152014-10-17 12:48:37 +00003511 FunctionParam->setDeclName(PatternParam->getDeclName());
Richard Smith2e321552014-11-12 02:00:47 +00003512 if (!PatternDecl->getType()->isDependentType()) {
3513 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
3514 QualType T = S.SubstType(PatternType, TemplateArgs,
3515 FunctionParam->getLocation(),
3516 FunctionParam->getDeclName());
3517 if (T.isNull())
3518 return true;
3519 FunctionParam->setType(T);
3520 }
3521
Richard Smithf623c962012-04-17 00:58:00 +00003522 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3523 ++FParamIdx;
3524 }
3525 }
Richard Smithf623c962012-04-17 00:58:00 +00003526
Richard Smith2e321552014-11-12 02:00:47 +00003527 return false;
Richard Smithf623c962012-04-17 00:58:00 +00003528}
3529
3530void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3531 FunctionDecl *Decl) {
Richard Smithd3729422012-04-19 00:08:28 +00003532 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3533 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithf623c962012-04-17 00:58:00 +00003534 return;
3535
3536 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3537 InstantiatingTemplate::ExceptionSpecification());
Alp Tokerd4a72d52013-10-08 08:09:04 +00003538 if (Inst.isInvalid()) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003539 // We hit the instantiation depth limit. Clear the exception specification
3540 // so that our callers don't have to cope with EST_Uninstantiated.
Richard Smith8acb4282014-07-31 21:57:55 +00003541 UpdateExceptionSpec(Decl, EST_None);
Richard Smithf623c962012-04-17 00:58:00 +00003542 return;
Richard Smithd3b5c9082012-07-27 04:22:15 +00003543 }
Richard Smith54f18e82016-08-31 02:15:21 +00003544 if (Inst.isAlreadyInstantiating()) {
3545 // This exception specification indirectly depends on itself. Reject.
3546 // FIXME: Corresponding rule in the standard?
3547 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
3548 UpdateExceptionSpec(Decl, EST_None);
3549 return;
3550 }
Richard Smithf623c962012-04-17 00:58:00 +00003551
3552 // Enter the scope of this instantiation. We don't use
3553 // PushDeclContext because we don't have a scope.
3554 Sema::ContextRAII savedContext(*this, Decl);
3555 LocalInstantiationScope Scope(*this);
3556
3557 MultiLevelTemplateArgumentList TemplateArgs =
Craig Topperc3ec1492014-05-26 06:22:03 +00003558 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
Richard Smithf623c962012-04-17 00:58:00 +00003559
Richard Smithd3729422012-04-19 00:08:28 +00003560 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
Richard Smith2e321552014-11-12 02:00:47 +00003561 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
3562 TemplateArgs)) {
3563 UpdateExceptionSpec(Decl, EST_None);
3564 return;
3565 }
Richard Smithf623c962012-04-17 00:58:00 +00003566
Richard Smith2e321552014-11-12 02:00:47 +00003567 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
3568 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003569}
3570
Mike Stump11289f42009-09-09 15:08:12 +00003571/// \brief Initializes the common fields of an instantiation function
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003572/// declaration (New) from the corresponding fields of its template (Tmpl).
3573///
3574/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003575bool
3576TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003577 FunctionDecl *Tmpl) {
David Blaikie5a0956e2012-07-16 18:50:45 +00003578 if (Tmpl->isDeleted())
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003579 New->setDeletedAsWritten();
Mike Stump11289f42009-09-09 15:08:12 +00003580
Richard Smith32918772017-02-14 00:25:28 +00003581 New->setImplicit(Tmpl->isImplicit());
3582
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003583 // Forward the mangling number from the template to the instantiated decl.
3584 SemaRef.Context.setManglingNumber(New,
3585 SemaRef.Context.getManglingNumber(Tmpl));
3586
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003587 // If we are performing substituting explicitly-specified template arguments
3588 // or deduced template arguments into a function template and we reach this
3589 // point, we are now past the point where SFINAE applies and have committed
Mike Stump11289f42009-09-09 15:08:12 +00003590 // to keeping the new function template specialization. We therefore
3591 // convert the active template instantiation for the function template
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003592 // into a template instantiation for this specific function template
3593 // specialization, which is not a SFINAE context, so that we diagnose any
3594 // further errors in the declaration itself.
Richard Smith696e3122017-02-23 01:43:54 +00003595 typedef Sema::CodeSynthesisContext ActiveInstType;
3596 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003597 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3598 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump11289f42009-09-09 15:08:12 +00003599 if (FunctionTemplateDecl *FunTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003600 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump11289f42009-09-09 15:08:12 +00003601 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003602 "Deduction from the wrong function template?");
Daniel Dunbar54c59642009-07-16 22:10:11 +00003603 (void) FunTmpl;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003604 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003605 ActiveInst.Entity = New;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003606 }
3607 }
Mike Stump11289f42009-09-09 15:08:12 +00003608
Douglas Gregor049bdca2009-12-08 17:45:32 +00003609 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3610 assert(Proto && "Function template without prototype?");
3611
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003612 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalldb40c7f2010-12-14 08:05:40 +00003613 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003614
Richard Smithf623c962012-04-17 00:58:00 +00003615 // DR1330: In C++11, defer instantiation of a non-trivial
3616 // exception specification.
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003617 // DR1484: Local classes and their members are instantiated along with the
3618 // containing function.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003619 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smith8acb4282014-07-31 21:57:55 +00003620 EPI.ExceptionSpec.Type != EST_None &&
3621 EPI.ExceptionSpec.Type != EST_DynamicNone &&
Serge Pavlov3739f5e72015-06-29 17:50:19 +00003622 EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
Serge Pavlov73c6a242015-08-23 10:22:28 +00003623 !Tmpl->isLexicallyWithinFunctionOrMethod()) {
Richard Smithd3729422012-04-19 00:08:28 +00003624 FunctionDecl *ExceptionSpecTemplate = Tmpl;
Richard Smith8acb4282014-07-31 21:57:55 +00003625 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
3626 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
Richard Smith185be182013-04-10 05:48:59 +00003627 ExceptionSpecificationType NewEST = EST_Uninstantiated;
Richard Smith8acb4282014-07-31 21:57:55 +00003628 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
Richard Smith185be182013-04-10 05:48:59 +00003629 NewEST = EST_Unevaluated;
Richard Smithd3729422012-04-19 00:08:28 +00003630
Richard Smithf623c962012-04-17 00:58:00 +00003631 // Mark the function has having an uninstantiated exception specification.
3632 const FunctionProtoType *NewProto
3633 = New->getType()->getAs<FunctionProtoType>();
3634 assert(NewProto && "Template instantiation without function prototype?");
3635 EPI = NewProto->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00003636 EPI.ExceptionSpec.Type = NewEST;
3637 EPI.ExceptionSpec.SourceDecl = New;
3638 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
Reid Kleckner896b32f2013-06-10 20:51:09 +00003639 New->setType(SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003640 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00003641 } else {
Richard Smith2e321552014-11-12 02:00:47 +00003642 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003643 }
Douglas Gregor049bdca2009-12-08 17:45:32 +00003644 }
3645
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003646 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithf623c962012-04-17 00:58:00 +00003647 const FunctionDecl *Definition = Tmpl;
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003648 Tmpl->isDefined(Definition);
3649
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00003650 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3651 LateAttrs, StartingScope);
Douglas Gregor08329632010-06-15 17:05:35 +00003652
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003653 return false;
3654}
3655
Douglas Gregor21342092009-03-24 00:38:23 +00003656/// \brief Initializes common fields of an instantiated method
3657/// declaration (New) from the corresponding fields of its template
3658/// (Tmpl).
3659///
3660/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003661bool
3662TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor21342092009-03-24 00:38:23 +00003663 CXXMethodDecl *Tmpl) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003664 if (InitFunctionInstantiation(New, Tmpl))
3665 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003666
Douglas Gregor21342092009-03-24 00:38:23 +00003667 New->setAccess(Tmpl->getAccess());
Fariborz Jahanian6dfc1972009-12-03 18:44:40 +00003668 if (Tmpl->isVirtualAsWritten())
Douglas Gregor11c024b2010-09-28 20:50:54 +00003669 New->setVirtualAsWritten(true);
Douglas Gregor21342092009-03-24 00:38:23 +00003670
Douglas Gregor21342092009-03-24 00:38:23 +00003671 // FIXME: New needs a pointer to Tmpl
3672 return false;
3673}
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003674
Reid Kleckner61195e12017-01-05 01:08:22 +00003675/// In the MS ABI, we need to instantiate default arguments of dllexported
3676/// default constructors along with the constructor definition. This allows IR
3677/// gen to emit a constructor closure which calls the default constructor with
3678/// its default arguments.
3679static void InstantiateDefaultCtorDefaultArgs(Sema &S,
3680 CXXConstructorDecl *Ctor) {
3681 assert(S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3682 Ctor->isDefaultConstructor());
3683 unsigned NumParams = Ctor->getNumParams();
3684 if (NumParams == 0)
3685 return;
3686 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
3687 if (!Attr)
3688 return;
3689 for (unsigned I = 0; I != NumParams; ++I) {
3690 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
3691 Ctor->getParamDecl(I));
3692 S.DiscardCleanupsInEvaluationContext();
3693 }
3694}
3695
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003696/// \brief Instantiate the definition of the given function from its
3697/// template.
3698///
Douglas Gregordda7ced2009-06-30 17:20:14 +00003699/// \param PointOfInstantiation the point at which the instantiation was
3700/// required. Note that this is not precisely a "point of instantiation"
3701/// for the function, but it's close.
3702///
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003703/// \param Function the already-instantiated declaration of a
Douglas Gregordda7ced2009-06-30 17:20:14 +00003704/// function template specialization or member function of a class template
3705/// specialization.
3706///
3707/// \param Recursive if true, recursively instantiates any functions that
3708/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003709///
3710/// \param DefinitionRequired if true, then we are performing an explicit
3711/// instantiation where the body of the function is required. Complain if
3712/// there is no such body.
Douglas Gregor85673582009-05-18 17:01:57 +00003713void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregordda7ced2009-06-30 17:20:14 +00003714 FunctionDecl *Function,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003715 bool Recursive,
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00003716 bool DefinitionRequired,
3717 bool AtEndOfTU) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003718 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregorb4850462009-05-14 23:26:13 +00003719 return;
3720
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003721 // Never instantiate an explicit specialization except if it is a class scope
3722 // explicit specialization.
Vassil Vassilevb21ee082016-08-18 22:01:25 +00003723 TemplateSpecializationKind TSK = Function->getTemplateSpecializationKind();
3724 if (TSK == TSK_ExplicitSpecialization &&
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003725 !Function->getClassScopeSpecializationPattern())
Douglas Gregor86d142a2009-10-08 07:24:58 +00003726 return;
Douglas Gregor69f6a362010-05-17 17:34:56 +00003727
Douglas Gregor24c332b2009-05-14 21:06:31 +00003728 // Find the function body that we'll be substituting.
Douglas Gregorafca3b42009-10-27 20:53:28 +00003729 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Alexis Hunt23f6b832011-05-27 20:00:14 +00003730 assert(PatternDecl && "instantiating a non-template");
3731
Richard Smith6f4e2e02016-08-23 19:41:39 +00003732 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
Richard Smith3f6865a82016-08-23 21:12:54 +00003733 Stmt *Pattern = nullptr;
3734 if (PatternDef) {
3735 Pattern = PatternDef->getBody(PatternDef);
Richard Smith6f4e2e02016-08-23 19:41:39 +00003736 PatternDecl = PatternDef;
Richard Smith3f6865a82016-08-23 21:12:54 +00003737 }
Douglas Gregor24c332b2009-05-14 21:06:31 +00003738
Vassil Vassilevb21ee082016-08-18 22:01:25 +00003739 // FIXME: We need to track the instantiation stack in order to know which
3740 // definitions should be visible within this instantiation.
3741 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
3742 Function->getInstantiatedFromMemberFunction(),
Richard Smith6f4e2e02016-08-23 19:41:39 +00003743 PatternDecl, PatternDef, TSK,
3744 /*Complain*/DefinitionRequired)) {
3745 if (DefinitionRequired)
3746 Function->setInvalidDecl();
3747 else if (TSK == TSK_ExplicitInstantiationDefinition) {
3748 // Try again at the end of the translation unit (at which point a
3749 // definition will be required).
3750 assert(!Recursive);
3751 PendingInstantiations.push_back(
3752 std::make_pair(Function, PointOfInstantiation));
3753 } else if (TSK == TSK_ImplicitInstantiation) {
Richard Smith152bcd22017-01-28 02:56:07 +00003754 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred()) {
Richard Smith6f4e2e02016-08-23 19:41:39 +00003755 Diag(PointOfInstantiation, diag::warn_func_template_missing)
3756 << Function;
3757 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
3758 if (getLangOpts().CPlusPlus11)
3759 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
3760 << Function;
3761 }
3762 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +00003763
Richard Smith6f4e2e02016-08-23 19:41:39 +00003764 return;
3765 }
Vassil Vassilevb21ee082016-08-18 22:01:25 +00003766
Francois Pichet1c229c02011-04-22 22:18:13 +00003767 // Postpone late parsed template instantiations.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003768 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky610128e2011-05-12 03:51:24 +00003769 !LateTemplateParser) {
Francois Pichet1c229c02011-04-22 22:18:13 +00003770 PendingInstantiations.push_back(
3771 std::make_pair(Function, PointOfInstantiation));
3772 return;
3773 }
3774
Nico Weberae4bb8c2014-08-15 23:21:41 +00003775 // If we're performing recursive template instantiation, create our own
3776 // queue of pending implicit instantiations that we will instantiate later,
3777 // while we're still within our own instantiation context.
3778 // This has to happen before LateTemplateParser below is called, so that
3779 // it marks vtables used in late parsed templates as used.
3780 SavePendingLocalImplicitInstantiationsRAII
3781 SavedPendingLocalImplicitInstantiations(*this);
Nico Weber7a92e1a2015-01-18 01:50:35 +00003782 SavePendingInstantiationsAndVTableUsesRAII
3783 SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
Nico Weberae4bb8c2014-08-15 23:21:41 +00003784
David Majnemerf0a84f22013-08-16 08:29:13 +00003785 // Call the LateTemplateParser callback if there is a need to late parse
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003786 // a templated function definition.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003787 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet1c229c02011-04-22 22:18:13 +00003788 LateTemplateParser) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00003789 // FIXME: Optimize to allow individual templates to be deserialized.
3790 if (PatternDecl->isFromASTFile())
3791 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3792
Justin Lebar28f09c52016-10-10 16:26:08 +00003793 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
3794 assert(LPTIter != LateParsedTemplateMap.end() &&
3795 "missing LateParsedTemplate");
3796 LateTemplateParser(OpaqueParser, *LPTIter->second);
Francois Pichet1c229c02011-04-22 22:18:13 +00003797 Pattern = PatternDecl->getBody(PatternDecl);
3798 }
3799
Richard Smith6f4e2e02016-08-23 19:41:39 +00003800 // Note, we should never try to instantiate a deleted function template.
3801 assert((Pattern || PatternDecl->isDefaulted()) &&
3802 "unexpected kind of function template definition");
Douglas Gregor24c332b2009-05-14 21:06:31 +00003803
Richard Smith2a7d4812013-05-04 07:00:32 +00003804 // C++1y [temp.explicit]p10:
3805 // Except for inline functions, declarations with types deduced from their
3806 // initializer or return value, and class template specializations, other
3807 // explicit instantiation declarations have the effect of suppressing the
3808 // implicit instantiation of the entity to which they refer.
Vassil Vassilevb21ee082016-08-18 22:01:25 +00003809 if (TSK == TSK_ExplicitInstantiationDeclaration &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003810 !PatternDecl->isInlined() &&
Alp Toker314cc812014-01-25 16:55:45 +00003811 !PatternDecl->getReturnType()->getContainedAutoType())
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003812 return;
Mike Stump11289f42009-09-09 15:08:12 +00003813
Richard Smith195d8ef2014-05-29 03:15:31 +00003814 if (PatternDecl->isInlined()) {
3815 // Function, and all later redeclarations of it (from imported modules,
3816 // for instance), are now implicitly inline.
3817 for (auto *D = Function->getMostRecentDecl(); /**/;
3818 D = D->getPreviousDecl()) {
3819 D->setImplicitlyInline();
3820 if (D == Function)
3821 break;
3822 }
3823 }
Richard Smithf3814ad2013-01-25 00:08:28 +00003824
Douglas Gregor85673582009-05-18 17:01:57 +00003825 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
Richard Smith54f18e82016-08-31 02:15:21 +00003826 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003827 return;
Richard Smithe19b95d2016-05-26 20:23:13 +00003828 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3829 "instantiating function definition");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003830
Vassil Vassilevb21ee082016-08-18 22:01:25 +00003831 // The instantiation is visible here, even if it was first declared in an
3832 // unimported module.
3833 Function->setHidden(false);
3834
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00003835 // Copy the inner loc start from the pattern.
3836 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3837
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003838 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00003839 Sema::PotentiallyEvaluated);
Douglas Gregor67da0d92009-05-15 17:59:04 +00003840
Douglas Gregorb4850462009-05-14 23:26:13 +00003841 // Introduce a new scope where local variable instantiations will be
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003842 // recorded, unless we're actually a member function within a local
3843 // class, in which case we need to merge our results with the parent
3844 // scope (of the enclosing function).
3845 bool MergeWithParentScope = false;
3846 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3847 MergeWithParentScope = Rec->isLocalClass();
3848
3849 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00003850
Richard Smithbd305122012-12-11 01:14:52 +00003851 if (PatternDecl->isDefaulted())
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003852 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smithbd305122012-12-11 01:14:52 +00003853 else {
Richard Smithcc928662014-10-17 20:37:29 +00003854 MultiLevelTemplateArgumentList TemplateArgs =
3855 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
3856
3857 // Substitute into the qualifier; we can get a substitution failure here
3858 // through evil use of alias templates.
3859 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
3860 // of the) lexical context of the pattern?
3861 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
3862
Craig Topperc3ec1492014-05-26 06:22:03 +00003863 ActOnStartOfFunctionDef(nullptr, Function);
Richard Smithbd305122012-12-11 01:14:52 +00003864
3865 // Enter the scope of this instantiation. We don't use
3866 // PushDeclContext because we don't have a scope.
3867 Sema::ContextRAII savedContext(*this, Function);
3868
Richard Smith2e321552014-11-12 02:00:47 +00003869 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3870 TemplateArgs))
3871 return;
Richard Smithbd305122012-12-11 01:14:52 +00003872
Reid Kleckner61195e12017-01-05 01:08:22 +00003873 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
3874 // If this is a constructor, instantiate the member initializers.
3875 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003876 TemplateArgs);
Reid Kleckner61195e12017-01-05 01:08:22 +00003877
3878 // If this is an MS ABI dllexport default constructor, instantiate any
3879 // default arguments.
3880 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3881 Ctor->isDefaultConstructor()) {
3882 InstantiateDefaultCtorDefaultArgs(*this, Ctor);
3883 }
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003884 }
3885
3886 // Instantiate the function body.
3887 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3888
3889 if (Body.isInvalid())
3890 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003891
Tim Shenb34d0ef2017-02-14 23:46:37 +00003892 // FIXME: finishing the function body while in an expression evaluation
3893 // context seems wrong. Investigate more.
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003894 ActOnFinishFunctionBody(Function, Body.get(),
3895 /*IsInstantiation=*/true);
Richard Smithbd305122012-12-11 01:14:52 +00003896
3897 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3898
Richard Smithd28ac5b2014-03-22 23:33:22 +00003899 if (auto *Listener = getASTMutationListener())
3900 Listener->FunctionDefinitionInstantiated(Function);
Richard Smith0ac1b8f2014-03-22 01:43:32 +00003901
Richard Smithbd305122012-12-11 01:14:52 +00003902 savedContext.pop();
Mike Stump11289f42009-09-09 15:08:12 +00003903 }
3904
Douglas Gregor28ad4b52009-05-26 20:50:29 +00003905 DeclGroupRef DG(Function);
3906 Consumer.HandleTopLevelDecl(DG);
Mike Stump11289f42009-09-09 15:08:12 +00003907
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003908 // This class may have local implicit instantiations that need to be
3909 // instantiation within this scope.
Chandler Carruth54080172010-08-25 08:44:16 +00003910 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003911 Scope.Exit();
3912
Douglas Gregordda7ced2009-06-30 17:20:14 +00003913 if (Recursive) {
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003914 // Define any pending vtables.
3915 DefineUsedVTables();
3916
Douglas Gregordda7ced2009-06-30 17:20:14 +00003917 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003918 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003919 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003920
Nico Weber7a92e1a2015-01-18 01:50:35 +00003921 // PendingInstantiations and VTableUses are restored through
3922 // SavePendingInstantiationsAndVTableUses's destructor.
Douglas Gregordda7ced2009-06-30 17:20:14 +00003923 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003924}
3925
Larisse Voufo39a1e502013-08-06 01:03:05 +00003926VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3927 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3928 const TemplateArgumentList &TemplateArgList,
3929 const TemplateArgumentListInfo &TemplateArgsInfo,
3930 SmallVectorImpl<TemplateArgument> &Converted,
3931 SourceLocation PointOfInstantiation, void *InsertPos,
3932 LateInstantiatedAttrVec *LateAttrs,
3933 LocalInstantiationScope *StartingScope) {
3934 if (FromVar->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00003935 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003936
3937 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003938 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003939 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003940
3941 MultiLevelTemplateArgumentList TemplateArgLists;
3942 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3943
Richard Smith8809a0c2013-09-27 20:14:12 +00003944 // Instantiate the first declaration of the variable template: for a partial
3945 // specialization of a static data member template, the first declaration may
3946 // or may not be the declaration in the class; if it's in the class, we want
3947 // to instantiate a member in the class (a declaration), and if it's outside,
3948 // we want to instantiate a definition.
Richard Smithbeef3452014-01-16 23:39:20 +00003949 //
3950 // If we're instantiating an explicitly-specialized member template or member
3951 // partial specialization, don't do this. The member specialization completely
3952 // replaces the original declaration in this case.
3953 bool IsMemberSpec = false;
3954 if (VarTemplatePartialSpecializationDecl *PartialSpec =
3955 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
3956 IsMemberSpec = PartialSpec->isMemberSpecialization();
3957 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
3958 IsMemberSpec = FromTemplate->isMemberSpecialization();
3959 if (!IsMemberSpec)
3960 FromVar = FromVar->getFirstDecl();
Richard Smith8809a0c2013-09-27 20:14:12 +00003961
Manuel Klimek5843add2013-09-30 13:29:01 +00003962 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3963 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3964 MultiLevelList);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003965
3966 // TODO: Set LateAttrs and StartingScope ...
3967
3968 return cast_or_null<VarTemplateSpecializationDecl>(
3969 Instantiator.VisitVarTemplateSpecializationDecl(
3970 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3971}
3972
3973/// \brief Instantiates a variable template specialization by completing it
3974/// with appropriate type information and initializer.
3975VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3976 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3977 const MultiLevelTemplateArgumentList &TemplateArgs) {
3978
3979 // Do substitution on the type of the declaration
3980 TypeSourceInfo *DI =
Richard Smith8809a0c2013-09-27 20:14:12 +00003981 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00003982 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3983 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00003984 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003985
3986 // Update the type of this variable template specialization.
3987 VarSpec->setType(DI->getType());
3988
3989 // Instantiate the initializer.
3990 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3991
3992 return VarSpec;
3993}
3994
3995/// BuildVariableInstantiation - Used after a new variable has been created.
3996/// Sets basic variable data and decides whether to postpone the
3997/// variable instantiation.
3998void Sema::BuildVariableInstantiation(
3999 VarDecl *NewVar, VarDecl *OldVar,
4000 const MultiLevelTemplateArgumentList &TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00004001 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
4002 LocalInstantiationScope *StartingScope,
Larisse Voufo72caf2b2013-08-22 00:59:14 +00004003 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004004
Richard Smith541b38b2013-09-20 01:15:31 +00004005 // If we are instantiating a local extern declaration, the
4006 // instantiation belongs lexically to the containing function.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004007 // If we are instantiating a static data member defined
4008 // out-of-line, the instantiation will have the same lexical
4009 // context (which will be a namespace scope) as the template.
Richard Smith541b38b2013-09-20 01:15:31 +00004010 if (OldVar->isLocalExternDecl()) {
4011 NewVar->setLocalExternDecl();
4012 NewVar->setLexicalDeclContext(Owner);
4013 } else if (OldVar->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00004014 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
4015 NewVar->setTSCSpec(OldVar->getTSCSpec());
4016 NewVar->setInitStyle(OldVar->getInitStyle());
4017 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
4018 NewVar->setConstexpr(OldVar->isConstexpr());
Richard Smithbb13c9a2013-09-28 04:02:39 +00004019 NewVar->setInitCapture(OldVar->isInitCapture());
Richard Smith1c34fb72013-08-13 18:18:50 +00004020 NewVar->setPreviousDeclInSameBlockScope(
4021 OldVar->isPreviousDeclInSameBlockScope());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004022 NewVar->setAccess(OldVar->getAccess());
4023
Richard Smith0b551192013-09-23 23:12:22 +00004024 if (!OldVar->isStaticDataMember()) {
Rafael Espindolae4865d22013-10-23 16:46:34 +00004025 if (OldVar->isUsed(false))
4026 NewVar->setIsUsed();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004027 NewVar->setReferenced(OldVar->isReferenced());
4028 }
4029
4030 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
4031
Richard Smith541b38b2013-09-20 01:15:31 +00004032 LookupResult Previous(
4033 *this, NewVar->getDeclName(), NewVar->getLocation(),
4034 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
4035 : Sema::LookupOrdinaryName,
4036 Sema::ForRedeclaration);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004037
Argyrios Kyrtzidis91486222013-11-27 08:34:14 +00004038 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
4039 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
4040 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
Richard Smith1c34fb72013-08-13 18:18:50 +00004041 // We have a previous declaration. Use that one, so we merge with the
4042 // right type.
4043 if (NamedDecl *NewPrev = FindInstantiatedDecl(
4044 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
4045 Previous.addDecl(NewPrev);
4046 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
4047 OldVar->hasLinkage())
Larisse Voufo39a1e502013-08-06 01:03:05 +00004048 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00004049 CheckVariableDeclaration(NewVar, Previous);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004050
Richard Smith541b38b2013-09-20 01:15:31 +00004051 if (!InstantiatingVarTemplate) {
4052 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
4053 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
Larisse Voufo39a1e502013-08-06 01:03:05 +00004054 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
Richard Smith541b38b2013-09-20 01:15:31 +00004055 }
4056
4057 if (!OldVar->isOutOfLine()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004058 if (NewVar->getDeclContext()->isFunctionOrMethod())
4059 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
4060 }
4061
4062 // Link instantiations of static data members back to the template from
4063 // which they were instantiated.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00004064 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
Larisse Voufo39a1e502013-08-06 01:03:05 +00004065 NewVar->setInstantiationOfStaticDataMember(OldVar,
4066 TSK_ImplicitInstantiation);
4067
David Majnemerdbc0c8f2013-12-04 09:01:55 +00004068 // Forward the mangling number from the template to the instantiated decl.
4069 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
David Majnemer2206bf52014-03-05 08:57:59 +00004070 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
David Majnemerdbc0c8f2013-12-04 09:01:55 +00004071
Richard Smith62f19e72016-06-25 00:15:56 +00004072 // Delay instantiation of the initializer for variable templates or inline
4073 // static data members until a definition of the variable is needed. We need
4074 // it right away if the type contains 'auto'.
Richard Smithd292b242014-03-16 01:00:40 +00004075 if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
Richard Smith62f19e72016-06-25 00:15:56 +00004076 !InstantiatingVarTemplate &&
4077 !(OldVar->isInline() && OldVar->isThisDeclarationADefinition())) ||
Richard Smithd292b242014-03-16 01:00:40 +00004078 NewVar->getType()->isUndeducedType())
Larisse Voufo39a1e502013-08-06 01:03:05 +00004079 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
4080
4081 // Diagnose unused local variables with dependent types, where the diagnostic
4082 // will have been deferred.
4083 if (!NewVar->isInvalidDecl() &&
Nico Weber72889432014-09-06 01:25:55 +00004084 NewVar->getDeclContext()->isFunctionOrMethod() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004085 OldVar->getType()->isDependentType())
4086 DiagnoseUnusedDecl(NewVar);
4087}
4088
4089/// \brief Instantiate the initializer of a variable.
4090void Sema::InstantiateVariableInitializer(
4091 VarDecl *Var, VarDecl *OldVar,
4092 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smith62f19e72016-06-25 00:15:56 +00004093 // We propagate the 'inline' flag with the initializer, because it
4094 // would otherwise imply that the variable is a definition for a
4095 // non-static data member.
4096 if (OldVar->isInlineSpecified())
4097 Var->setInlineSpecified();
4098 else if (OldVar->isInline())
4099 Var->setImplicitlyInline();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004100
Larisse Voufo39a1e502013-08-06 01:03:05 +00004101 if (OldVar->getInit()) {
4102 if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
4103 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
4104 else
4105 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
4106
4107 // Instantiate the initializer.
Akira Hatanakab87faff2016-04-28 23:50:12 +00004108 ExprResult Init;
4109
4110 {
4111 ContextRAII SwitchContext(*this, Var->getDeclContext());
4112 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
4113 OldVar->getInitStyle() == VarDecl::CallInit);
4114 }
4115
Larisse Voufo39a1e502013-08-06 01:03:05 +00004116 if (!Init.isInvalid()) {
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00004117 Expr *InitExpr = Init.get();
4118
Richard Smith95b83e92014-07-10 20:53:43 +00004119 if (Var->hasAttr<DLLImportAttr>() &&
4120 (!InitExpr ||
4121 !InitExpr->isConstantInitializer(getASTContext(), false))) {
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00004122 // Do not dynamically initialize dllimport variables.
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00004123 } else if (InitExpr) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004124 bool DirectInit = OldVar->isDirectInit();
Richard Smith3beb7c62017-01-12 02:27:38 +00004125 AddInitializerToDecl(Var, InitExpr, DirectInit);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004126 } else
Richard Smith3beb7c62017-01-12 02:27:38 +00004127 ActOnUninitializedDecl(Var);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004128 } else {
4129 // FIXME: Not too happy about invalidating the declaration
4130 // because of a bogus initializer.
4131 Var->setInvalidDecl();
4132 }
4133
4134 PopExpressionEvaluationContext();
Richard Smith54f18e82016-08-31 02:15:21 +00004135 } else {
4136 if (Var->isStaticDataMember()) {
4137 if (!Var->isOutOfLine())
4138 return;
4139
4140 // If the declaration inside the class had an initializer, don't add
4141 // another one to the out-of-line definition.
4142 if (OldVar->getFirstDecl()->hasInit())
4143 return;
4144 }
4145
4146 // We'll add an initializer to a for-range declaration later.
4147 if (Var->isCXXForRangeDecl())
4148 return;
4149
Richard Smith3beb7c62017-01-12 02:27:38 +00004150 ActOnUninitializedDecl(Var);
Richard Smith54f18e82016-08-31 02:15:21 +00004151 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004152}
4153
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004154/// \brief Instantiate the definition of the given variable from its
4155/// template.
4156///
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004157/// \param PointOfInstantiation the point at which the instantiation was
4158/// required. Note that this is not precisely a "point of instantiation"
4159/// for the function, but it's close.
4160///
4161/// \param Var the already-instantiated declaration of a static member
4162/// variable of a class template specialization.
4163///
4164/// \param Recursive if true, recursively instantiates any functions that
4165/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00004166///
4167/// \param DefinitionRequired if true, then we are performing an explicit
4168/// instantiation where an out-of-line definition of the member variable
4169/// is required. Complain if there is no such definition.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004170void Sema::InstantiateStaticDataMemberDefinition(
4171 SourceLocation PointOfInstantiation,
4172 VarDecl *Var,
Douglas Gregora8b89d22009-10-15 14:05:49 +00004173 bool Recursive,
4174 bool DefinitionRequired) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004175 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
4176 DefinitionRequired);
4177}
4178
4179void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
4180 VarDecl *Var, bool Recursive,
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00004181 bool DefinitionRequired, bool AtEndOfTU) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004182 if (Var->isInvalidDecl())
4183 return;
Mike Stump11289f42009-09-09 15:08:12 +00004184
Larisse Voufo39a1e502013-08-06 01:03:05 +00004185 VarTemplateSpecializationDecl *VarSpec =
4186 dyn_cast<VarTemplateSpecializationDecl>(Var);
Craig Topperc3ec1492014-05-26 06:22:03 +00004187 VarDecl *PatternDecl = nullptr, *Def = nullptr;
Richard Smith8809a0c2013-09-27 20:14:12 +00004188 MultiLevelTemplateArgumentList TemplateArgs =
4189 getTemplateInstantiationArgs(Var);
Mike Stump11289f42009-09-09 15:08:12 +00004190
Larisse Voufo39a1e502013-08-06 01:03:05 +00004191 if (VarSpec) {
Richard Smith8809a0c2013-09-27 20:14:12 +00004192 // If this is a variable template specialization, make sure that it is
4193 // non-dependent, then find its instantiation pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004194 bool InstantiationDependent = false;
4195 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
4196 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
4197 "Only instantiate variable template specializations that are "
4198 "not type-dependent");
Larisse Voufo4154f462013-08-06 03:57:41 +00004199 (void)InstantiationDependent;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004200
Richard Smith8809a0c2013-09-27 20:14:12 +00004201 // Find the variable initialization that we'll be substituting. If the
4202 // pattern was instantiated from a member template, look back further to
4203 // find the real pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004204 assert(VarSpec->getSpecializedTemplate() &&
4205 "Specialization without specialized template?");
4206 llvm::PointerUnion<VarTemplateDecl *,
4207 VarTemplatePartialSpecializationDecl *> PatternPtr =
4208 VarSpec->getSpecializedTemplateOrPartial();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00004209 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00004210 VarTemplatePartialSpecializationDecl *Tmpl =
4211 PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
4212 while (VarTemplatePartialSpecializationDecl *From =
4213 Tmpl->getInstantiatedFromMember()) {
4214 if (Tmpl->isMemberSpecialization())
4215 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00004216
Richard Smith8809a0c2013-09-27 20:14:12 +00004217 Tmpl = From;
4218 }
4219 PatternDecl = Tmpl;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00004220 } else {
Richard Smith8809a0c2013-09-27 20:14:12 +00004221 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
4222 while (VarTemplateDecl *From =
4223 Tmpl->getInstantiatedFromMemberTemplate()) {
4224 if (Tmpl->isMemberSpecialization())
4225 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00004226
Richard Smith8809a0c2013-09-27 20:14:12 +00004227 Tmpl = From;
4228 }
4229 PatternDecl = Tmpl->getTemplatedDecl();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00004230 }
Richard Smith8809a0c2013-09-27 20:14:12 +00004231
4232 // If this is a static data member template, there might be an
4233 // uninstantiated initializer on the declaration. If so, instantiate
4234 // it now.
4235 if (PatternDecl->isStaticDataMember() &&
Rafael Espindola8db352d2013-10-17 15:37:26 +00004236 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
Richard Smith8809a0c2013-09-27 20:14:12 +00004237 !Var->hasInit()) {
4238 // FIXME: Factor out the duplicated instantiation context setup/tear down
4239 // code here.
4240 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Richard Smith54f18e82016-08-31 02:15:21 +00004241 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
Richard Smith8809a0c2013-09-27 20:14:12 +00004242 return;
Richard Smithe19b95d2016-05-26 20:23:13 +00004243 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4244 "instantiating variable initializer");
Richard Smith8809a0c2013-09-27 20:14:12 +00004245
Richard Smithedbc6e92016-10-14 21:41:24 +00004246 // The instantiation is visible here, even if it was first declared in an
4247 // unimported module.
4248 Var->setHidden(false);
4249
Richard Smith8809a0c2013-09-27 20:14:12 +00004250 // If we're performing recursive template instantiation, create our own
4251 // queue of pending implicit instantiations that we will instantiate
4252 // later, while we're still within our own instantiation context.
Nico Weber7a92e1a2015-01-18 01:50:35 +00004253 SavePendingInstantiationsAndVTableUsesRAII
4254 SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
Richard Smith8809a0c2013-09-27 20:14:12 +00004255
4256 LocalInstantiationScope Local(*this);
4257
4258 // Enter the scope of this instantiation. We don't use
4259 // PushDeclContext because we don't have a scope.
4260 ContextRAII PreviousContext(*this, Var->getDeclContext());
4261 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
4262 PreviousContext.pop();
4263
4264 // FIXME: Need to inform the ASTConsumer that we instantiated the
4265 // initializer?
4266
4267 // This variable may have local implicit instantiations that need to be
4268 // instantiated within this scope.
4269 PerformPendingInstantiations(/*LocalOnly=*/true);
4270
4271 Local.Exit();
4272
4273 if (Recursive) {
4274 // Define any newly required vtables.
4275 DefineUsedVTables();
4276
4277 // Instantiate any pending implicit instantiations found during the
4278 // instantiation of this template.
4279 PerformPendingInstantiations();
4280
Nico Weber7a92e1a2015-01-18 01:50:35 +00004281 // PendingInstantiations and VTableUses are restored through
4282 // SavePendingInstantiationsAndVTableUses's destructor.
Richard Smith8809a0c2013-09-27 20:14:12 +00004283 }
4284 }
4285
4286 // Find actual definition
4287 Def = PatternDecl->getDefinition(getASTContext());
4288 } else {
4289 // If this is a static data member, find its out-of-line definition.
4290 assert(Var->isStaticDataMember() && "not a static data member?");
4291 PatternDecl = Var->getInstantiatedFromStaticDataMember();
4292
4293 assert(PatternDecl && "data member was not instantiated from a template?");
4294 assert(PatternDecl->isStaticDataMember() && "not a static data member?");
Richard Smith62f19e72016-06-25 00:15:56 +00004295 Def = PatternDecl->getDefinition();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004296 }
4297
Richard Smithedbc6e92016-10-14 21:41:24 +00004298 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
Richard Smith6739a102016-05-05 00:56:12 +00004299
Richard Smith8809a0c2013-09-27 20:14:12 +00004300 // If we don't have a definition of the variable template, we won't perform
4301 // any instantiation. Rather, we rely on the user to instantiate this
4302 // definition (or provide a specialization for it) in another translation
4303 // unit.
Richard Smithedbc6e92016-10-14 21:41:24 +00004304 if (!Def && !DefinitionRequired) {
4305 if (TSK == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00004306 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004307 std::make_pair(Var, PointOfInstantiation));
Richard Smithedbc6e92016-10-14 21:41:24 +00004308 } else if (TSK == TSK_ImplicitInstantiation) {
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00004309 // Warn about missing definition at the end of translation unit.
4310 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred()) {
4311 Diag(PointOfInstantiation, diag::warn_var_template_missing)
4312 << Var;
4313 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4314 if (getLangOpts().CPlusPlus11)
4315 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
4316 }
Richard Smithedbc6e92016-10-14 21:41:24 +00004317 return;
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004318 }
4319
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004320 }
4321
Richard Smithedbc6e92016-10-14 21:41:24 +00004322 // FIXME: We need to track the instantiation stack in order to know which
4323 // definitions should be visible within this instantiation.
4324 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
4325 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
4326 /*InstantiatedFromMember*/false,
4327 PatternDecl, Def, TSK,
4328 /*Complain*/DefinitionRequired))
4329 return;
4330
Rafael Espindola189fa742012-03-05 10:54:55 +00004331
Douglas Gregor86d142a2009-10-08 07:24:58 +00004332 // Never instantiate an explicit specialization.
Rafael Espindola189fa742012-03-05 10:54:55 +00004333 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor86d142a2009-10-08 07:24:58 +00004334 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004335
Larisse Voufo39a1e502013-08-06 01:03:05 +00004336 // C++11 [temp.explicit]p10:
4337 // Except for inline functions, [...] explicit instantiation declarations
4338 // have the effect of suppressing the implicit instantiation of the entity
4339 // to which they refer.
Rafael Espindola189fa742012-03-05 10:54:55 +00004340 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor86d142a2009-10-08 07:24:58 +00004341 return;
Mike Stump11289f42009-09-09 15:08:12 +00004342
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00004343 // Make sure to pass the instantiated variable to the consumer at the end.
4344 struct PassToConsumerRAII {
4345 ASTConsumer &Consumer;
4346 VarDecl *Var;
4347
4348 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
4349 : Consumer(Consumer), Var(Var) { }
4350
4351 ~PassToConsumerRAII() {
Richard Smith8809a0c2013-09-27 20:14:12 +00004352 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00004353 }
4354 } PassToConsumerRAII(Consumer, Var);
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00004355
Reid Klecknere07140e2015-04-15 01:08:06 +00004356 // If we already have a definition, we're done.
4357 if (VarDecl *Def = Var->getDefinition()) {
4358 // We may be explicitly instantiating something we've already implicitly
4359 // instantiated.
4360 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
4361 PointOfInstantiation);
Richard Smith8809a0c2013-09-27 20:14:12 +00004362 return;
Reid Klecknere07140e2015-04-15 01:08:06 +00004363 }
Douglas Gregor57d4f972011-06-03 03:35:07 +00004364
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004365 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Richard Smith54f18e82016-08-31 02:15:21 +00004366 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004367 return;
Richard Smithe19b95d2016-05-26 20:23:13 +00004368 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4369 "instantiating variable definition");
Mike Stump11289f42009-09-09 15:08:12 +00004370
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004371 // If we're performing recursive template instantiation, create our own
4372 // queue of pending implicit instantiations that we will instantiate later,
4373 // while we're still within our own instantiation context.
David Majnemerfd6c685f2013-11-27 22:57:44 +00004374 SavePendingLocalImplicitInstantiationsRAII
4375 SavedPendingLocalImplicitInstantiations(*this);
Nico Weber7a92e1a2015-01-18 01:50:35 +00004376 SavePendingInstantiationsAndVTableUsesRAII
4377 SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
Mike Stump11289f42009-09-09 15:08:12 +00004378
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004379 // Enter the scope of this instantiation. We don't use
4380 // PushDeclContext because we don't have a scope.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004381 ContextRAII PreviousContext(*this, Var->getDeclContext());
Douglas Gregora86bc002012-02-16 21:36:18 +00004382 LocalInstantiationScope Local(*this);
John McCall2957e3e2011-02-14 20:37:25 +00004383
Larisse Voufo39a1e502013-08-06 01:03:05 +00004384 VarDecl *OldVar = Var;
Richard Smith62f19e72016-06-25 00:15:56 +00004385 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
4386 // We're instantiating an inline static data member whose definition was
4387 // provided inside the class.
4388 // FIXME: Update record?
4389 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4390 } else if (!VarSpec) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004391 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Richard Smith8809a0c2013-09-27 20:14:12 +00004392 TemplateArgs));
Richard Smith62f19e72016-06-25 00:15:56 +00004393 } else if (Var->isStaticDataMember() &&
4394 Var->getLexicalDeclContext()->isRecord()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00004395 // We need to instantiate the definition of a static data member template,
4396 // and all we have is the in-class declaration of it. Instantiate a separate
4397 // declaration of the definition.
4398 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
4399 TemplateArgs);
4400 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
Craig Topperc3ec1492014-05-26 06:22:03 +00004401 VarSpec->getSpecializedTemplate(), Def, nullptr,
Richard Smith8809a0c2013-09-27 20:14:12 +00004402 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
4403 if (Var) {
4404 llvm::PointerUnion<VarTemplateDecl *,
4405 VarTemplatePartialSpecializationDecl *> PatternPtr =
4406 VarSpec->getSpecializedTemplateOrPartial();
4407 if (VarTemplatePartialSpecializationDecl *Partial =
4408 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
4409 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
4410 Partial, &VarSpec->getTemplateInstantiationArgs());
4411
4412 // Merge the definition with the declaration.
4413 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
4414 LookupOrdinaryName, ForRedeclaration);
4415 R.addDecl(OldVar);
4416 MergeVarDecl(Var, R);
4417
4418 // Attach the initializer.
4419 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4420 }
4421 } else
4422 // Complete the existing variable's definition with an appropriately
4423 // substituted type and initializer.
4424 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004425
4426 PreviousContext.pop();
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004427
4428 if (Var) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00004429 PassToConsumerRAII.Var = Var;
Richard Smith8809a0c2013-09-27 20:14:12 +00004430 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
4431 OldVar->getPointOfInstantiation());
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004432 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004433
4434 // This variable may have local implicit instantiations that need to be
4435 // instantiated within this scope.
4436 PerformPendingInstantiations(/*LocalOnly=*/true);
4437
Douglas Gregora86bc002012-02-16 21:36:18 +00004438 Local.Exit();
4439
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004440 if (Recursive) {
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00004441 // Define any newly required vtables.
4442 DefineUsedVTables();
4443
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004444 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00004445 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00004446 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00004447
Nico Weber7a92e1a2015-01-18 01:50:35 +00004448 // PendingInstantiations and VTableUses are restored through
4449 // SavePendingInstantiationsAndVTableUses's destructor.
Mike Stump11289f42009-09-09 15:08:12 +00004450 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00004451}
Douglas Gregor51783312009-05-27 05:35:12 +00004452
Anders Carlsson70553942009-08-29 05:16:22 +00004453void
4454Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
4455 const CXXConstructorDecl *Tmpl,
4456 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00004457
Richard Trieu9becef62011-09-09 03:18:59 +00004458 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith60f2e1e2012-09-25 00:23:05 +00004459 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004460
Anders Carlsson70553942009-08-29 05:16:22 +00004461 // Instantiate all the initializers.
Aaron Ballman0ad78302014-03-13 17:34:31 +00004462 for (const auto *Init : Tmpl->inits()) {
Chandler Carruthf92bd8c2010-09-03 21:54:20 +00004463 // Only instantiate written initializers, let Sema re-construct implicit
4464 // ones.
4465 if (!Init->isWritten())
4466 continue;
4467
Douglas Gregor44e7df62011-01-04 00:32:56 +00004468 SourceLocation EllipsisLoc;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004469
Douglas Gregor44e7df62011-01-04 00:32:56 +00004470 if (Init->isPackExpansion()) {
4471 // This is a pack expansion. We should expand it now.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004472 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky2c308502013-06-13 00:45:47 +00004473 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor44e7df62011-01-04 00:32:56 +00004474 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky2c308502013-06-13 00:45:47 +00004475 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor44e7df62011-01-04 00:32:56 +00004476 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004477 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00004478 Optional<unsigned> NumExpansions;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004479 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004480 BaseTL.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00004481 Unexpanded,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004482 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004483 RetainExpansion,
Douglas Gregor44e7df62011-01-04 00:32:56 +00004484 NumExpansions)) {
4485 AnyErrors = true;
4486 New->setInvalidDecl();
4487 continue;
4488 }
4489 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004490
4491 // Loop over all of the arguments in the argument pack(s),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004492 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004493 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4494
4495 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004496 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4497 /*CXXDirectInit=*/true);
4498 if (TempInit.isInvalid()) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004499 AnyErrors = true;
4500 break;
4501 }
4502
4503 // Instantiate the base type.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004504 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004505 TemplateArgs,
4506 Init->getSourceLocation(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004507 New->getDeclName());
4508 if (!BaseTInfo) {
4509 AnyErrors = true;
4510 break;
4511 }
4512
4513 // Build the initializer.
Sebastian Redla74948d2011-09-24 17:48:25 +00004514 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004515 BaseTInfo, TempInit.get(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004516 New->getParent(),
4517 SourceLocation());
4518 if (NewInit.isInvalid()) {
4519 AnyErrors = true;
4520 break;
4521 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004522
Douglas Gregor44e7df62011-01-04 00:32:56 +00004523 NewInits.push_back(NewInit.get());
Douglas Gregor44e7df62011-01-04 00:32:56 +00004524 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004525
Douglas Gregor44e7df62011-01-04 00:32:56 +00004526 continue;
4527 }
4528
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004529 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004530 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4531 /*CXXDirectInit=*/true);
4532 if (TempInit.isInvalid()) {
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004533 AnyErrors = true;
4534 continue;
Anders Carlsson70553942009-08-29 05:16:22 +00004535 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004536
Anders Carlsson70553942009-08-29 05:16:22 +00004537 MemInitResult NewInit;
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004538 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4539 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4540 TemplateArgs,
4541 Init->getSourceLocation(),
4542 New->getDeclName());
4543 if (!TInfo) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004544 AnyErrors = true;
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00004545 New->setInvalidDecl();
4546 continue;
4547 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004548
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004549 if (Init->isBaseInitializer())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004550 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004551 New->getParent(), EllipsisLoc);
4552 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004553 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004554 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson70553942009-08-29 05:16:22 +00004555 } else if (Init->isMemberInitializer()) {
Douglas Gregor55e6b312011-03-04 19:46:35 +00004556 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004557 Init->getMemberLocation(),
4558 Init->getMember(),
4559 TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00004560 if (!Member) {
4561 AnyErrors = true;
4562 New->setInvalidDecl();
4563 continue;
4564 }
Mike Stump11289f42009-09-09 15:08:12 +00004565
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004566 NewInit = BuildMemberInitializer(Member, TempInit.get(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004567 Init->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +00004568 } else if (Init->isIndirectMemberInitializer()) {
4569 IndirectFieldDecl *IndirectMember =
Douglas Gregor55e6b312011-03-04 19:46:35 +00004570 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004571 Init->getMemberLocation(),
4572 Init->getIndirectMember(), TemplateArgs));
4573
Douglas Gregor55e6b312011-03-04 19:46:35 +00004574 if (!IndirectMember) {
4575 AnyErrors = true;
4576 New->setInvalidDecl();
Sebastian Redla74948d2011-09-24 17:48:25 +00004577 continue;
Douglas Gregor55e6b312011-03-04 19:46:35 +00004578 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004579
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004580 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004581 Init->getSourceLocation());
Anders Carlsson70553942009-08-29 05:16:22 +00004582 }
4583
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004584 if (NewInit.isInvalid()) {
4585 AnyErrors = true;
Anders Carlsson70553942009-08-29 05:16:22 +00004586 New->setInvalidDecl();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004587 } else {
Richard Trieu9becef62011-09-09 03:18:59 +00004588 NewInits.push_back(NewInit.get());
Anders Carlsson70553942009-08-29 05:16:22 +00004589 }
4590 }
Mike Stump11289f42009-09-09 15:08:12 +00004591
Anders Carlsson70553942009-08-29 05:16:22 +00004592 // Assign all the initializers to the new constructor.
John McCall48871652010-08-21 09:40:31 +00004593 ActOnMemInitializers(New,
Anders Carlsson70553942009-08-29 05:16:22 +00004594 /*FIXME: ColonLoc */
4595 SourceLocation(),
David Blaikie3fc2f912013-01-17 05:26:25 +00004596 NewInits,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004597 AnyErrors);
Anders Carlsson70553942009-08-29 05:16:22 +00004598}
4599
John McCall59660882009-08-29 08:11:13 +00004600// TODO: this could be templated if the various decl types used the
4601// same method name.
4602static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4603 ClassTemplateDecl *Instance) {
4604 Pattern = Pattern->getCanonicalDecl();
4605
4606 do {
4607 Instance = Instance->getCanonicalDecl();
4608 if (Pattern == Instance) return true;
4609 Instance = Instance->getInstantiatedFromMemberTemplate();
4610 } while (Instance);
4611
4612 return false;
4613}
4614
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004615static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4616 FunctionTemplateDecl *Instance) {
4617 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004618
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004619 do {
4620 Instance = Instance->getCanonicalDecl();
4621 if (Pattern == Instance) return true;
4622 Instance = Instance->getInstantiatedFromMemberTemplate();
4623 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004624
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004625 return false;
4626}
4627
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004628static bool
Douglas Gregor21610382009-10-29 00:04:11 +00004629isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4630 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004631 Pattern
Douglas Gregor21610382009-10-29 00:04:11 +00004632 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4633 do {
4634 Instance = cast<ClassTemplatePartialSpecializationDecl>(
4635 Instance->getCanonicalDecl());
4636 if (Pattern == Instance)
4637 return true;
4638 Instance = Instance->getInstantiatedFromMember();
4639 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004640
Douglas Gregor21610382009-10-29 00:04:11 +00004641 return false;
4642}
4643
John McCall59660882009-08-29 08:11:13 +00004644static bool isInstantiationOf(CXXRecordDecl *Pattern,
4645 CXXRecordDecl *Instance) {
4646 Pattern = Pattern->getCanonicalDecl();
4647
4648 do {
4649 Instance = Instance->getCanonicalDecl();
4650 if (Pattern == Instance) return true;
4651 Instance = Instance->getInstantiatedFromMemberClass();
4652 } while (Instance);
4653
4654 return false;
4655}
4656
4657static bool isInstantiationOf(FunctionDecl *Pattern,
4658 FunctionDecl *Instance) {
4659 Pattern = Pattern->getCanonicalDecl();
4660
4661 do {
4662 Instance = Instance->getCanonicalDecl();
4663 if (Pattern == Instance) return true;
4664 Instance = Instance->getInstantiatedFromMemberFunction();
4665 } while (Instance);
4666
4667 return false;
4668}
4669
4670static bool isInstantiationOf(EnumDecl *Pattern,
4671 EnumDecl *Instance) {
4672 Pattern = Pattern->getCanonicalDecl();
4673
4674 do {
4675 Instance = Instance->getCanonicalDecl();
4676 if (Pattern == Instance) return true;
4677 Instance = Instance->getInstantiatedFromMemberEnum();
4678 } while (Instance);
4679
4680 return false;
4681}
4682
John McCallb96ec562009-12-04 22:46:56 +00004683static bool isInstantiationOf(UsingShadowDecl *Pattern,
4684 UsingShadowDecl *Instance,
4685 ASTContext &C) {
Richard Smith32952e12014-10-14 02:00:47 +00004686 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
4687 Pattern);
John McCallb96ec562009-12-04 22:46:56 +00004688}
4689
Richard Smith151c4562016-12-20 21:35:28 +00004690static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
John McCallb96ec562009-12-04 22:46:56 +00004691 ASTContext &C) {
Richard Smith32952e12014-10-14 02:00:47 +00004692 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
John McCallb96ec562009-12-04 22:46:56 +00004693}
4694
Richard Smith151c4562016-12-20 21:35:28 +00004695template<typename T>
4696static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
4697 ASTContext &Ctx) {
4698 // An unresolved using declaration can instantiate to an unresolved using
4699 // declaration, or to a using declaration or a using declaration pack.
4700 //
4701 // Multiple declarations can claim to be instantiated from an unresolved
4702 // using declaration if it's a pack expansion. We want the UsingPackDecl
4703 // in that case, not the individual UsingDecls within the pack.
4704 bool OtherIsPackExpansion;
4705 NamedDecl *OtherFrom;
4706 if (auto *OtherUUD = dyn_cast<T>(Other)) {
4707 OtherIsPackExpansion = OtherUUD->isPackExpansion();
4708 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
4709 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
4710 OtherIsPackExpansion = true;
4711 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
4712 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
4713 OtherIsPackExpansion = false;
4714 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
4715 } else {
4716 return false;
4717 }
4718 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
4719 declaresSameEntity(OtherFrom, Pattern);
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004720}
4721
John McCall59660882009-08-29 08:11:13 +00004722static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4723 VarDecl *Instance) {
4724 assert(Instance->isStaticDataMember());
4725
4726 Pattern = Pattern->getCanonicalDecl();
4727
4728 do {
4729 Instance = Instance->getCanonicalDecl();
4730 if (Pattern == Instance) return true;
4731 Instance = Instance->getInstantiatedFromStaticDataMember();
4732 } while (Instance);
4733
4734 return false;
4735}
4736
John McCallb96ec562009-12-04 22:46:56 +00004737// Other is the prospective instantiation
4738// D is the prospective pattern
Douglas Gregor51783312009-05-27 05:35:12 +00004739static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Richard Smith151c4562016-12-20 21:35:28 +00004740 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
4741 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
John McCalle61f2ba2009-11-18 02:36:19 +00004742
Richard Smith151c4562016-12-20 21:35:28 +00004743 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
4744 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
Douglas Gregor51783312009-05-27 05:35:12 +00004745
Richard Smith151c4562016-12-20 21:35:28 +00004746 if (D->getKind() != Other->getKind())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004747 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004748
Richard Smithd8a9e372016-12-18 21:39:37 +00004749 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004750 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump11289f42009-09-09 15:08:12 +00004751
Richard Smithd8a9e372016-12-18 21:39:37 +00004752 if (auto *Function = dyn_cast<FunctionDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004753 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor51783312009-05-27 05:35:12 +00004754
Richard Smithd8a9e372016-12-18 21:39:37 +00004755 if (auto *Enum = dyn_cast<EnumDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004756 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor51783312009-05-27 05:35:12 +00004757
Richard Smithd8a9e372016-12-18 21:39:37 +00004758 if (auto *Var = dyn_cast<VarDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004759 if (Var->isStaticDataMember())
4760 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4761
Richard Smithd8a9e372016-12-18 21:39:37 +00004762 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004763 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregorf3db0032009-08-28 22:03:51 +00004764
Richard Smithd8a9e372016-12-18 21:39:37 +00004765 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004766 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4767
Richard Smithd8a9e372016-12-18 21:39:37 +00004768 if (auto *PartialSpec =
4769 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
Douglas Gregor21610382009-10-29 00:04:11 +00004770 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4771 PartialSpec);
4772
Richard Smithd8a9e372016-12-18 21:39:37 +00004773 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
Anders Carlsson5da84842009-09-01 04:26:58 +00004774 if (!Field->getDeclName()) {
4775 // This is an unnamed field.
Richard Smith32952e12014-10-14 02:00:47 +00004776 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
4777 cast<FieldDecl>(D));
Anders Carlsson5da84842009-09-01 04:26:58 +00004778 }
4779 }
Mike Stump11289f42009-09-09 15:08:12 +00004780
Richard Smithd8a9e372016-12-18 21:39:37 +00004781 if (auto *Using = dyn_cast<UsingDecl>(Other))
John McCallb96ec562009-12-04 22:46:56 +00004782 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4783
Richard Smithd8a9e372016-12-18 21:39:37 +00004784 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
John McCallb96ec562009-12-04 22:46:56 +00004785 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4786
Richard Smithd8a9e372016-12-18 21:39:37 +00004787 return D->getDeclName() &&
4788 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
Douglas Gregor51783312009-05-27 05:35:12 +00004789}
4790
4791template<typename ForwardIterator>
Mike Stump11289f42009-09-09 15:08:12 +00004792static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor51783312009-05-27 05:35:12 +00004793 NamedDecl *D,
4794 ForwardIterator first,
4795 ForwardIterator last) {
4796 for (; first != last; ++first)
4797 if (isInstantiationOf(Ctx, D, *first))
4798 return cast<NamedDecl>(*first);
4799
Craig Topperc3ec1492014-05-26 06:22:03 +00004800 return nullptr;
Douglas Gregor51783312009-05-27 05:35:12 +00004801}
4802
John McCallaa74a0c2009-08-28 07:59:38 +00004803/// \brief Finds the instantiation of the given declaration context
4804/// within the current instantiation.
4805///
4806/// \returns NULL if there was an error
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004807DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregor64621e62009-09-16 18:34:49 +00004808 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCallaa74a0c2009-08-28 07:59:38 +00004809 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004810 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCallaa74a0c2009-08-28 07:59:38 +00004811 return cast_or_null<DeclContext>(ID);
4812 } else return DC;
4813}
4814
Douglas Gregorcd3a0972009-05-27 17:54:46 +00004815/// \brief Find the instantiation of the given declaration within the
4816/// current instantiation.
Douglas Gregor51783312009-05-27 05:35:12 +00004817///
4818/// This routine is intended to be used when \p D is a declaration
4819/// referenced from within a template, that needs to mapped into the
4820/// corresponding declaration within an instantiation. For example,
4821/// given:
4822///
4823/// \code
4824/// template<typename T>
4825/// struct X {
4826/// enum Kind {
4827/// KnownValue = sizeof(T)
4828/// };
4829///
4830/// bool getKind() const { return KnownValue; }
4831/// };
4832///
4833/// template struct X<int>;
4834/// \endcode
4835///
Serge Pavloved5fe902013-07-10 04:59:14 +00004836/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4837/// \p EnumConstantDecl for \p KnownValue (which refers to
4838/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4839/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4840/// this mapping from within the instantiation of <tt>X<int></tt>.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004841NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregor64621e62009-09-16 18:34:49 +00004842 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor51783312009-05-27 05:35:12 +00004843 DeclContext *ParentDC = D->getDeclContext();
Faisal Vali2cba1332013-10-23 06:44:28 +00004844 // FIXME: Parmeters of pointer to functions (y below) that are themselves
4845 // parameters (p below) can have their ParentDC set to the translation-unit
4846 // - thus we can not consistently check if the ParentDC of such a parameter
4847 // is Dependent or/and a FunctionOrMethod.
4848 // For e.g. this code, during Template argument deduction tries to
4849 // find an instantiated decl for (T y) when the ParentDC for y is
4850 // the translation unit.
4851 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
Aaron Ballman36a53502014-01-16 13:03:14 +00004852 // float baz(float(*)()) { return 0.0; }
Faisal Vali2cba1332013-10-23 06:44:28 +00004853 // Foo(baz);
4854 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4855 // it gets here, always has a FunctionOrMethod as its ParentDC??
4856 // For now:
4857 // - as long as we have a ParmVarDecl whose parent is non-dependent and
4858 // whose type is not instantiation dependent, do nothing to the decl
4859 // - otherwise find its instantiated decl.
4860 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4861 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4862 return D;
Rafael Espindola09b00e32013-10-23 04:12:23 +00004863 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregorb93971082010-02-05 19:54:12 +00004864 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregora86bc002012-02-16 21:36:18 +00004865 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4866 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004867 // D is a local of some kind. Look into the map of local
4868 // declarations to their instantiations.
Alexey Samsonov2c0aac22014-09-03 18:45:45 +00004869 if (CurrentInstantiationScope) {
4870 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
4871 if (Decl *FD = Found->dyn_cast<Decl *>())
4872 return cast<NamedDecl>(FD);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004873
Alexey Samsonov2c0aac22014-09-03 18:45:45 +00004874 int PackIdx = ArgumentPackSubstitutionIndex;
4875 assert(PackIdx != -1 &&
4876 "found declaration pack but not pack expanding");
4877 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4878 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4879 }
Chris Lattnercab02a62011-02-17 20:34:02 +00004880 }
4881
Serge Pavlov7cd8f602013-07-15 06:14:07 +00004882 // If we're performing a partial substitution during template argument
4883 // deduction, we may not have values for template parameters yet. They
4884 // just map to themselves.
4885 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4886 isa<TemplateTemplateParmDecl>(D))
4887 return D;
4888
Serge Pavlov074a5182013-08-10 12:00:21 +00004889 if (D->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00004890 return nullptr;
Serge Pavlov074a5182013-08-10 12:00:21 +00004891
Serge Pavlove7ad8312015-05-15 10:10:28 +00004892 // Normally this function only searches for already instantiated declaration
4893 // however we have to make an exclusion for local types used before
4894 // definition as in the code:
4895 //
4896 // template<typename T> void f1() {
4897 // void g1(struct x1);
4898 // struct x1 {};
4899 // }
4900 //
4901 // In this case instantiation of the type of 'g1' requires definition of
4902 // 'x1', which is defined later. Error recovery may produce an enum used
4903 // before definition. In these cases we need to instantiate relevant
4904 // declarations here.
4905 bool NeedInstantiate = false;
4906 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4907 NeedInstantiate = RD->isLocalClass();
4908 else
4909 NeedInstantiate = isa<EnumDecl>(D);
4910 if (NeedInstantiate) {
Serge Pavlov4c511742015-05-04 16:44:39 +00004911 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4912 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4913 return cast<TypeDecl>(Inst);
4914 }
4915
Chris Lattnercab02a62011-02-17 20:34:02 +00004916 // If we didn't find the decl, then we must have a label decl that hasn't
4917 // been found yet. Lazily instantiate it and return it now.
4918 assert(isa<LabelDecl>(D));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004919
Chris Lattnercab02a62011-02-17 20:34:02 +00004920 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4921 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004922
Chris Lattnercab02a62011-02-17 20:34:02 +00004923 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4924 return cast<LabelDecl>(Inst);
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004925 }
Douglas Gregor51783312009-05-27 05:35:12 +00004926
Larisse Voufo39a1e502013-08-06 01:03:05 +00004927 // For variable template specializations, update those that are still
4928 // type-dependent.
4929 if (VarTemplateSpecializationDecl *VarSpec =
4930 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4931 bool InstantiationDependent = false;
4932 const TemplateArgumentListInfo &VarTemplateArgs =
4933 VarSpec->getTemplateArgsInfo();
4934 if (TemplateSpecializationType::anyDependentTemplateArguments(
4935 VarTemplateArgs, InstantiationDependent))
4936 D = cast<NamedDecl>(
4937 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4938 return D;
4939 }
4940
Douglas Gregor64621e62009-09-16 18:34:49 +00004941 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4942 if (!Record->isDependentContext())
4943 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004944
Douglas Gregor4109afa2011-11-07 17:43:18 +00004945 // Determine whether this record is the "templated" declaration describing
4946 // a class template or class template partial specialization.
Douglas Gregor64621e62009-09-16 18:34:49 +00004947 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor4109afa2011-11-07 17:43:18 +00004948 if (ClassTemplate)
4949 ClassTemplate = ClassTemplate->getCanonicalDecl();
4950 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4951 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4952 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004953
Douglas Gregor4109afa2011-11-07 17:43:18 +00004954 // Walk the current context to find either the record or an instantiation of
4955 // it.
4956 DeclContext *DC = CurContext;
4957 while (!DC->isFileContext()) {
4958 // If we're performing substitution while we're inside the template
4959 // definition, we'll find our own context. We're done.
4960 if (DC->Equals(Record))
4961 return Record;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004962
Douglas Gregor4109afa2011-11-07 17:43:18 +00004963 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4964 // Check whether we're in the process of instantiating a class template
4965 // specialization of the template we're mapping.
4966 if (ClassTemplateSpecializationDecl *InstSpec
4967 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4968 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4969 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4970 return InstRecord;
4971 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004972
Douglas Gregor4109afa2011-11-07 17:43:18 +00004973 // Check whether we're in the process of instantiating a member class.
4974 if (isInstantiationOf(Record, InstRecord))
4975 return InstRecord;
Douglas Gregor64621e62009-09-16 18:34:49 +00004976 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004977
Douglas Gregor4109afa2011-11-07 17:43:18 +00004978 // Move to the outer template scope.
4979 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4980 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4981 DC = FD->getLexicalDeclContext();
4982 continue;
4983 }
Richard Smith32918772017-02-14 00:25:28 +00004984 // An implicit deduction guide acts as if it's within the class template
4985 // specialization described by its name and first N template params.
Richard Smithbc491202017-02-17 20:05:37 +00004986 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
4987 if (Guide && Guide->isImplicit()) {
4988 TemplateDecl *TD = Guide->getDeducedTemplate();
Richard Smith0cd9c042017-02-21 08:42:39 +00004989 // Convert the arguments to an "as-written" list.
Richard Smith32918772017-02-14 00:25:28 +00004990 TemplateArgumentListInfo Args(Loc, Loc);
Richard Smith0cd9c042017-02-21 08:42:39 +00004991 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
4992 TD->getTemplateParameters()->size())) {
4993 ArrayRef<TemplateArgument> Unpacked(Arg);
4994 if (Arg.getKind() == TemplateArgument::Pack)
4995 Unpacked = Arg.pack_elements();
4996 for (TemplateArgument UnpackedArg : Unpacked)
4997 Args.addArgument(
4998 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
4999 }
Richard Smith32918772017-02-14 00:25:28 +00005000 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
5001 if (T.isNull())
5002 return nullptr;
5003 DC = T->getAsCXXRecordDecl();
5004 continue;
5005 }
John McCall59660882009-08-29 08:11:13 +00005006 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00005007
Douglas Gregor4109afa2011-11-07 17:43:18 +00005008 DC = DC->getParent();
John McCall59660882009-08-29 08:11:13 +00005009 }
Douglas Gregord225fa02010-02-05 22:40:03 +00005010
Douglas Gregor64621e62009-09-16 18:34:49 +00005011 // Fall through to deal with other dependent record types (e.g.,
5012 // anonymous unions in class templates).
5013 }
John McCall59660882009-08-29 08:11:13 +00005014
Douglas Gregor64621e62009-09-16 18:34:49 +00005015 if (!ParentDC->isDependentContext())
5016 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005017
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005018 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00005019 if (!ParentDC)
Craig Topperc3ec1492014-05-26 06:22:03 +00005020 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005021
Douglas Gregor51783312009-05-27 05:35:12 +00005022 if (ParentDC != D->getDeclContext()) {
5023 // We performed some kind of instantiation in the parent context,
5024 // so now we need to look into the instantiated parent context to
5025 // find the instantiation of the declaration D.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005026
John McCalle78aac42010-03-10 03:28:59 +00005027 // If our context used to be dependent, we may need to instantiate
5028 // it before performing lookup into that context.
Douglas Gregor528ad932011-03-06 20:12:45 +00005029 bool IsBeingInstantiated = false;
John McCalle78aac42010-03-10 03:28:59 +00005030 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005031 if (!Spec->isDependentContext()) {
5032 QualType T = Context.getTypeDeclType(Spec);
John McCalle78aac42010-03-10 03:28:59 +00005033 const RecordType *Tag = T->getAs<RecordType>();
5034 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregor528ad932011-03-06 20:12:45 +00005035 if (Tag->isBeingDefined())
5036 IsBeingInstantiated = true;
John McCalle78aac42010-03-10 03:28:59 +00005037 if (!Tag->isBeingDefined() &&
5038 RequireCompleteType(Loc, T, diag::err_incomplete_type))
Craig Topperc3ec1492014-05-26 06:22:03 +00005039 return nullptr;
Douglas Gregor25edf432010-11-05 23:22:45 +00005040
5041 ParentDC = Tag->getDecl();
Douglas Gregora04f2ca2010-03-01 15:56:25 +00005042 }
5043 }
5044
Craig Topperc3ec1492014-05-26 06:22:03 +00005045 NamedDecl *Result = nullptr;
Richard Smith151c4562016-12-20 21:35:28 +00005046 // FIXME: If the name is a dependent name, this lookup won't necessarily
5047 // find it. Does that ever matter?
Akira Hatanaka59e3b432017-01-31 19:53:32 +00005048 if (auto Name = D->getDeclName()) {
5049 DeclarationNameInfo NameInfo(Name, D->getLocation());
5050 Name = SubstDeclarationNameInfo(NameInfo, TemplateArgs).getName();
5051 if (!Name)
5052 return nullptr;
5053 DeclContext::lookup_result Found = ParentDC->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005054 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor51783312009-05-27 05:35:12 +00005055 } else {
5056 // Since we don't have a name for the entity we're looking for,
5057 // our only option is to walk through all of the declarations to
5058 // find that name. This will occur in a few cases:
5059 //
5060 // - anonymous struct/union within a template
5061 // - unnamed class/struct/union/enum within a template
5062 //
5063 // FIXME: Find a better way to find these instantiations!
Mike Stump11289f42009-09-09 15:08:12 +00005064 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005065 ParentDC->decls_begin(),
5066 ParentDC->decls_end());
Douglas Gregor51783312009-05-27 05:35:12 +00005067 }
Mike Stump11289f42009-09-09 15:08:12 +00005068
Douglas Gregor528ad932011-03-06 20:12:45 +00005069 if (!Result) {
5070 if (isa<UsingShadowDecl>(D)) {
5071 // UsingShadowDecls can instantiate to nothing because of using hiding.
5072 } else if (Diags.hasErrorOccurred()) {
5073 // We've already complained about something, so most likely this
5074 // declaration failed to instantiate. There's no point in complaining
5075 // further, since this is normal in invalid code.
5076 } else if (IsBeingInstantiated) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005077 // The class in which this member exists is currently being
Douglas Gregor528ad932011-03-06 20:12:45 +00005078 // instantiated, and we haven't gotten around to instantiating this
5079 // member yet. This can happen when the code uses forward declarations
5080 // of member classes, and introduces ordering dependencies via
5081 // template instantiation.
5082 Diag(Loc, diag::err_member_not_yet_instantiated)
5083 << D->getDeclName()
5084 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
5085 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith169f2192012-03-26 20:28:16 +00005086 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
5087 // This enumeration constant was found when the template was defined,
5088 // but can't be found in the instantiation. This can happen if an
5089 // unscoped enumeration member is explicitly specialized.
5090 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
5091 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
5092 TemplateArgs));
5093 assert(Spec->getTemplateSpecializationKind() ==
5094 TSK_ExplicitSpecialization);
5095 Diag(Loc, diag::err_enumerator_does_not_exist)
5096 << D->getDeclName()
5097 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
5098 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
5099 << Context.getTypeDeclType(Spec);
Douglas Gregor528ad932011-03-06 20:12:45 +00005100 } else {
5101 // We should have found something, but didn't.
5102 llvm_unreachable("Unable to find instantiation of declaration!");
5103 }
5104 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00005105
Douglas Gregor51783312009-05-27 05:35:12 +00005106 D = Result;
5107 }
5108
Douglas Gregor51783312009-05-27 05:35:12 +00005109 return D;
5110}
Douglas Gregor77b50e12009-06-22 23:06:13 +00005111
Mike Stump11289f42009-09-09 15:08:12 +00005112/// \brief Performs template instantiation for all implicit template
Douglas Gregor77b50e12009-06-22 23:06:13 +00005113/// instantiations we have seen until this point.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00005114void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00005115 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth54080172010-08-25 08:44:16 +00005116 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00005117 PendingImplicitInstantiation Inst;
5118
5119 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth54080172010-08-25 08:44:16 +00005120 Inst = PendingInstantiations.front();
5121 PendingInstantiations.pop_front();
Douglas Gregor7f792cf2010-01-16 22:29:39 +00005122 } else {
5123 Inst = PendingLocalImplicitInstantiations.front();
5124 PendingLocalImplicitInstantiations.pop_front();
5125 }
Mike Stump11289f42009-09-09 15:08:12 +00005126
Douglas Gregora6ef8f02009-07-24 20:34:43 +00005127 // Instantiate function definitions
5128 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005129 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
5130 TSK_ExplicitInstantiationDefinition;
5131 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00005132 DefinitionRequired, true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00005133 continue;
5134 }
Mike Stump11289f42009-09-09 15:08:12 +00005135
Larisse Voufo39a1e502013-08-06 01:03:05 +00005136 // Instantiate variable definitions
Douglas Gregora6ef8f02009-07-24 20:34:43 +00005137 VarDecl *Var = cast<VarDecl>(Inst.first);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005138
5139 assert((Var->isStaticDataMember() ||
5140 isa<VarTemplateSpecializationDecl>(Var)) &&
5141 "Not a static data member, nor a variable template"
5142 " specialization?");
Anders Carlsson62215c42009-09-01 05:12:24 +00005143
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005144 // Don't try to instantiate declarations if the most recent redeclaration
5145 // is invalid.
Douglas Gregorec9fd132012-01-14 16:38:05 +00005146 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005147 continue;
5148
5149 // Check if the most recent declaration has changed the specialization kind
5150 // and removed the need for implicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00005151 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005152 case TSK_Undeclared:
David Blaikie83d382b2011-09-23 05:06:16 +00005153 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005154 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005155 case TSK_ExplicitSpecialization:
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005156 continue; // No longer need to instantiate this type.
5157 case TSK_ExplicitInstantiationDefinition:
5158 // We only need an instantiation if the pending instantiation *is* the
5159 // explicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00005160 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth6b4756a2010-02-13 10:17:50 +00005161 case TSK_ImplicitInstantiation:
5162 break;
5163 }
5164
Larisse Voufo39a1e502013-08-06 01:03:05 +00005165 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
5166 "instantiating variable definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00005167 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
5168 TSK_ExplicitInstantiationDefinition;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005169
5170 // Instantiate static data member definitions or variable template
5171 // specializations.
5172 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
Serge Pavlov7dcc97e2016-04-19 06:19:52 +00005173 DefinitionRequired, true);
Douglas Gregor77b50e12009-06-22 23:06:13 +00005174 }
5175}
John McCallc62bb642010-03-24 05:22:00 +00005176
5177void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
5178 const MultiLevelTemplateArgumentList &TemplateArgs) {
Aaron Ballmanb105e492014-03-07 14:09:15 +00005179 for (auto DD : Pattern->ddiags()) {
John McCallc62bb642010-03-24 05:22:00 +00005180 switch (DD->getKind()) {
5181 case DependentDiagnostic::Access:
5182 HandleDependentAccessCheck(*DD, TemplateArgs);
5183 break;
5184 }
5185 }
5186}