blob: 2218bdd958e6d5c7dfd0c6c754c2930486d24705 [file] [log] [blame]
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001//===------- SemaTemplateInstantiate.cpp - C++ Template 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.
10//
11//===----------------------------------------------------------------------===/
12
John McCall83024632010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregord6ff3322009-08-04 16:50:30 +000014#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
Faisal Vali2cba1332013-10-23 06:44:28 +000017#include "clang/AST/ASTLambda.h"
Richard Smith4b054b22016-08-24 21:25:37 +000018#include "clang/AST/ASTMutationListener.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
Jordan Rose1e879d82018-03-23 00:07:18 +000021#include "clang/AST/PrettyDeclStackTrace.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/LangOptions.h"
John McCall8b0666c2010-08-20 18:27:03 +000023#include "clang/Sema/DeclSpec.h"
Richard Smith938f40b2011-06-11 17:19:42 +000024#include "clang/Sema/Initialization.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000025#include "clang/Sema/Lookup.h"
John McCallde6836a2010-08-24 07:21:54 +000026#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000027#include "clang/Sema/TemplateDeduction.h"
Gabor Horvath207e7b12018-02-10 14:04:45 +000028#include "clang/Sema/TemplateInstCallback.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000029
30using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000031using namespace sema;
Douglas Gregorfe1e1102009-02-27 19:31:52 +000032
Douglas Gregor4ea568f2009-03-10 18:03:33 +000033//===----------------------------------------------------------------------===/
34// Template Instantiation Support
35//===----------------------------------------------------------------------===/
36
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000037/// Retrieve the template argument list(s) that should be used to
Douglas Gregor01afeef2009-08-28 20:31:08 +000038/// instantiate the definition of the given declaration.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000039///
40/// \param D the declaration for which we are computing template instantiation
41/// arguments.
42///
43/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor8c702532010-02-05 07:33:43 +000044///
45/// \param RelativeToPrimary true if we should get the template
46/// arguments relative to the primary template, even when we're
47/// dealing with a specialization. This is only relevant for function
48/// template specializations.
Douglas Gregor1bd7a942010-05-03 23:29:10 +000049///
50/// \param Pattern If non-NULL, indicates the pattern from which we will be
51/// instantiating the definition of the given declaration, \p D. This is
52/// used to determine the proper set of template instantiation arguments for
53/// friend function template specializations.
Douglas Gregora654dd82009-08-28 17:37:35 +000054MultiLevelTemplateArgumentList
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000055Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor8c702532010-02-05 07:33:43 +000056 const TemplateArgumentList *Innermost,
Douglas Gregor1bd7a942010-05-03 23:29:10 +000057 bool RelativeToPrimary,
58 const FunctionDecl *Pattern) {
Douglas Gregora654dd82009-08-28 17:37:35 +000059 // Accumulate the set of template argument lists in this structure.
60 MultiLevelTemplateArgumentList Result;
Mike Stump11289f42009-09-09 15:08:12 +000061
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000062 if (Innermost)
63 Result.addOuterTemplateArguments(Innermost);
64
Douglas Gregora654dd82009-08-28 17:37:35 +000065 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregora51c9cc2011-05-22 00:21:10 +000066 if (!Ctx) {
Douglas Gregora654dd82009-08-28 17:37:35 +000067 Ctx = D->getDeclContext();
Larisse Voufo39a1e502013-08-06 01:03:05 +000068
69 // Add template arguments from a variable template instantiation.
70 if (VarTemplateSpecializationDecl *Spec =
71 dyn_cast<VarTemplateSpecializationDecl>(D)) {
72 // We're done when we hit an explicit specialization.
73 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
74 !isa<VarTemplatePartialSpecializationDecl>(Spec))
75 return Result;
76
77 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
78
79 // If this variable template specialization was instantiated from a
80 // specialized member that is a variable template, we're done.
81 assert(Spec->getSpecializedTemplate() && "No variable template?");
Richard Smithbeef3452014-01-16 23:39:20 +000082 llvm::PointerUnion<VarTemplateDecl*,
83 VarTemplatePartialSpecializationDecl*> Specialized
84 = Spec->getSpecializedTemplateOrPartial();
85 if (VarTemplatePartialSpecializationDecl *Partial =
86 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
87 if (Partial->isMemberSpecialization())
88 return Result;
89 } else {
90 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
91 if (Tmpl->isMemberSpecialization())
92 return Result;
93 }
Larisse Voufo39a1e502013-08-06 01:03:05 +000094 }
95
Douglas Gregor55462622011-06-15 14:20:42 +000096 // If we have a template template parameter with translation unit context,
97 // then we're performing substitution into a default template argument of
98 // this template template parameter before we've constructed the template
99 // that will own this template template parameter. In this case, we
100 // use empty template parameter lists for all of the outer templates
101 // to avoid performing any substitutions.
102 if (Ctx->isTranslationUnit()) {
103 if (TemplateTemplateParmDecl *TTP
104 = dyn_cast<TemplateTemplateParmDecl>(D)) {
105 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +0000106 Result.addOuterTemplateArguments(None);
Douglas Gregor55462622011-06-15 14:20:42 +0000107 return Result;
108 }
109 }
Douglas Gregora51c9cc2011-05-22 00:21:10 +0000110 }
111
John McCall970d5302009-08-29 03:16:09 +0000112 while (!Ctx->isFileContext()) {
Douglas Gregora654dd82009-08-28 17:37:35 +0000113 // Add template arguments from a class template instantiation.
Mike Stump11289f42009-09-09 15:08:12 +0000114 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregora654dd82009-08-28 17:37:35 +0000115 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
116 // We're done when we hit an explicit specialization.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000117 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
118 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregora654dd82009-08-28 17:37:35 +0000119 break;
Mike Stump11289f42009-09-09 15:08:12 +0000120
Douglas Gregora654dd82009-08-28 17:37:35 +0000121 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000122
123 // If this class template specialization was instantiated from a
124 // specialized member that is a class template, we're done.
125 assert(Spec->getSpecializedTemplate() && "No class template?");
126 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
127 break;
Mike Stump11289f42009-09-09 15:08:12 +0000128 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000129 // Add template arguments from a function template specialization.
John McCall970d5302009-08-29 03:16:09 +0000130 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor8c702532010-02-05 07:33:43 +0000131 if (!RelativeToPrimary &&
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000132 (Function->getTemplateSpecializationKind() ==
133 TSK_ExplicitSpecialization &&
134 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorcf915552009-10-13 16:30:37 +0000135 break;
136
Douglas Gregora654dd82009-08-28 17:37:35 +0000137 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorcf915552009-10-13 16:30:37 +0000138 = Function->getTemplateSpecializationArgs()) {
139 // Add the template arguments for this specialization.
Douglas Gregora654dd82009-08-28 17:37:35 +0000140 Result.addOuterTemplateArguments(TemplateArgs);
John McCall970d5302009-08-29 03:16:09 +0000141
Douglas Gregorcf915552009-10-13 16:30:37 +0000142 // If this function was instantiated from a specialized member that is
143 // a function template, we're done.
144 assert(Function->getPrimaryTemplate() && "No function template?");
145 if (Function->getPrimaryTemplate()->isMemberSpecialization())
146 break;
Faisal Vali2cba1332013-10-23 06:44:28 +0000147
148 // If this function is a generic lambda specialization, we are done.
149 if (isGenericLambdaCallOperatorSpecialization(Function))
150 break;
151
Douglas Gregor43669f82011-03-05 17:54:25 +0000152 } else if (FunctionTemplateDecl *FunTmpl
153 = Function->getDescribedFunctionTemplate()) {
154 // Add the "injected" template arguments.
Richard Smith841d8b22013-05-17 03:04:50 +0000155 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000156 }
157
John McCall970d5302009-08-29 03:16:09 +0000158 // If this is a friend declaration and it declares an entity at
159 // namespace scope, take arguments from its lexical parent
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000160 // instead of its semantic parent, unless of course the pattern we're
161 // instantiating actually comes from the file's context!
John McCall970d5302009-08-29 03:16:09 +0000162 if (Function->getFriendObjectKind() &&
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000163 Function->getDeclContext()->isFileContext() &&
164 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCall970d5302009-08-29 03:16:09 +0000165 Ctx = Function->getLexicalDeclContext();
Douglas Gregor8c702532010-02-05 07:33:43 +0000166 RelativeToPrimary = false;
John McCall970d5302009-08-29 03:16:09 +0000167 continue;
168 }
Douglas Gregor9961ce92010-07-08 18:37:38 +0000169 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
170 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
171 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith841d8b22013-05-17 03:04:50 +0000172 const TemplateSpecializationType *TST =
173 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
174 Result.addOuterTemplateArguments(
175 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor9961ce92010-07-08 18:37:38 +0000176 if (ClassTemplate->isMemberSpecialization())
177 break;
178 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000179 }
John McCall970d5302009-08-29 03:16:09 +0000180
181 Ctx = Ctx->getParent();
Douglas Gregor8c702532010-02-05 07:33:43 +0000182 RelativeToPrimary = false;
Douglas Gregorb4850462009-05-14 23:26:13 +0000183 }
Mike Stump11289f42009-09-09 15:08:12 +0000184
Douglas Gregora654dd82009-08-28 17:37:35 +0000185 return Result;
Douglas Gregorb4850462009-05-14 23:26:13 +0000186}
187
Richard Smith696e3122017-02-23 01:43:54 +0000188bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000189 switch (Kind) {
190 case TemplateInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000191 case ExceptionSpecInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000192 case DefaultTemplateArgumentInstantiation:
193 case DefaultFunctionArgumentInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000194 case ExplicitTemplateArgumentSubstitution:
195 case DeducedTemplateArgumentSubstitution:
196 case PriorTemplateArgumentSubstitution:
Richard Smith8a874c92012-07-08 02:38:24 +0000197 return true;
198
Douglas Gregor84d49a22009-11-11 21:54:23 +0000199 case DefaultTemplateArgumentChecking:
Richard Smith13381222017-02-23 21:43:43 +0000200 case DeclaringSpecialMember:
Richard Smith883dbc42017-05-25 22:47:05 +0000201 case DefiningSynthesizedFunction:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000202 return false;
Gabor Horvath207e7b12018-02-10 14:04:45 +0000203
204 // This function should never be called when Kind's value is Memoization.
205 case Memoization:
206 break;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000207 }
David Blaikie8a40f702012-01-17 06:56:22 +0000208
Richard Smith696e3122017-02-23 01:43:54 +0000209 llvm_unreachable("Invalid SynthesisKind!");
Douglas Gregor84d49a22009-11-11 21:54:23 +0000210}
211
Benjamin Kramer7761a042015-03-06 16:36:50 +0000212Sema::InstantiatingTemplate::InstantiatingTemplate(
Richard Smith696e3122017-02-23 01:43:54 +0000213 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000214 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
215 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000216 sema::TemplateDeductionInfo *DeductionInfo)
Richard Smith13381222017-02-23 21:43:43 +0000217 : SemaRef(SemaRef) {
Akira Hatanaka43556c12016-11-03 15:04:58 +0000218 // Don't allow further instantiation if a fatal error and an uncompilable
Akira Hatanaka40c15ab2016-11-03 17:11:28 +0000219 // error have occurred. Any diagnostics we might have raised will not be
Akira Hatanaka43556c12016-11-03 15:04:58 +0000220 // visible, and we do not need to construct a correct AST.
221 if (SemaRef.Diags.hasFatalErrorOccurred() &&
222 SemaRef.Diags.hasUncompilableErrorOccurred()) {
David Majnemer8c969ea2015-01-30 05:01:23 +0000223 Invalid = true;
224 return;
225 }
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000226 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
227 if (!Invalid) {
Richard Smith696e3122017-02-23 01:43:54 +0000228 CodeSynthesisContext Inst;
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000229 Inst.Kind = Kind;
230 Inst.PointOfInstantiation = PointOfInstantiation;
231 Inst.Entity = Entity;
232 Inst.Template = Template;
233 Inst.TemplateArgs = TemplateArgs.data();
234 Inst.NumTemplateArgs = TemplateArgs.size();
235 Inst.DeductionInfo = DeductionInfo;
236 Inst.InstantiationRange = InstantiationRange;
Richard Smith13381222017-02-23 21:43:43 +0000237 SemaRef.pushCodeSynthesisContext(Inst);
238
Richard Smith54f18e82016-08-31 02:15:21 +0000239 AlreadyInstantiating =
240 !SemaRef.InstantiatingSpecializations
241 .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
242 .second;
Gabor Horvath207e7b12018-02-10 14:04:45 +0000243 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000244 }
245}
246
Benjamin Kramer7761a042015-03-06 16:36:50 +0000247Sema::InstantiatingTemplate::InstantiatingTemplate(
248 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
249 SourceRange InstantiationRange)
250 : InstantiatingTemplate(SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000251 CodeSynthesisContext::TemplateInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000252 PointOfInstantiation, InstantiationRange, Entity) {}
Douglas Gregor79cf6032009-03-10 20:44:00 +0000253
Benjamin Kramer7761a042015-03-06 16:36:50 +0000254Sema::InstantiatingTemplate::InstantiatingTemplate(
255 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
256 ExceptionSpecification, SourceRange InstantiationRange)
257 : InstantiatingTemplate(
Richard Smith696e3122017-02-23 01:43:54 +0000258 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000259 PointOfInstantiation, InstantiationRange, Entity) {}
Richard Smithf623c962012-04-17 00:58:00 +0000260
Benjamin Kramer7761a042015-03-06 16:36:50 +0000261Sema::InstantiatingTemplate::InstantiatingTemplate(
Richard Smith54f18e82016-08-31 02:15:21 +0000262 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
263 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
264 SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000265 : InstantiatingTemplate(
266 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000267 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
Richard Smith54f18e82016-08-31 02:15:21 +0000268 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
269 Template, TemplateArgs) {}
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000270
Benjamin Kramer7761a042015-03-06 16:36:50 +0000271Sema::InstantiatingTemplate::InstantiatingTemplate(
272 Sema &SemaRef, SourceLocation PointOfInstantiation,
273 FunctionTemplateDecl *FunctionTemplate,
274 ArrayRef<TemplateArgument> TemplateArgs,
Richard Smith696e3122017-02-23 01:43:54 +0000275 CodeSynthesisContext::SynthesisKind Kind,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000276 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
277 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
278 InstantiationRange, FunctionTemplate, nullptr,
Richard Smith54f18e82016-08-31 02:15:21 +0000279 TemplateArgs, &DeductionInfo) {
280 assert(
Richard Smith696e3122017-02-23 01:43:54 +0000281 Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
282 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution);
Richard Smith54f18e82016-08-31 02:15:21 +0000283}
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000284
Benjamin Kramer7761a042015-03-06 16:36:50 +0000285Sema::InstantiatingTemplate::InstantiatingTemplate(
286 Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith0e617ec2016-12-27 07:56:27 +0000287 TemplateDecl *Template,
288 ArrayRef<TemplateArgument> TemplateArgs,
289 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
290 : InstantiatingTemplate(
291 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000292 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
Richard Smith0e617ec2016-12-27 07:56:27 +0000293 PointOfInstantiation, InstantiationRange, Template, nullptr,
294 TemplateArgs, &DeductionInfo) {}
295
296Sema::InstantiatingTemplate::InstantiatingTemplate(
297 Sema &SemaRef, SourceLocation PointOfInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000298 ClassTemplatePartialSpecializationDecl *PartialSpec,
299 ArrayRef<TemplateArgument> TemplateArgs,
300 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
301 : InstantiatingTemplate(
302 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000303 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000304 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
305 TemplateArgs, &DeductionInfo) {}
Douglas Gregor637d9982009-06-10 23:47:09 +0000306
Larisse Voufo39a1e502013-08-06 01:03:05 +0000307Sema::InstantiatingTemplate::InstantiatingTemplate(
308 Sema &SemaRef, SourceLocation PointOfInstantiation,
309 VarTemplatePartialSpecializationDecl *PartialSpec,
310 ArrayRef<TemplateArgument> TemplateArgs,
311 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000312 : InstantiatingTemplate(
313 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000314 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000315 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
316 TemplateArgs, &DeductionInfo) {}
Larisse Voufo39a1e502013-08-06 01:03:05 +0000317
Benjamin Kramer7761a042015-03-06 16:36:50 +0000318Sema::InstantiatingTemplate::InstantiatingTemplate(
319 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
320 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
321 : InstantiatingTemplate(
322 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000323 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000324 PointOfInstantiation, InstantiationRange, Param, nullptr,
325 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000326
Benjamin Kramer7761a042015-03-06 16:36:50 +0000327Sema::InstantiatingTemplate::InstantiatingTemplate(
328 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
329 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
330 SourceRange InstantiationRange)
331 : InstantiatingTemplate(
332 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000333 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000334 PointOfInstantiation, InstantiationRange, Param, Template,
335 TemplateArgs) {}
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000336
Benjamin Kramer7761a042015-03-06 16:36:50 +0000337Sema::InstantiatingTemplate::InstantiatingTemplate(
338 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
339 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
340 SourceRange InstantiationRange)
341 : InstantiatingTemplate(
342 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000343 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000344 PointOfInstantiation, InstantiationRange, Param, Template,
345 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000346
Benjamin Kramer7761a042015-03-06 16:36:50 +0000347Sema::InstantiatingTemplate::InstantiatingTemplate(
348 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
349 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
350 SourceRange InstantiationRange)
351 : InstantiatingTemplate(
Richard Smith696e3122017-02-23 01:43:54 +0000352 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000353 PointOfInstantiation, InstantiationRange, Param, Template,
354 TemplateArgs) {}
Anders Carlsson657bad42009-09-05 05:14:19 +0000355
Richard Smith13381222017-02-23 21:43:43 +0000356void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
357 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
358 InNonInstantiationSFINAEContext = false;
359
360 CodeSynthesisContexts.push_back(Ctx);
361
362 if (!Ctx.isInstantiationRecord())
363 ++NonInstantiationEntries;
364}
365
366void Sema::popCodeSynthesisContext() {
367 auto &Active = CodeSynthesisContexts.back();
368 if (!Active.isInstantiationRecord()) {
369 assert(NonInstantiationEntries > 0);
370 --NonInstantiationEntries;
371 }
372
373 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
374
375 // Name lookup no longer looks in this template's defining module.
376 assert(CodeSynthesisContexts.size() >=
377 CodeSynthesisContextLookupModules.size() &&
378 "forgot to remove a lookup module for a template instantiation");
379 if (CodeSynthesisContexts.size() ==
380 CodeSynthesisContextLookupModules.size()) {
381 if (Module *M = CodeSynthesisContextLookupModules.back())
382 LookupModulesCache.erase(M);
383 CodeSynthesisContextLookupModules.pop_back();
384 }
385
386 // If we've left the code synthesis context for the current context stack,
387 // stop remembering that we've emitted that stack.
388 if (CodeSynthesisContexts.size() ==
389 LastEmittedCodeSynthesisContextDepth)
390 LastEmittedCodeSynthesisContextDepth = 0;
391
392 CodeSynthesisContexts.pop_back();
393}
394
Douglas Gregor85673582009-05-18 17:01:57 +0000395void Sema::InstantiatingTemplate::Clear() {
396 if (!Invalid) {
Richard Smith13381222017-02-23 21:43:43 +0000397 if (!AlreadyInstantiating) {
398 auto &Active = SemaRef.CodeSynthesisContexts.back();
Richard Smith54f18e82016-08-31 02:15:21 +0000399 SemaRef.InstantiatingSpecializations.erase(
400 std::make_pair(Active.Entity, Active.Kind));
Richard Smith13381222017-02-23 21:43:43 +0000401 }
Richard Smith54f18e82016-08-31 02:15:21 +0000402
Gabor Horvath207e7b12018-02-10 14:04:45 +0000403 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
404 SemaRef.CodeSynthesisContexts.back());
Richard Smith13381222017-02-23 21:43:43 +0000405
Gabor Horvath207e7b12018-02-10 14:04:45 +0000406 SemaRef.popCodeSynthesisContext();
Douglas Gregor85673582009-05-18 17:01:57 +0000407 Invalid = true;
408 }
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000409}
410
Douglas Gregor79cf6032009-03-10 20:44:00 +0000411bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
412 SourceLocation PointOfInstantiation,
413 SourceRange InstantiationRange) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000414 assert(SemaRef.NonInstantiationEntries <=
Richard Smith696e3122017-02-23 01:43:54 +0000415 SemaRef.CodeSynthesisContexts.size());
416 if ((SemaRef.CodeSynthesisContexts.size() -
Douglas Gregor84d49a22009-11-11 21:54:23 +0000417 SemaRef.NonInstantiationEntries)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000418 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregor79cf6032009-03-10 20:44:00 +0000419 return false;
420
Mike Stump11289f42009-09-09 15:08:12 +0000421 SemaRef.Diag(PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000422 diag::err_template_recursion_depth_exceeded)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000423 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregor79cf6032009-03-10 20:44:00 +0000424 << InstantiationRange;
425 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000426 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000427 return true;
428}
429
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000430/// Prints the current instantiation stack through a series of
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000431/// notes.
432void Sema::PrintInstantiationStack() {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000433 // Determine which template instantiations to skip, if any.
Richard Smith696e3122017-02-23 01:43:54 +0000434 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000435 unsigned Limit = Diags.getTemplateBacktraceLimit();
Richard Smith696e3122017-02-23 01:43:54 +0000436 if (Limit && Limit < CodeSynthesisContexts.size()) {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000437 SkipStart = Limit / 2 + Limit % 2;
Richard Smith696e3122017-02-23 01:43:54 +0000438 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000439 }
440
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000441 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000442 unsigned InstantiationIdx = 0;
Richard Smith696e3122017-02-23 01:43:54 +0000443 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
444 Active = CodeSynthesisContexts.rbegin(),
445 ActiveEnd = CodeSynthesisContexts.rend();
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000446 Active != ActiveEnd;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000447 ++Active, ++InstantiationIdx) {
448 // Skip this instantiation?
449 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
450 if (InstantiationIdx == SkipStart) {
451 // Note that we're skipping instantiations.
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000452 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000453 diag::note_instantiation_contexts_suppressed)
Richard Smith696e3122017-02-23 01:43:54 +0000454 << unsigned(CodeSynthesisContexts.size() - Limit);
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000455 }
456 continue;
457 }
458
Douglas Gregor79cf6032009-03-10 20:44:00 +0000459 switch (Active->Kind) {
Richard Smith696e3122017-02-23 01:43:54 +0000460 case CodeSynthesisContext::TemplateInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000461 Decl *D = Active->Entity;
Douglas Gregor85673582009-05-18 17:01:57 +0000462 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
463 unsigned DiagID = diag::note_template_member_class_here;
464 if (isa<ClassTemplateSpecializationDecl>(Record))
465 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000466 Diags.Report(Active->PointOfInstantiation, DiagID)
Richard Smith792c22d2016-12-24 04:09:05 +0000467 << Record << Active->InstantiationRange;
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000468 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +0000469 unsigned DiagID;
470 if (Function->getPrimaryTemplate())
471 DiagID = diag::note_function_template_spec_here;
472 else
473 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000474 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000475 << Function
476 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000477 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000478 Diags.Report(Active->PointOfInstantiation,
Larisse Voufodbd65772013-08-14 20:15:02 +0000479 VD->isStaticDataMember()?
480 diag::note_template_static_data_member_def_here
481 : diag::note_template_variable_def_here)
Richard Smith3f1b5d02011-05-05 21:57:07 +0000482 << VD
483 << Active->InstantiationRange;
Richard Smith4b38ded2012-03-14 23:13:10 +0000484 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
485 Diags.Report(Active->PointOfInstantiation,
486 diag::note_template_enum_def_here)
487 << ED
488 << Active->InstantiationRange;
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000489 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
490 Diags.Report(Active->PointOfInstantiation,
491 diag::note_template_nsdmi_here)
492 << FD << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000493 } else {
494 Diags.Report(Active->PointOfInstantiation,
495 diag::note_template_type_alias_instantiation_here)
496 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000497 << Active->InstantiationRange;
Douglas Gregor85673582009-05-18 17:01:57 +0000498 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000499 break;
500 }
501
Richard Smith696e3122017-02-23 01:43:54 +0000502 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
Richard Smith54f18e82016-08-31 02:15:21 +0000503 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000504 SmallVector<char, 128> TemplateArgsStr;
505 llvm::raw_svector_ostream OS(TemplateArgsStr);
506 Template->printName(OS);
Serge Pavlov03e672c2017-11-28 16:14:14 +0000507 printTemplateArgumentList(OS, Active->template_arguments(),
508 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000509 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000510 diag::note_default_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000511 << OS.str()
Douglas Gregor79cf6032009-03-10 20:44:00 +0000512 << Active->InstantiationRange;
513 break;
514 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000515
Richard Smith696e3122017-02-23 01:43:54 +0000516 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000517 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000518 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000519 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000520 << FnTmpl
521 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
522 Active->TemplateArgs,
523 Active->NumTemplateArgs)
524 << Active->InstantiationRange;
Douglas Gregor637d9982009-06-10 23:47:09 +0000525 break;
526 }
Mike Stump11289f42009-09-09 15:08:12 +0000527
Richard Smith696e3122017-02-23 01:43:54 +0000528 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
Richard Smithe68a38f2016-12-24 04:20:31 +0000529 if (FunctionTemplateDecl *FnTmpl =
530 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000531 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000532 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000533 << FnTmpl
534 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
535 Active->TemplateArgs,
536 Active->NumTemplateArgs)
537 << Active->InstantiationRange;
Richard Smithe68a38f2016-12-24 04:20:31 +0000538 } else {
539 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
540 isa<VarTemplateSpecializationDecl>(Active->Entity);
Richard Smith0e617ec2016-12-27 07:56:27 +0000541 bool IsTemplate = false;
Richard Smithe68a38f2016-12-24 04:20:31 +0000542 TemplateParameterList *Params;
Richard Smith0e617ec2016-12-27 07:56:27 +0000543 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
544 IsTemplate = true;
545 Params = D->getTemplateParameters();
546 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
Richard Smithe68a38f2016-12-24 04:20:31 +0000547 Active->Entity)) {
548 Params = D->getTemplateParameters();
549 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
550 Active->Entity)) {
551 Params = D->getTemplateParameters();
552 } else {
553 llvm_unreachable("unexpected template kind");
554 }
555
Richard Smithe68a38f2016-12-24 04:20:31 +0000556 Diags.Report(Active->PointOfInstantiation,
557 diag::note_deduced_template_arg_substitution_here)
Richard Smith0e617ec2016-12-27 07:56:27 +0000558 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
Richard Smithe68a38f2016-12-24 04:20:31 +0000559 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
560 Active->NumTemplateArgs)
561 << Active->InstantiationRange;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000562 }
563 break;
Richard Smithe68a38f2016-12-24 04:20:31 +0000564 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000565
Richard Smith696e3122017-02-23 01:43:54 +0000566 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000567 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson657bad42009-09-05 05:14:19 +0000568 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +0000569
Benjamin Kramer9170e912013-02-22 15:46:01 +0000570 SmallVector<char, 128> TemplateArgsStr;
571 llvm::raw_svector_ostream OS(TemplateArgsStr);
572 FD->printName(OS);
Serge Pavlov03e672c2017-11-28 16:14:14 +0000573 printTemplateArgumentList(OS, Active->template_arguments(),
574 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000575 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000576 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000577 << OS.str()
Anders Carlsson657bad42009-09-05 05:14:19 +0000578 << Active->InstantiationRange;
579 break;
580 }
Mike Stump11289f42009-09-09 15:08:12 +0000581
Richard Smith696e3122017-02-23 01:43:54 +0000582 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000583 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000584 std::string Name;
585 if (!Parm->getName().empty())
586 Name = std::string(" '") + Parm->getName().str() + "'";
Craig Topperc3ec1492014-05-26 06:22:03 +0000587
588 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000589 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
590 TemplateParams = Template->getTemplateParameters();
591 else
592 TemplateParams =
593 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
594 ->getTemplateParameters();
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000595 Diags.Report(Active->PointOfInstantiation,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000596 diag::note_prior_template_arg_substitution)
597 << isa<TemplateTemplateParmDecl>(Parm)
598 << Name
Douglas Gregorca4686d2011-01-04 23:35:54 +0000599 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000600 Active->TemplateArgs,
601 Active->NumTemplateArgs)
602 << Active->InstantiationRange;
603 break;
604 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000605
Richard Smith696e3122017-02-23 01:43:54 +0000606 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
Craig Topperc3ec1492014-05-26 06:22:03 +0000607 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000608 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
609 TemplateParams = Template->getTemplateParameters();
610 else
611 TemplateParams =
612 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
613 ->getTemplateParameters();
614
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000615 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000616 diag::note_template_default_arg_checking)
Douglas Gregorca4686d2011-01-04 23:35:54 +0000617 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000618 Active->TemplateArgs,
619 Active->NumTemplateArgs)
620 << Active->InstantiationRange;
621 break;
622 }
Richard Smithf623c962012-04-17 00:58:00 +0000623
Richard Smith696e3122017-02-23 01:43:54 +0000624 case CodeSynthesisContext::ExceptionSpecInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000625 Diags.Report(Active->PointOfInstantiation,
626 diag::note_template_exception_spec_instantiation_here)
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000627 << cast<FunctionDecl>(Active->Entity)
Richard Smithf623c962012-04-17 00:58:00 +0000628 << Active->InstantiationRange;
629 break;
Richard Smith13381222017-02-23 21:43:43 +0000630
631 case CodeSynthesisContext::DeclaringSpecialMember:
632 Diags.Report(Active->PointOfInstantiation,
633 diag::note_in_declaration_of_implicit_special_member)
634 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
635 break;
Richard Smith883dbc42017-05-25 22:47:05 +0000636
Gabor Horvath207e7b12018-02-10 14:04:45 +0000637 case CodeSynthesisContext::DefiningSynthesizedFunction: {
Richard Smith883dbc42017-05-25 22:47:05 +0000638 // FIXME: For synthesized members other than special members, produce a note.
639 auto *MD = dyn_cast<CXXMethodDecl>(Active->Entity);
640 auto CSM = MD ? getSpecialMember(MD) : CXXInvalid;
641 if (CSM != CXXInvalid) {
642 Diags.Report(Active->PointOfInstantiation,
643 diag::note_member_synthesized_at)
644 << CSM << Context.getTagDeclType(MD->getParent());
645 }
646 break;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000647 }
Gabor Horvath207e7b12018-02-10 14:04:45 +0000648
649 case CodeSynthesisContext::Memoization:
650 break;
651 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000652 }
653}
654
David Blaikie05785d12013-02-20 22:23:23 +0000655Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregoredb76852011-01-27 22:31:44 +0000656 if (InNonInstantiationSFINAEContext)
Craig Topperc3ec1492014-05-26 06:22:03 +0000657 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregoredb76852011-01-27 22:31:44 +0000658
Richard Smith696e3122017-02-23 01:43:54 +0000659 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
660 Active = CodeSynthesisContexts.rbegin(),
661 ActiveEnd = CodeSynthesisContexts.rend();
Douglas Gregor33834512009-06-14 07:33:30 +0000662 Active != ActiveEnd;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000663 ++Active)
664 {
Richard Smith13381222017-02-23 21:43:43 +0000665 switch (Active->Kind) {
Richard Smith696e3122017-02-23 01:43:54 +0000666 case CodeSynthesisContext::TemplateInstantiation:
Richard Smith72249ba2012-04-26 07:24:08 +0000667 // An instantiation of an alias template may or may not be a SFINAE
668 // context, depending on what else is on the stack.
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000669 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smith72249ba2012-04-26 07:24:08 +0000670 break;
671 // Fall through.
Richard Smith696e3122017-02-23 01:43:54 +0000672 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
673 case CodeSynthesisContext::ExceptionSpecInstantiation:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000674 // This is a template instantiation, so there is no SFINAE.
David Blaikie7a30dc52013-02-21 01:47:18 +0000675 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000676
Richard Smith696e3122017-02-23 01:43:54 +0000677 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
678 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
679 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000680 // A default template argument instantiation and substitution into
681 // template parameters with arguments for prior parameters may or may
682 // not be a SFINAE context; look further up the stack.
Douglas Gregor33834512009-06-14 07:33:30 +0000683 break;
Mike Stump11289f42009-09-09 15:08:12 +0000684
Richard Smith696e3122017-02-23 01:43:54 +0000685 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
686 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000687 // We're either substitution explicitly-specified template arguments
688 // or deduced template arguments, so SFINAE applies.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000689 assert(Active->DeductionInfo && "Missing deduction info pointer");
690 return Active->DeductionInfo;
Richard Smith13381222017-02-23 21:43:43 +0000691
692 case CodeSynthesisContext::DeclaringSpecialMember:
Richard Smith883dbc42017-05-25 22:47:05 +0000693 case CodeSynthesisContext::DefiningSynthesizedFunction:
Richard Smith13381222017-02-23 21:43:43 +0000694 // This happens in a context unrelated to template instantiation, so
695 // there is no SFINAE.
696 return None;
Gabor Horvath207e7b12018-02-10 14:04:45 +0000697
698 case CodeSynthesisContext::Memoization:
699 break;
Douglas Gregor33834512009-06-14 07:33:30 +0000700 }
Richard Smith13381222017-02-23 21:43:43 +0000701
702 // The inner context was transparent for SFINAE. If it occurred within a
703 // non-instantiation SFINAE context, then SFINAE applies.
704 if (Active->SavedInNonInstantiationSFINAEContext)
705 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregor33834512009-06-14 07:33:30 +0000706 }
707
David Blaikie7a30dc52013-02-21 01:47:18 +0000708 return None;
Douglas Gregor33834512009-06-14 07:33:30 +0000709}
710
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000711/// Retrieve the depth and index of a parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000712static std::pair<unsigned, unsigned>
713getDepthAndIndex(NamedDecl *ND) {
714 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
715 return std::make_pair(TTP->getDepth(), TTP->getIndex());
716
717 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
718 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
719
720 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
721 return std::make_pair(TTP->getDepth(), TTP->getIndex());
722}
723
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000724//===----------------------------------------------------------------------===/
725// Template Instantiation for Types
726//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000727namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000728 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000729 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000730 SourceLocation Loc;
731 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000732
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000733 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000734 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000735
736 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000737 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000738 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000739 DeclarationName Entity)
740 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000741 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000742
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000743 /// Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-08-04 16:50:30 +0000744 /// transformed.
745 ///
746 /// For the purposes of template instantiation, a type has already been
747 /// transformed if it is NULL or if it is not dependent.
Douglas Gregor5597ab42010-05-07 23:12:07 +0000748 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000749
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000750 /// Returns the location of the entity being instantiated, if known.
Douglas Gregord6ff3322009-08-04 16:50:30 +0000751 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000752
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000753 /// Returns the name of the entity being instantiated, if any.
Douglas Gregord6ff3322009-08-04 16:50:30 +0000754 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000755
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000756 /// Sets the "base" location and entity when that
Douglas Gregoref6ab412009-10-27 06:26:26 +0000757 /// information is known based on another transformation.
758 void setBase(SourceLocation Loc, DeclarationName Entity) {
759 this->Loc = Loc;
760 this->Entity = Entity;
761 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000762
763 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
764 SourceRange PatternRange,
Robert Wilhelm16e94b92013-08-09 18:02:13 +0000765 ArrayRef<UnexpandedParameterPack> Unexpanded,
766 bool &ShouldExpand, bool &RetainExpansion,
David Blaikie05785d12013-02-20 22:23:23 +0000767 Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000768 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
769 PatternRange, Unexpanded,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000770 TemplateArgs,
771 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000772 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000773 NumExpansions);
774 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000775
Douglas Gregorf3010112011-01-07 16:43:16 +0000776 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
777 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
778 }
779
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000780 TemplateArgument ForgetPartiallySubstitutedPack() {
781 TemplateArgument Result;
782 if (NamedDecl *PartialPack
783 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
784 MultiLevelTemplateArgumentList &TemplateArgs
785 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
786 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000787 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000788 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
789 Result = TemplateArgs(Depth, Index);
790 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
791 }
792 }
793
794 return Result;
795 }
796
797 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
798 if (Arg.isNull())
799 return;
800
801 if (NamedDecl *PartialPack
802 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
803 MultiLevelTemplateArgumentList &TemplateArgs
804 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
805 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000806 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000807 TemplateArgs.setArgument(Depth, Index, Arg);
808 }
809 }
810
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000811 /// Transform the given declaration by instantiating a reference to
Douglas Gregord6ff3322009-08-04 16:50:30 +0000812 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000813 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000814
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000815 void transformAttrs(Decl *Old, Decl *New) {
816 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
817 }
818
819 void transformedLocalDecl(Decl *Old, Decl *New) {
Richard Smithc38498f2015-04-27 21:27:54 +0000820 // If we've instantiated the call operator of a lambda or the call
821 // operator template of a generic lambda, update the "instantiation of"
822 // information.
823 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
824 if (NewMD && isLambdaCallOperator(NewMD)) {
825 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
826 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
827 NewTD->setInstantiatedFromMemberTemplate(
828 OldMD->getDescribedFunctionTemplate());
829 else
830 NewMD->setInstantiationOfMemberFunction(OldMD,
831 TSK_ImplicitInstantiation);
832 }
833
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000834 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
Richard Smithc7649dc2016-03-23 20:07:07 +0000835
836 // We recreated a local declaration, but not by instantiating it. There
837 // may be pending dependent diagnostics to produce.
838 if (auto *DC = dyn_cast<DeclContext>(Old))
839 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000840 }
841
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000842 /// Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000843 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000844 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000845
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000846 /// Transform the first qualifier within a scope by instantiating the
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000847 /// declaration.
848 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
849
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000850 /// Rebuild the exception declaration and register the declaration
Douglas Gregorebe10102009-08-20 07:17:43 +0000851 /// as an instantiated local.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000852 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000853 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000854 SourceLocation StartLoc,
855 SourceLocation NameLoc,
856 IdentifierInfo *Name);
Mike Stump11289f42009-09-09 15:08:12 +0000857
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000858 /// Rebuild the Objective-C exception declaration and register the
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000859 /// declaration as an instantiated local.
860 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
861 TypeSourceInfo *TSInfo, QualType T);
862
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000863 /// Check for tag mismatches when instantiating an
John McCall7f41d982009-09-11 04:59:25 +0000864 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000865 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
866 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000867 NestedNameSpecifierLoc QualifierLoc,
868 QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000869
Craig Topperc3ec1492014-05-26 06:22:03 +0000870 TemplateName
871 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
872 SourceLocation NameLoc,
873 QualType ObjectType = QualType(),
Richard Smithfd3dae02017-01-20 00:20:39 +0000874 NamedDecl *FirstQualifierInScope = nullptr,
875 bool AllowInjectedClassName = false);
Douglas Gregor9db53502011-03-02 18:07:45 +0000876
Tyler Nowickic724a83e2014-10-12 20:46:07 +0000877 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
878
John McCalldadc5752010-08-24 06:29:42 +0000879 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
880 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
881 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000882
John McCalldadc5752010-08-24 06:29:42 +0000883 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000884 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000885 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
886 SubstNonTypeTemplateParmPackExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000887
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000888 /// Rebuild a DeclRefExpr for a ParmVarDecl reference.
Richard Smithb15fe3a2012-09-12 00:56:43 +0000889 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
890
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000891 /// Transform a reference to a function parameter pack.
Richard Smithb15fe3a2012-09-12 00:56:43 +0000892 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
893 ParmVarDecl *PD);
894
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000895 /// Transform a FunctionParmPackExpr which was built when we couldn't
Richard Smithb15fe3a2012-09-12 00:56:43 +0000896 /// expand a function parameter pack reference which refers to an expanded
897 /// pack.
898 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
899
Hans Wennborge113c202014-09-18 16:01:32 +0000900 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
Richard Smith2e321552014-11-12 02:00:47 +0000901 FunctionProtoTypeLoc TL) {
902 // Call the base version; it will forward to our overridden version below.
903 return inherited::TransformFunctionProtoType(TLB, TL);
904 }
905
906 template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +0000907 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
908 FunctionProtoTypeLoc TL,
909 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +0000910 unsigned ThisTypeQuals,
911 Fn TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +0000912
Douglas Gregor715e4612011-01-14 22:40:04 +0000913 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +0000914 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +0000915 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +0000916 bool ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +0000917
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000918 /// Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +0000919 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +0000920 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000921 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000922
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000923 /// Transforms an already-substituted template type parameter pack
Douglas Gregorada4b792011-01-14 02:55:32 +0000924 /// into either itself (if we aren't substituting into its pack expansion)
925 /// or the appropriate substituted argument.
926 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
927 SubstTemplateTypeParmPackTypeLoc TL);
928
Richard Smith2589b9802012-07-25 03:56:55 +0000929 ExprResult TransformLambdaExpr(LambdaExpr *E) {
930 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
931 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
932 }
933
David Majnemerb1004102014-03-02 18:46:05 +0000934 TemplateParameterList *TransformTemplateParameterList(
Faisal Vali2cba1332013-10-23 06:44:28 +0000935 TemplateParameterList *OrigTPL) {
936 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
937
938 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
939 TemplateDeclInstantiator DeclInstantiator(getSema(),
940 /* DeclContext *Owner */ Owner, TemplateArgs);
941 return DeclInstantiator.SubstTemplateParams(OrigTPL);
942 }
John McCall7c454bb2011-07-15 05:09:51 +0000943 private:
944 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
945 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +0000946 TemplateArgument arg);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000947 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000948}
Douglas Gregor04318252009-07-06 15:59:29 +0000949
Douglas Gregor5597ab42010-05-07 23:12:07 +0000950bool TemplateInstantiator::AlreadyTransformed(QualType T) {
951 if (T.isNull())
952 return true;
953
Douglas Gregor678d76c2011-07-01 01:22:09 +0000954 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +0000955 return false;
956
957 getSema().MarkDeclarationsReferencedInType(Loc, T);
958 return true;
959}
960
Eli Friedman8917ad52013-07-19 19:40:38 +0000961static TemplateArgument
962getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
963 assert(S.ArgumentPackSubstitutionIndex >= 0);
964 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
965 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
966 if (Arg.isPackExpansion())
967 Arg = Arg.getPackExpansionPattern();
968 return Arg;
969}
970
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000971Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000972 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +0000973 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000974
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000975 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000976 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +0000977 // If the corresponding template argument is NULL or non-existent, it's
978 // because we are performing instantiation from explicitly-specified
979 // template arguments in a function template, but there were some
980 // arguments left unspecified.
981 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
982 TTP->getPosition()))
983 return D;
984
Douglas Gregorf5500772011-01-05 15:48:55 +0000985 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
986
987 if (TTP->isParameterPack()) {
988 assert(Arg.getKind() == TemplateArgument::Pack &&
989 "Missing argument pack");
Eli Friedman8917ad52013-07-19 19:40:38 +0000990 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorf5500772011-01-05 15:48:55 +0000991 }
992
Richard Smith1abacfc2017-08-29 22:14:43 +0000993 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000994 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +0000995 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000996 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +0000997 }
Mike Stump11289f42009-09-09 15:08:12 +0000998
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000999 // Fall through to find the instantiated declaration for this template
1000 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +00001001 }
Mike Stump11289f42009-09-09 15:08:12 +00001002
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001003 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +00001004}
1005
Douglas Gregor25289362010-03-01 17:25:41 +00001006Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +00001007 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +00001008 if (!Inst)
Craig Topperc3ec1492014-05-26 06:22:03 +00001009 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001010
Douglas Gregorebe10102009-08-20 07:17:43 +00001011 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1012 return Inst;
1013}
1014
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001015NamedDecl *
1016TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1017 SourceLocation Loc) {
1018 // If the first part of the nested-name-specifier was a template type
1019 // parameter, instantiate that type parameter down to a tag type.
1020 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1021 const TemplateTypeParmType *TTP
1022 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001023
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001024 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001025 // FIXME: This needs testing w/ member access expressions.
1026 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1027
1028 if (TTP->isParameterPack()) {
1029 assert(Arg.getKind() == TemplateArgument::Pack &&
1030 "Missing argument pack");
1031
Douglas Gregore1d60df2011-01-14 23:41:42 +00001032 if (getSema().ArgumentPackSubstitutionIndex == -1)
Craig Topperc3ec1492014-05-26 06:22:03 +00001033 return nullptr;
1034
Eli Friedman8917ad52013-07-19 19:40:38 +00001035 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001036 }
1037
1038 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001039 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001040 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001041
1042 if (const TagType *Tag = T->getAs<TagType>())
1043 return Tag->getDecl();
1044
1045 // The resulting type is not a tag; complain.
1046 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
Craig Topperc3ec1492014-05-26 06:22:03 +00001047 return nullptr;
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001048 }
1049 }
1050
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001051 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001052}
1053
Douglas Gregorebe10102009-08-20 07:17:43 +00001054VarDecl *
1055TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +00001056 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001057 SourceLocation StartLoc,
1058 SourceLocation NameLoc,
1059 IdentifierInfo *Name) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00001060 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001061 StartLoc, NameLoc, Name);
Douglas Gregorf4e837f2010-04-26 17:57:08 +00001062 if (Var)
1063 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1064 return Var;
1065}
1066
1067VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1068 TypeSourceInfo *TSInfo,
1069 QualType T) {
1070 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1071 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +00001072 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1073 return Var;
1074}
1075
John McCall7f41d982009-09-11 04:59:25 +00001076QualType
John McCall954b5de2010-11-04 19:04:38 +00001077TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1078 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001079 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara6150c882010-05-11 21:36:43 +00001080 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +00001081 if (const TagType *TT = T->getAs<TagType>()) {
1082 TagDecl* TD = TT->getDecl();
1083
John McCall954b5de2010-11-04 19:04:38 +00001084 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +00001085
John McCall7f41d982009-09-11 04:59:25 +00001086 IdentifierInfo *Id = TD->getIdentifier();
1087
1088 // TODO: should we even warn on struct/class mismatches for this? Seems
1089 // like it's likely to produce a lot of spurious errors.
Richard Smith80b3c5a2012-08-17 00:12:27 +00001090 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001091 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieucaa33d32011-06-10 03:11:26 +00001092 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001093 TagLocation, Id)) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001094 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1095 << Id
1096 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1097 TD->getKindName());
1098 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1099 }
John McCall7f41d982009-09-11 04:59:25 +00001100 }
1101 }
1102
John McCall954b5de2010-11-04 19:04:38 +00001103 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1104 Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001105 QualifierLoc,
1106 T);
John McCall7f41d982009-09-11 04:59:25 +00001107}
1108
Richard Smithfd3dae02017-01-20 00:20:39 +00001109TemplateName TemplateInstantiator::TransformTemplateName(
1110 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1111 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1112 bool AllowInjectedClassName) {
Douglas Gregor9db53502011-03-02 18:07:45 +00001113 if (TemplateTemplateParmDecl *TTP
1114 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1115 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1116 // If the corresponding template argument is NULL or non-existent, it's
1117 // because we are performing instantiation from explicitly-specified
1118 // template arguments in a function template, but there were some
1119 // arguments left unspecified.
1120 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1121 TTP->getPosition()))
1122 return Name;
1123
1124 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1125
1126 if (TTP->isParameterPack()) {
1127 assert(Arg.getKind() == TemplateArgument::Pack &&
1128 "Missing argument pack");
1129
1130 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1131 // We have the template argument pack to substitute, but we're not
1132 // actually expanding the enclosing pack expansion yet. So, just
1133 // keep the entire argument pack.
1134 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1135 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001136
1137 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor9db53502011-03-02 18:07:45 +00001138 }
1139
Richard Smith1abacfc2017-08-29 22:14:43 +00001140 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001141 assert(!Template.isNull() && "Null template template argument");
Richard Smith1abacfc2017-08-29 22:14:43 +00001142 assert(!Template.getAsQualifiedTemplateName() &&
1143 "template decl to substitute is qualified?");
John McCalld9dfe3a2011-06-30 08:33:18 +00001144
1145 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregor9db53502011-03-02 18:07:45 +00001146 return Template;
1147 }
1148 }
1149
1150 if (SubstTemplateTemplateParmPackStorage *SubstPack
1151 = Name.getAsSubstTemplateTemplateParmPack()) {
1152 if (getSema().ArgumentPackSubstitutionIndex == -1)
1153 return Name;
1154
Eli Friedman8917ad52013-07-19 19:40:38 +00001155 TemplateArgument Arg = SubstPack->getArgumentPack();
1156 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Richard Smith1abacfc2017-08-29 22:14:43 +00001157 return Arg.getAsTemplate().getNameToSubstitute();
Douglas Gregor9db53502011-03-02 18:07:45 +00001158 }
Richard Smithfd3dae02017-01-20 00:20:39 +00001159
1160 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1161 FirstQualifierInScope,
1162 AllowInjectedClassName);
Douglas Gregor9db53502011-03-02 18:07:45 +00001163}
1164
John McCalldadc5752010-08-24 06:29:42 +00001165ExprResult
John McCall47f29ea2009-12-08 09:21:05 +00001166TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +00001167 if (!E->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001168 return E;
Anders Carlsson0b209a82009-09-11 01:22:35 +00001169
Wei Panc354d212013-09-16 13:57:27 +00001170 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
Anders Carlsson0b209a82009-09-11 01:22:35 +00001171}
1172
John McCalldadc5752010-08-24 06:29:42 +00001173ExprResult
John McCall13481c52010-02-06 08:42:39 +00001174TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001175 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +00001176 // If the corresponding template argument is NULL or non-existent, it's
1177 // because we are performing instantiation from explicitly-specified
1178 // template arguments in a function template, but there were some
1179 // arguments left unspecified.
1180 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1181 NTTP->getPosition()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001182 return E;
Mike Stump11289f42009-09-09 15:08:12 +00001183
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001184 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
Richard Smithb4f96252017-02-21 06:30:38 +00001185
1186 if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1187 // We're performing a partial substitution, so the substituted argument
1188 // could be dependent. As a result we can't create a SubstNonType*Expr
1189 // node now, since that represents a fully-substituted argument.
1190 // FIXME: We should have some AST representation for this.
1191 if (Arg.getKind() == TemplateArgument::Pack) {
1192 // FIXME: This won't work for alias templates.
1193 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1194 "unexpected pack arguments in partial substitution");
1195 Arg = Arg.pack_begin()->getPackExpansionPattern();
1196 }
1197 assert(Arg.getKind() == TemplateArgument::Expression &&
1198 "unexpected nontype template argument kind in partial substitution");
1199 return Arg.getAsExpr();
1200 }
1201
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001202 if (NTTP->isParameterPack()) {
1203 assert(Arg.getKind() == TemplateArgument::Pack &&
1204 "Missing argument pack");
1205
1206 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001207 // We have an argument pack, but we can't select a particular argument
1208 // out of it yet. Therefore, we'll build an expression to hold on to that
1209 // argument pack.
1210 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1211 E->getLocation(),
1212 NTTP->getDeclName());
1213 if (TargetType.isNull())
1214 return ExprError();
Richard Smithf1f20e62018-02-14 02:07:53 +00001215
1216 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1217 TargetType.getNonLValueExprType(SemaRef.Context),
1218 TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP,
1219 E->getLocation(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001220 }
1221
Eli Friedman8917ad52013-07-19 19:40:38 +00001222 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001223 }
Mike Stump11289f42009-09-09 15:08:12 +00001224
John McCall7c454bb2011-07-15 05:09:51 +00001225 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1226}
1227
Tyler Nowickic724a83e2014-10-12 20:46:07 +00001228const LoopHintAttr *
1229TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1230 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1231
1232 if (TransformedExpr == LH->getValue())
1233 return LH;
1234
1235 // Generate error if there is a problem with the value.
1236 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1237 return LH;
1238
1239 // Create new LoopHintValueAttr with integral expression in place of the
1240 // non-type template parameter.
1241 return LoopHintAttr::CreateImplicit(
1242 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1243 LH->getState(), TransformedExpr, LH->getRange());
1244}
1245
John McCall7c454bb2011-07-15 05:09:51 +00001246ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1247 NonTypeTemplateParmDecl *parm,
1248 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001249 TemplateArgument arg) {
John McCall7c454bb2011-07-15 05:09:51 +00001250 ExprResult result;
1251 QualType type;
1252
John McCall13481c52010-02-06 08:42:39 +00001253 // The template argument itself might be an expression, in which
1254 // case we just return that expression.
John McCall7c454bb2011-07-15 05:09:51 +00001255 if (arg.getKind() == TemplateArgument::Expression) {
1256 Expr *argExpr = arg.getAsExpr();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001257 result = argExpr;
John McCall7c454bb2011-07-15 05:09:51 +00001258 type = argExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001259
Eli Friedmanb826a002012-09-26 02:36:12 +00001260 } else if (arg.getKind() == TemplateArgument::Declaration ||
1261 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001262 ValueDecl *VD;
Eli Friedmanb826a002012-09-26 02:36:12 +00001263 if (arg.getKind() == TemplateArgument::Declaration) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00001264 VD = arg.getAsDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001265
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001266 // Find the instantiation of the template argument. This is
1267 // required for nested templates.
1268 VD = cast_or_null<ValueDecl>(
1269 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1270 if (!VD)
1271 return ExprError();
1272 } else {
1273 // Propagate NULL template argument.
Craig Topperc3ec1492014-05-26 06:22:03 +00001274 VD = nullptr;
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001275 }
1276
John McCall15dda372010-02-06 10:23:53 +00001277 // Derive the type we want the substituted decl to have. This had
1278 // better be non-dependent, or these checks will have serious problems.
John McCall7c454bb2011-07-15 05:09:51 +00001279 if (parm->isExpandedParameterPack()) {
1280 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1281 } else if (parm->isParameterPack() &&
1282 isa<PackExpansionType>(parm->getType())) {
1283 type = SemaRef.SubstType(
1284 cast<PackExpansionType>(parm->getType())->getPattern(),
1285 TemplateArgs, loc, parm->getDeclName());
1286 } else {
Richard Smith5f274382016-09-28 23:55:27 +00001287 type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1288 TemplateArgs, loc, parm->getDeclName());
John McCall7c454bb2011-07-15 05:09:51 +00001289 }
1290 assert(!type.isNull() && "type substitution failed for param type");
1291 assert(!type->isDependentType() && "param type still dependent");
1292 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCall13481c52010-02-06 08:42:39 +00001293
John McCall7c454bb2011-07-15 05:09:51 +00001294 if (!result.isInvalid()) type = result.get()->getType();
1295 } else {
1296 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1297
1298 // Note that this type can be different from the type of 'result',
1299 // e.g. if it's an enum type.
1300 type = arg.getIntegralType();
1301 }
1302 if (result.isInvalid()) return ExprError();
1303
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001304 Expr *resultExpr = result.get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001305 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1306 type, resultExpr->getValueKind(), loc, parm, resultExpr);
John McCall13481c52010-02-06 08:42:39 +00001307}
1308
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001309ExprResult
1310TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1311 SubstNonTypeTemplateParmPackExpr *E) {
1312 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1313 // We aren't expanding the parameter pack, so just return ourselves.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001314 return E;
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001315 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001316
1317 TemplateArgument Arg = E->getArgumentPack();
1318 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall7c454bb2011-07-15 05:09:51 +00001319 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1320 E->getParameterPackLocation(),
1321 Arg);
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001322}
John McCall13481c52010-02-06 08:42:39 +00001323
John McCalldadc5752010-08-24 06:29:42 +00001324ExprResult
Richard Smithb15fe3a2012-09-12 00:56:43 +00001325TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1326 SourceLocation Loc) {
1327 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1328 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1329}
1330
1331ExprResult
1332TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1333 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1334 // We can expand this parameter pack now.
1335 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1336 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1337 if (!VD)
1338 return ExprError();
1339 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1340 }
1341
1342 QualType T = TransformType(E->getType());
1343 if (T.isNull())
1344 return ExprError();
1345
1346 // Transform each of the parameter expansions into the corresponding
1347 // parameters in the instantiation of the function decl.
James Y Knight48fefa32015-09-30 14:04:23 +00001348 SmallVector<ParmVarDecl *, 8> Parms;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001349 Parms.reserve(E->getNumExpansions());
1350 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1351 I != End; ++I) {
1352 ParmVarDecl *D =
1353 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1354 if (!D)
1355 return ExprError();
1356 Parms.push_back(D);
1357 }
1358
1359 return FunctionParmPackExpr::Create(getSema().Context, T,
1360 E->getParameterPack(),
1361 E->getParameterPackLocation(), Parms);
1362}
1363
1364ExprResult
1365TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1366 ParmVarDecl *PD) {
1367 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1368 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1369 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1370 assert(Found && "no instantiation for parameter pack");
1371
1372 Decl *TransformedDecl;
1373 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
Nico Weberc153d242014-07-28 00:02:09 +00001374 // If this is a reference to a function parameter pack which we can
1375 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
Richard Smithb15fe3a2012-09-12 00:56:43 +00001376 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1377 QualType T = TransformType(E->getType());
1378 if (T.isNull())
1379 return ExprError();
1380 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1381 E->getExprLoc(), *Pack);
1382 }
1383
1384 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1385 } else {
1386 TransformedDecl = Found->get<Decl*>();
1387 }
1388
1389 // We have either an unexpanded pack or a specific expansion.
1390 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1391 E->getExprLoc());
1392}
1393
1394ExprResult
John McCall13481c52010-02-06 08:42:39 +00001395TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1396 NamedDecl *D = E->getDecl();
Richard Smithb15fe3a2012-09-12 00:56:43 +00001397
1398 // Handle references to non-type template parameters and non-type template
1399 // parameter packs.
John McCall13481c52010-02-06 08:42:39 +00001400 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1401 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1402 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor954de172009-10-31 17:21:17 +00001403
1404 // We have a non-type template parameter that isn't fully substituted;
1405 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001406 }
Mike Stump11289f42009-09-09 15:08:12 +00001407
Richard Smithb15fe3a2012-09-12 00:56:43 +00001408 // Handle references to function parameter packs.
1409 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1410 if (PD->isParameterPack())
1411 return TransformFunctionParmPackRefExpr(E, PD);
1412
John McCall47f29ea2009-12-08 09:21:05 +00001413 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001414}
1415
John McCalldadc5752010-08-24 06:29:42 +00001416ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001417 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001418 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1419 getDescribedFunctionTemplate() &&
1420 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001421 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1422 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1423 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001424}
1425
Richard Smith2e321552014-11-12 02:00:47 +00001426template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +00001427QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1428 FunctionProtoTypeLoc TL,
1429 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +00001430 unsigned ThisTypeQuals,
1431 Fn TransformExceptionSpec) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001432 // We need a local instantiation scope for this function prototype.
1433 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
Richard Smith2e321552014-11-12 02:00:47 +00001434 return inherited::TransformFunctionProtoType(
1435 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +00001436}
1437
John McCall58f10c32010-03-11 09:03:00 +00001438ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001439TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001440 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001441 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001442 bool ExpectParameterPack) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001443 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001444 NumExpansions, ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +00001445}
1446
Mike Stump11289f42009-09-09 15:08:12 +00001447QualType
John McCall550e0c22009-10-21 00:40:46 +00001448TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001449 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001450 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001451 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001452 // Replace the template type parameter with its corresponding
1453 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001454
1455 // If the corresponding template argument is NULL or doesn't exist, it's
1456 // because we are performing instantiation from explicitly-specified
1457 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001458 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001459 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1460 TemplateTypeParmTypeLoc NewTL
1461 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1462 NewTL.setNameLoc(TL.getNameLoc());
1463 return TL.getType();
1464 }
Mike Stump11289f42009-09-09 15:08:12 +00001465
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001466 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1467
1468 if (T->isParameterPack()) {
1469 assert(Arg.getKind() == TemplateArgument::Pack &&
1470 "Missing argument pack");
1471
1472 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001473 // We have the template argument pack, but we're not expanding the
1474 // enclosing pack expansion yet. Just save the template argument
1475 // pack for later substitution.
1476 QualType Result
1477 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1478 SubstTemplateTypeParmPackTypeLoc NewTL
1479 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1480 NewTL.setNameLoc(TL.getNameLoc());
1481 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001482 }
1483
Eli Friedman8917ad52013-07-19 19:40:38 +00001484 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001485 }
1486
1487 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001488 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001489
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001490 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001491
1492 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001493 QualType Result
1494 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1495 SubstTemplateTypeParmTypeLoc NewTL
1496 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1497 NewTL.setNameLoc(TL.getNameLoc());
1498 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001499 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001500
1501 // The template type parameter comes from an inner template (e.g.,
1502 // the template parameter list of a member template inside the
1503 // template we are instantiating). Create a new template type
1504 // parameter with the template "level" reduced by one.
Craig Topperc3ec1492014-05-26 06:22:03 +00001505 TemplateTypeParmDecl *NewTTPDecl = nullptr;
Chandler Carruth08836322011-05-01 00:51:33 +00001506 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1507 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1508 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1509
Richard Smithb4f96252017-02-21 06:30:38 +00001510 QualType Result = getSema().Context.getTemplateTypeParmType(
1511 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1512 T->isParameterPack(), NewTTPDecl);
John McCall550e0c22009-10-21 00:40:46 +00001513 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1514 NewTL.setNameLoc(TL.getNameLoc());
1515 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001516}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001517
Douglas Gregorada4b792011-01-14 02:55:32 +00001518QualType
1519TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1520 TypeLocBuilder &TLB,
1521 SubstTemplateTypeParmPackTypeLoc TL) {
1522 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1523 // We aren't expanding the parameter pack, so just return ourselves.
1524 SubstTemplateTypeParmPackTypeLoc NewTL
1525 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1526 NewTL.setNameLoc(TL.getNameLoc());
1527 return TL.getType();
1528 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001529
1530 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1531 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1532 QualType Result = Arg.getAsType();
1533
Douglas Gregorada4b792011-01-14 02:55:32 +00001534 Result = getSema().Context.getSubstTemplateTypeParmType(
1535 TL.getTypePtr()->getReplacedParameter(),
1536 Result);
1537 SubstTemplateTypeParmTypeLoc NewTL
1538 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1539 NewTL.setNameLoc(TL.getNameLoc());
1540 return Result;
1541}
1542
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001543/// Perform substitution on the type T with a given set of template
John McCall76d824f2009-08-25 22:02:44 +00001544/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001545///
1546/// This routine substitutes the given template arguments into the
1547/// type T and produces the instantiated type.
1548///
1549/// \param T the type into which the template arguments will be
1550/// substituted. If this type is not dependent, it will be returned
1551/// immediately.
1552///
James Dennett634962f2012-06-14 21:40:34 +00001553/// \param Args the template arguments that will be
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001554/// substituted for the top-level template parameters within T.
1555///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001556/// \param Loc the location in the source code where this substitution
1557/// is being performed. It will typically be the location of the
1558/// declarator (if we're instantiating the type of some declaration)
1559/// or the location of the type in the source code (if, e.g., we're
1560/// instantiating the type of a cast expression).
1561///
1562/// \param Entity the name of the entity associated with a declaration
1563/// being instantiated (if any). May be empty to indicate that there
1564/// is no such entity (if, e.g., this is a type that occurs as part of
1565/// a cast expression) or that the entity has no name (e.g., an
1566/// unnamed function parameter).
1567///
Richard Smithee579842017-01-30 20:39:26 +00001568/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1569/// acceptable as the top level type of the result.
1570///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001571/// \returns If the instantiation succeeds, the instantiated
1572/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001573TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001574 const MultiLevelTemplateArgumentList &Args,
1575 SourceLocation Loc,
Richard Smithee579842017-01-30 20:39:26 +00001576 DeclarationName Entity,
1577 bool AllowDeducedTST) {
Richard Smith696e3122017-02-23 01:43:54 +00001578 assert(!CodeSynthesisContexts.empty() &&
John McCall609459e2009-10-21 00:58:09 +00001579 "Cannot perform an instantiation without some context on the "
1580 "instantiation stack");
1581
Douglas Gregor678d76c2011-07-01 01:22:09 +00001582 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001583 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001584 return T;
1585
1586 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
Richard Smithee579842017-01-30 20:39:26 +00001587 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
1588 : Instantiator.TransformType(T);
John McCall609459e2009-10-21 00:58:09 +00001589}
1590
Douglas Gregor5499af42011-01-05 23:12:31 +00001591TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1592 const MultiLevelTemplateArgumentList &Args,
1593 SourceLocation Loc,
1594 DeclarationName Entity) {
Richard Smith696e3122017-02-23 01:43:54 +00001595 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001596 "Cannot perform an instantiation without some context on the "
1597 "instantiation stack");
1598
1599 if (TL.getType().isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001600 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001601
Douglas Gregor678d76c2011-07-01 01:22:09 +00001602 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001603 !TL.getType()->isVariablyModifiedType()) {
1604 // FIXME: Make a copy of the TypeLoc data here, so that we can
1605 // return a new TypeSourceInfo. Inefficient!
1606 TypeLocBuilder TLB;
1607 TLB.pushFullCopy(TL);
1608 return TLB.getTypeSourceInfo(Context, TL.getType());
1609 }
1610
1611 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1612 TypeLocBuilder TLB;
1613 TLB.reserve(TL.getFullDataSize());
1614 QualType Result = Instantiator.TransformType(TLB, TL);
1615 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001616 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001617
1618 return TLB.getTypeSourceInfo(Context, Result);
1619}
1620
John McCall609459e2009-10-21 00:58:09 +00001621/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001622QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001623 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001624 SourceLocation Loc, DeclarationName Entity) {
Richard Smith696e3122017-02-23 01:43:54 +00001625 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregor79cf6032009-03-10 20:44:00 +00001626 "Cannot perform an instantiation without some context on the "
1627 "instantiation stack");
1628
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001629 // If T is not a dependent type or a variably-modified type, there
1630 // is nothing to do.
Douglas Gregor678d76c2011-07-01 01:22:09 +00001631 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001632 return T;
1633
Douglas Gregord6ff3322009-08-04 16:50:30 +00001634 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1635 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001636}
Douglas Gregor463421d2009-03-03 04:44:36 +00001637
John McCallb29f78f2010-04-09 17:38:44 +00001638static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Nico Weberc0973372016-02-01 22:31:51 +00001639 if (T->getType()->isInstantiationDependentType() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00001640 T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001641 return true;
1642
Abramo Bagnara6d810632010-12-14 22:11:44 +00001643 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00001644 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCallb29f78f2010-04-09 17:38:44 +00001645 return false;
1646
David Blaikie6adc78e2013-02-18 22:06:02 +00001647 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Nico Weberc0973372016-02-01 22:31:51 +00001648 for (ParmVarDecl *P : FP.getParams()) {
Reid Klecknera09e44c2013-07-31 21:00:18 +00001649 // This must be synthesized from a typedef.
1650 if (!P) continue;
1651
Nico Weberc0973372016-02-01 22:31:51 +00001652 // If there are any parameters, a new TypeSourceInfo that refers to the
1653 // instantiated parameters must be built.
1654 return true;
John McCallb29f78f2010-04-09 17:38:44 +00001655 }
1656
1657 return false;
1658}
1659
1660/// A form of SubstType intended specifically for instantiating the
1661/// type of a FunctionDecl. Its purpose is solely to force the
Richard Smith2e321552014-11-12 02:00:47 +00001662/// instantiation of default-argument expressions and to avoid
1663/// instantiating an exception-specification.
John McCallb29f78f2010-04-09 17:38:44 +00001664TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1665 const MultiLevelTemplateArgumentList &Args,
1666 SourceLocation Loc,
Douglas Gregor3024f072012-04-16 07:05:22 +00001667 DeclarationName Entity,
1668 CXXRecordDecl *ThisContext,
1669 unsigned ThisTypeQuals) {
Richard Smith696e3122017-02-23 01:43:54 +00001670 assert(!CodeSynthesisContexts.empty() &&
John McCallb29f78f2010-04-09 17:38:44 +00001671 "Cannot perform an instantiation without some context on the "
1672 "instantiation stack");
Nico Weberc0973372016-02-01 22:31:51 +00001673
John McCallb29f78f2010-04-09 17:38:44 +00001674 if (!NeedsInstantiationAsFunctionType(T))
1675 return T;
1676
1677 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1678
1679 TypeLocBuilder TLB;
1680
1681 TypeLoc TL = T->getTypeLoc();
1682 TLB.reserve(TL.getFullDataSize());
1683
Douglas Gregor3024f072012-04-16 07:05:22 +00001684 QualType Result;
David Blaikie6adc78e2013-02-18 22:06:02 +00001685
Richard Smith2e321552014-11-12 02:00:47 +00001686 if (FunctionProtoTypeLoc Proto =
1687 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1688 // Instantiate the type, other than its exception specification. The
1689 // exception specification is instantiated in InitFunctionInstantiation
1690 // once we've built the FunctionDecl.
1691 // FIXME: Set the exception specification to EST_Uninstantiated here,
1692 // instead of rebuilding the function type again later.
1693 Result = Instantiator.TransformFunctionProtoType(
1694 TLB, Proto, ThisContext, ThisTypeQuals,
1695 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1696 bool &Changed) { return false; });
Douglas Gregor3024f072012-04-16 07:05:22 +00001697 } else {
1698 Result = Instantiator.TransformType(TLB, TL);
1699 }
John McCallb29f78f2010-04-09 17:38:44 +00001700 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001701 return nullptr;
John McCallb29f78f2010-04-09 17:38:44 +00001702
1703 return TLB.getTypeSourceInfo(Context, Result);
1704}
1705
Richard Smithcd198152017-06-07 21:46:22 +00001706bool Sema::SubstExceptionSpec(SourceLocation Loc,
1707 FunctionProtoType::ExceptionSpecInfo &ESI,
1708 SmallVectorImpl<QualType> &ExceptionStorage,
1709 const MultiLevelTemplateArgumentList &Args) {
1710 assert(ESI.Type != EST_Uninstantiated);
1711
1712 bool Changed = false;
1713 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
1714 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
1715 Changed);
1716}
1717
Richard Smith2e321552014-11-12 02:00:47 +00001718void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1719 const MultiLevelTemplateArgumentList &Args) {
1720 FunctionProtoType::ExceptionSpecInfo ESI =
1721 Proto->getExtProtoInfo().ExceptionSpec;
Richard Smith2e321552014-11-12 02:00:47 +00001722
1723 SmallVector<QualType, 4> ExceptionStorage;
Richard Smithcd198152017-06-07 21:46:22 +00001724 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getLocEnd(),
1725 ESI, ExceptionStorage, Args))
Richard Smith2e321552014-11-12 02:00:47 +00001726 // On error, recover by dropping the exception specification.
1727 ESI.Type = EST_None;
1728
1729 UpdateExceptionSpec(New, ESI);
1730}
1731
Douglas Gregor940bca72010-04-12 07:48:19 +00001732ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001733 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall8fb0d9d2011-05-01 22:35:37 +00001734 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001735 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001736 bool ExpectParameterPack) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001737 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Craig Topperc3ec1492014-05-26 06:22:03 +00001738 TypeSourceInfo *NewDI = nullptr;
1739
Douglas Gregor5499af42011-01-05 23:12:31 +00001740 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00001741 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1742
Douglas Gregor5499af42011-01-05 23:12:31 +00001743 // We have a function parameter pack. Substitute into the pattern of the
1744 // expansion.
1745 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1746 OldParm->getLocation(), OldParm->getDeclName());
1747 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001748 return nullptr;
1749
Douglas Gregor5499af42011-01-05 23:12:31 +00001750 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1751 // We still have unexpanded parameter packs, which means that
1752 // our function parameter is still a function parameter pack.
1753 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001754 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001755 NumExpansions);
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001756 } else if (ExpectParameterPack) {
1757 // We expected to get a parameter pack but didn't (because the type
1758 // itself is not a pack expansion type), so complain. This can occur when
1759 // the substitution goes through an alias template that "loses" the
1760 // pack expansion.
1761 Diag(OldParm->getLocation(),
1762 diag::err_function_parameter_pack_without_parameter_packs)
1763 << NewDI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001764 return nullptr;
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001765 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001766 } else {
1767 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1768 OldParm->getDeclName());
1769 }
1770
Douglas Gregor940bca72010-04-12 07:48:19 +00001771 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001772 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001773
1774 if (NewDI->getType()->isVoidType()) {
1775 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
Craig Topperc3ec1492014-05-26 06:22:03 +00001776 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001777 }
1778
1779 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001780 OldParm->getInnerLocStart(),
Douglas Gregor940bca72010-04-12 07:48:19 +00001781 OldParm->getLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001782 OldParm->getIdentifier(),
1783 NewDI->getType(), NewDI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001784 OldParm->getStorageClass());
Douglas Gregor940bca72010-04-12 07:48:19 +00001785 if (!NewParm)
Craig Topperc3ec1492014-05-26 06:22:03 +00001786 return nullptr;
1787
Douglas Gregor940bca72010-04-12 07:48:19 +00001788 // Mark the (new) default argument as uninstantiated (if any).
1789 if (OldParm->hasUninstantiatedDefaultArg()) {
1790 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1791 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001792 } else if (OldParm->hasUnparsedDefaultArg()) {
1793 NewParm->setUnparsedDefaultArg();
1794 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001795 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1796 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
Serge Pavlov73c6a242015-08-23 10:22:28 +00001797 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1798 // Instantiate default arguments for methods of local classes (DR1484)
1799 // and non-defining declarations.
1800 Sema::ContextRAII SavedContext(*this, OwningFunc);
Akira Hatanakad644e022016-12-16 03:19:41 +00001801 LocalInstantiationScope Local(*this, true);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001802 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
John McCalldc40b612015-12-11 01:56:36 +00001803 if (NewArg.isUsable()) {
1804 // It would be nice if we still had this.
1805 SourceLocation EqualLoc = NewArg.get()->getLocStart();
1806 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1807 }
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001808 } else {
1809 // FIXME: if we non-lazily instantiated non-dependent default args for
1810 // non-dependent parameter types we could remove a bunch of duplicate
1811 // conversion warnings for such arguments.
1812 NewParm->setUninstantiatedDefaultArg(Arg);
1813 }
1814 }
Douglas Gregor940bca72010-04-12 07:48:19 +00001815
1816 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001817
Douglas Gregorf3010112011-01-07 16:43:16 +00001818 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smith928be492012-01-25 02:14:59 +00001819 // Add the new parameter to the instantiated parameter pack.
Douglas Gregorf3010112011-01-07 16:43:16 +00001820 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1821 } else {
1822 // Introduce an Old -> New mapping
Douglas Gregor5499af42011-01-05 23:12:31 +00001823 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001824 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001825
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001826 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1827 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001828 NewParm->setDeclContext(CurContext);
John McCall8fb0d9d2011-05-01 22:35:37 +00001829
1830 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1831 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rosea0a86be2013-03-08 22:25:36 +00001832
1833 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1834
Douglas Gregor940bca72010-04-12 07:48:19 +00001835 return NewParm;
1836}
1837
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001838/// Substitute the given template arguments into the given set of
Douglas Gregordd472162011-01-07 00:20:55 +00001839/// parameters, producing the set of parameter types that would be generated
1840/// from such a substitution.
David Majnemer59f77922016-06-24 04:05:48 +00001841bool Sema::SubstParmTypes(
1842 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1843 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1844 const MultiLevelTemplateArgumentList &TemplateArgs,
1845 SmallVectorImpl<QualType> &ParamTypes,
1846 SmallVectorImpl<ParmVarDecl *> *OutParams,
1847 ExtParameterInfoBuilder &ParamInfos) {
Richard Smith696e3122017-02-23 01:43:54 +00001848 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregordd472162011-01-07 00:20:55 +00001849 "Cannot perform an instantiation without some context on the "
1850 "instantiation stack");
1851
1852 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1853 DeclarationName());
David Majnemer59f77922016-06-24 04:05:48 +00001854 return Instantiator.TransformFunctionTypeParams(
1855 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
Douglas Gregordd472162011-01-07 00:20:55 +00001856}
1857
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001858/// Perform substitution on the base class specifiers of the
John McCall76d824f2009-08-25 22:02:44 +00001859/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001860///
1861/// Produces a diagnostic and returns true on error, returns false and
1862/// attaches the instantiated base classes to the class template
1863/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001864bool
John McCall76d824f2009-08-25 22:02:44 +00001865Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1866 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001867 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001868 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001869 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Richard Trieub5841332015-04-15 01:21:42 +00001870 for (const auto &Base : Pattern->bases()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001871 if (!Base.getType()->isDependentType()) {
1872 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay76d0b462013-06-21 18:58:32 +00001873 if (RD->isInvalidDecl())
1874 Instantiation->setInvalidDecl();
1875 }
Aaron Ballman574705e2014-03-13 15:41:46 +00001876 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001877 continue;
1878 }
1879
Douglas Gregor752a5952011-01-03 22:36:02 +00001880 SourceLocation EllipsisLoc;
Douglas Gregorc52264e2011-03-02 02:04:06 +00001881 TypeSourceInfo *BaseTypeLoc;
Aaron Ballman574705e2014-03-13 15:41:46 +00001882 if (Base.isPackExpansion()) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001883 // This is a pack expansion. See whether we should expand it now, or
1884 // wait until later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001885 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Aaron Ballman574705e2014-03-13 15:41:46 +00001886 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001887 Unexpanded);
1888 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001889 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001890 Optional<unsigned> NumExpansions;
Aaron Ballman574705e2014-03-13 15:41:46 +00001891 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1892 Base.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001893 Unexpanded,
Douglas Gregor752a5952011-01-03 22:36:02 +00001894 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001895 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001896 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001897 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001898 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001899 }
1900
1901 // If we should expand this pack expansion now, do so.
1902 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001903 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001904 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1905
Aaron Ballman574705e2014-03-13 15:41:46 +00001906 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001907 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001908 Base.getSourceRange().getBegin(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001909 DeclarationName());
1910 if (!BaseTypeLoc) {
1911 Invalid = true;
1912 continue;
1913 }
1914
1915 if (CXXBaseSpecifier *InstantiatedBase
1916 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001917 Base.getSourceRange(),
1918 Base.isVirtual(),
1919 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001920 BaseTypeLoc,
1921 SourceLocation()))
1922 InstantiatedBases.push_back(InstantiatedBase);
1923 else
1924 Invalid = true;
1925 }
1926
1927 continue;
1928 }
1929
1930 // The resulting base specifier will (still) be a pack expansion.
Aaron Ballman574705e2014-03-13 15:41:46 +00001931 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregorc52264e2011-03-02 02:04:06 +00001932 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Aaron Ballman574705e2014-03-13 15:41:46 +00001933 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001934 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001935 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001936 DeclarationName());
1937 } else {
Aaron Ballman574705e2014-03-13 15:41:46 +00001938 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001939 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001940 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001941 DeclarationName());
Douglas Gregor752a5952011-01-03 22:36:02 +00001942 }
1943
Nick Lewycky19b9f952010-07-26 16:56:01 +00001944 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001945 Invalid = true;
1946 continue;
1947 }
1948
1949 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001950 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001951 Base.getSourceRange(),
1952 Base.isVirtual(),
1953 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001954 BaseTypeLoc,
1955 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001956 InstantiatedBases.push_back(InstantiatedBase);
1957 else
1958 Invalid = true;
1959 }
1960
Craig Topperaa700cb2015-12-27 21:55:19 +00001961 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
Douglas Gregor463421d2009-03-03 04:44:36 +00001962 Invalid = true;
1963
1964 return Invalid;
1965}
1966
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001967// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00001968namespace clang {
1969 namespace sema {
1970 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1971 const MultiLevelTemplateArgumentList &TemplateArgs);
Erich Keanea32910d2017-03-23 18:51:54 +00001972 Attr *instantiateTemplateAttributeForDecl(
1973 const Attr *At, ASTContext &C, Sema &S,
1974 const MultiLevelTemplateArgumentList &TemplateArgs);
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00001975 }
1976}
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001977
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001978/// Instantiate the definition of a class from a given pattern.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001979///
1980/// \param PointOfInstantiation The point of instantiation within the
1981/// source code.
1982///
1983/// \param Instantiation is the declaration whose definition is being
1984/// instantiated. This will be either a class template specialization
1985/// or a member class of a class template specialization.
1986///
1987/// \param Pattern is the pattern from which the instantiation
1988/// occurs. This will be either the declaration of a class template or
1989/// the declaration of a member class of a class template.
1990///
1991/// \param TemplateArgs The template arguments to be substituted into
1992/// the pattern.
1993///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001994/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001995///
1996/// \param Complain whether to complain if the class cannot be instantiated due
1997/// to the lack of a definition.
1998///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001999/// \returns true if an error occurred, false otherwise.
2000bool
2001Sema::InstantiateClass(SourceLocation PointOfInstantiation,
2002 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002003 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002004 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002005 bool Complain) {
Mike Stump11289f42009-09-09 15:08:12 +00002006 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002007 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Vassil Vassilevb21ee082016-08-18 22:01:25 +00002008 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00002009 Instantiation->getInstantiatedFromMemberClass(),
2010 Pattern, PatternDef, TSK, Complain))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002011 return true;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002012 Pattern = PatternDef;
2013
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002014 // Record the point of instantiation.
Douglas Gregord6ba93d2009-10-15 15:54:05 +00002015 if (MemberSpecializationInfo *MSInfo
2016 = Instantiation->getMemberSpecializationInfo()) {
2017 MSInfo->setTemplateSpecializationKind(TSK);
2018 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregoref6ab412009-10-27 06:26:26 +00002019 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weber3ffc4c92011-12-20 20:32:49 +00002020 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregoref6ab412009-10-27 06:26:26 +00002021 Spec->setTemplateSpecializationKind(TSK);
2022 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00002023 }
Richard Smitha1087602014-03-10 00:04:29 +00002024
Douglas Gregorf3430ae2009-03-25 21:23:52 +00002025 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002026 if (Inst.isInvalid())
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002027 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002028 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
Jordan Rose1e879d82018-03-23 00:07:18 +00002029 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00002030 "instantiating class definition");
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002031
2032 // Enter the scope of this instantiation. We don't use
2033 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00002034 ContextRAII SavedContext(*this, Instantiation);
Faisal Valid143a0c2017-04-01 21:30:49 +00002035 EnterExpressionEvaluationContext EvalContext(
2036 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002037
Douglas Gregor51121572010-03-24 01:33:17 +00002038 // If this is an instantiation of a local class, merge this local
2039 // instantiation scope with the enclosing scope. Otherwise, every
2040 // instantiation of a class has its own local instantiation scope.
2041 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00002042 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00002043
Volodymyr Sapsai4fbaa622017-09-21 19:54:12 +00002044 // Some class state isn't processed immediately but delayed till class
2045 // instantiation completes. We may not be ready to handle any delayed state
2046 // already on the stack as it might correspond to a different class, so save
2047 // it now and put it back later.
2048 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
Reid Kleckner5b640342016-02-26 19:51:02 +00002049
John McCall6602bb12010-08-01 02:01:53 +00002050 // Pull attributes from the pattern onto the instantiation.
2051 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2052
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002053 // Start the definition of this instantiation.
2054 Instantiation->startDefinition();
Richard Smitha1087602014-03-10 00:04:29 +00002055
2056 // The instantiation is visible here, even if it was first declared in an
2057 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00002058 Instantiation->setVisibleDespiteOwningModule();
Richard Smitha1087602014-03-10 00:04:29 +00002059
2060 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregore9029562010-05-06 00:28:52 +00002061 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002062
John McCall76d824f2009-08-25 22:02:44 +00002063 // Do substitution on the base class specifiers.
2064 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002065 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002066
Douglas Gregor869853e2010-11-10 19:44:59 +00002067 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002068 SmallVector<Decl*, 4> Fields;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002069 // Delay instantiation of late parsed attributes.
2070 LateInstantiatedAttrVec LateAttrs;
2071 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2072
Aaron Ballman629afae2014-03-07 19:56:05 +00002073 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002074 // Don't instantiate members not belonging in this semantic context.
2075 // e.g. for:
2076 // @code
2077 // template <int i> class A {
2078 // class B *g;
2079 // };
2080 // @endcode
2081 // 'class B' has the template as lexical context but semantically it is
2082 // introduced in namespace scope.
Aaron Ballman629afae2014-03-07 19:56:05 +00002083 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002084 continue;
2085
Aaron Ballman629afae2014-03-07 19:56:05 +00002086 if (Member->isInvalidDecl()) {
Richard Smithded9c2e2012-07-11 22:37:56 +00002087 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002088 continue;
2089 }
2090
Aaron Ballman629afae2014-03-07 19:56:05 +00002091 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002092 if (NewMember) {
Richard Smith938f40b2011-06-11 17:19:42 +00002093 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCall48871652010-08-21 09:40:31 +00002094 Fields.push_back(Field);
Richard Smith7d137e32012-03-23 03:33:32 +00002095 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2096 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2097 // specialization causes the implicit instantiation of the definitions
2098 // of unscoped member enumerations.
2099 // Record a point of instantiation for this implicit instantiation.
Richard Smithb66d7772012-03-23 23:09:08 +00002100 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2101 Enum->isCompleteDefinition()) {
Richard Smith7d137e32012-03-23 03:33:32 +00002102 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2103 assert(MSInfo && "no spec info for member enum specialization");
2104 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2105 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2106 }
Richard Smithded9c2e2012-07-11 22:37:56 +00002107 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2108 if (SA->isFailed()) {
2109 // A static_assert failed. Bail out; instantiating this
2110 // class is probably not meaningful.
2111 Instantiation->setInvalidDecl();
2112 break;
2113 }
Richard Smith7d137e32012-03-23 03:33:32 +00002114 }
2115
2116 if (NewMember->isInvalidDecl())
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002117 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002118 } else {
2119 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002120 // instantiations was a semantic disaster, and we'll want to mark the
2121 // declaration invalid.
2122 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002123 }
2124 }
2125
2126 // Finish checking fields.
Craig Topperc3ec1492014-05-26 06:22:03 +00002127 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2128 SourceLocation(), SourceLocation(), nullptr);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002129 CheckCompletedCXXClass(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002130
Reid Kleckner93f661a2015-03-17 21:51:43 +00002131 // Default arguments are parsed, if not instantiated. We can go instantiate
2132 // default arg exprs for default constructors if necessary now.
Hans Wennborg99000c22015-08-15 01:18:16 +00002133 ActOnFinishCXXNonNestedClass(Instantiation);
Reid Kleckner93f661a2015-03-17 21:51:43 +00002134
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002135 // Instantiate late parsed attributes, and attach them to their decls.
2136 // See Sema::InstantiateAttrs
2137 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2138 E = LateAttrs.end(); I != E; ++I) {
2139 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2140 CurrentInstantiationScope = I->Scope;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002141
2142 // Allow 'this' within late-parsed attributes.
2143 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2144 CXXRecordDecl *ThisContext =
2145 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2146 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2147 ND && ND->isCXXInstanceMember());
2148
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002149 Attr *NewAttr =
2150 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2151 I->NewDecl->addAttr(NewAttr);
2152 LocalInstantiationScope::deleteScopes(I->Scope,
2153 Instantiator.getStartingScope());
2154 }
2155 Instantiator.disableLateAttributeInstantiation();
2156 LateAttrs.clear();
2157
Richard Smithd3b5c9082012-07-27 04:22:15 +00002158 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002159
Richard Smitha1087602014-03-10 00:04:29 +00002160 // FIXME: We should do something similar for explicit instantiations so they
2161 // end up in the right module.
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002162 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidise3789482012-02-11 01:59:57 +00002163 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002164 Instantiation->setLocStart(Pattern->getInnerLocStart());
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00002165 Instantiation->setBraceRange(Pattern->getBraceRange());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002166 }
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002167
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002168 if (!Instantiation->isInvalidDecl()) {
John McCalla0a96892012-08-10 03:15:35 +00002169 // Perform any dependent diagnostics from the pattern.
2170 PerformDependentDiagnostics(Pattern, TemplateArgs);
2171
Douglas Gregor869853e2010-11-10 19:44:59 +00002172 // Instantiate any out-of-line class template partial
2173 // specializations now.
Richard Smith10b55fc2013-09-26 03:49:48 +00002174 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregor869853e2010-11-10 19:44:59 +00002175 P = Instantiator.delayed_partial_spec_begin(),
2176 PEnd = Instantiator.delayed_partial_spec_end();
2177 P != PEnd; ++P) {
2178 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smith10b55fc2013-09-26 03:49:48 +00002179 P->first, P->second)) {
2180 Instantiation->setInvalidDecl();
2181 break;
2182 }
2183 }
2184
2185 // Instantiate any out-of-line variable template partial
2186 // specializations now.
2187 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2188 P = Instantiator.delayed_var_partial_spec_begin(),
2189 PEnd = Instantiator.delayed_var_partial_spec_end();
2190 P != PEnd; ++P) {
2191 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2192 P->first, P->second)) {
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002193 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002194 break;
2195 }
2196 }
2197 }
2198
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002199 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00002200 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002201
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002202 if (!Instantiation->isInvalidDecl()) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00002203 Consumer.HandleTagDeclDefinition(Instantiation);
2204
Douglas Gregor88d292c2010-05-13 16:44:06 +00002205 // Always emit the vtable for an explicit instantiation definition
2206 // of a polymorphic class template specialization.
2207 if (TSK == TSK_ExplicitInstantiationDefinition)
2208 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2209 }
2210
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002211 return Instantiation->isInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002212}
2213
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002214/// Instantiate the definition of an enum from a given pattern.
Richard Smith4b38ded2012-03-14 23:13:10 +00002215///
2216/// \param PointOfInstantiation The point of instantiation within the
2217/// source code.
2218/// \param Instantiation is the declaration whose definition is being
2219/// instantiated. This will be a member enumeration of a class
2220/// temploid specialization, or a local enumeration within a
2221/// function temploid specialization.
2222/// \param Pattern The templated declaration from which the instantiation
2223/// occurs.
2224/// \param TemplateArgs The template arguments to be substituted into
2225/// the pattern.
2226/// \param TSK The kind of implicit or explicit instantiation to perform.
2227///
2228/// \return \c true if an error occurred, \c false otherwise.
2229bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2230 EnumDecl *Instantiation, EnumDecl *Pattern,
2231 const MultiLevelTemplateArgumentList &TemplateArgs,
2232 TemplateSpecializationKind TSK) {
2233 EnumDecl *PatternDef = Pattern->getDefinition();
Vassil Vassilevb21ee082016-08-18 22:01:25 +00002234 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00002235 Instantiation->getInstantiatedFromMemberEnum(),
2236 Pattern, PatternDef, TSK,/*Complain*/true))
2237 return true;
2238 Pattern = PatternDef;
2239
2240 // Record the point of instantiation.
2241 if (MemberSpecializationInfo *MSInfo
2242 = Instantiation->getMemberSpecializationInfo()) {
2243 MSInfo->setTemplateSpecializationKind(TSK);
2244 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2245 }
2246
2247 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002248 if (Inst.isInvalid())
Richard Smith4b38ded2012-03-14 23:13:10 +00002249 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002250 if (Inst.isAlreadyInstantiating())
2251 return false;
Jordan Rose1e879d82018-03-23 00:07:18 +00002252 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00002253 "instantiating enum definition");
Richard Smith4b38ded2012-03-14 23:13:10 +00002254
Richard Smitha1087602014-03-10 00:04:29 +00002255 // The instantiation is visible here, even if it was first declared in an
2256 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00002257 Instantiation->setVisibleDespiteOwningModule();
Richard Smitha1087602014-03-10 00:04:29 +00002258
Richard Smith4b38ded2012-03-14 23:13:10 +00002259 // Enter the scope of this instantiation. We don't use
2260 // PushDeclContext because we don't have a scope.
2261 ContextRAII SavedContext(*this, Instantiation);
Faisal Valid143a0c2017-04-01 21:30:49 +00002262 EnterExpressionEvaluationContext EvalContext(
2263 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith4b38ded2012-03-14 23:13:10 +00002264
2265 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2266
2267 // Pull attributes from the pattern onto the instantiation.
2268 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2269
2270 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2271 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2272
2273 // Exit the scope of this instantiation.
2274 SavedContext.pop();
2275
2276 return Instantiation->isInvalidDecl();
2277}
2278
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002279
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002280/// Instantiate the definition of a field from the given pattern.
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002281///
2282/// \param PointOfInstantiation The point of instantiation within the
2283/// source code.
2284/// \param Instantiation is the declaration whose definition is being
2285/// instantiated. This will be a class of a class temploid
2286/// specialization, or a local enumeration within a function temploid
2287/// specialization.
2288/// \param Pattern The templated declaration from which the instantiation
2289/// occurs.
2290/// \param TemplateArgs The template arguments to be substituted into
2291/// the pattern.
2292///
2293/// \return \c true if an error occurred, \c false otherwise.
2294bool Sema::InstantiateInClassInitializer(
2295 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2296 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2297 // If there is no initializer, we don't need to do anything.
2298 if (!Pattern->hasInClassInitializer())
2299 return false;
2300
2301 assert(Instantiation->getInClassInitStyle() ==
2302 Pattern->getInClassInitStyle() &&
2303 "pattern and instantiation disagree about init style");
2304
2305 // Error out if we haven't parsed the initializer of the pattern yet because
2306 // we are waiting for the closing brace of the outer class.
2307 Expr *OldInit = Pattern->getInClassInitializer();
2308 if (!OldInit) {
2309 RecordDecl *PatternRD = Pattern->getParent();
2310 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
Richard Smith8dbc6b22016-11-22 22:55:12 +00002311 Diag(PointOfInstantiation,
2312 diag::err_in_class_initializer_not_yet_parsed)
2313 << OutermostClass << Pattern;
2314 Diag(Pattern->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002315 Instantiation->setInvalidDecl();
2316 return true;
2317 }
2318
2319 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2320 if (Inst.isInvalid())
2321 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002322 if (Inst.isAlreadyInstantiating()) {
2323 // Error out if we hit an instantiation cycle for this initializer.
2324 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2325 << Instantiation;
2326 return true;
2327 }
Jordan Rose1e879d82018-03-23 00:07:18 +00002328 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00002329 "instantiating default member init");
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002330
2331 // Enter the scope of this instantiation. We don't use PushDeclContext because
2332 // we don't have a scope.
2333 ContextRAII SavedContext(*this, Instantiation->getParent());
Faisal Valid143a0c2017-04-01 21:30:49 +00002334 EnterExpressionEvaluationContext EvalContext(
2335 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002336
Serge Pavlov907233f2015-04-28 17:58:47 +00002337 LocalInstantiationScope Scope(*this, true);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002338
2339 // Instantiate the initializer.
2340 ActOnStartCXXInClassMemberInitializer();
2341 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2342
2343 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2344 /*CXXDirectInit=*/false);
2345 Expr *Init = NewInit.get();
2346 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2347 ActOnFinishCXXInClassMemberInitializer(
2348 Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2349
Richard Smith4b054b22016-08-24 21:25:37 +00002350 if (auto *L = getASTMutationListener())
2351 L->DefaultMemberInitializerInstantiated(Instantiation);
2352
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002353 // Return true if the in-class initializer is still missing.
2354 return !Instantiation->getInClassInitializer();
2355}
2356
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002357namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002358 /// A partial specialization whose template arguments have matched
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002359 /// a given template-id.
2360 struct PartialSpecMatchResult {
2361 ClassTemplatePartialSpecializationDecl *Partial;
2362 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002363 };
2364}
2365
Richard Smithe6d4b772017-06-07 02:42:27 +00002366bool Sema::usesPartialOrExplicitSpecialization(
2367 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
2368 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
2369 TSK_ExplicitSpecialization)
2370 return true;
2371
2372 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2373 ClassTemplateSpec->getSpecializedTemplate()
2374 ->getPartialSpecializations(PartialSpecs);
2375 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2376 TemplateDeductionInfo Info(Loc);
2377 if (!DeduceTemplateArguments(PartialSpecs[I],
2378 ClassTemplateSpec->getTemplateArgs(), Info))
2379 return true;
2380 }
2381
2382 return false;
2383}
2384
Richard Smith32b43762017-01-08 22:45:21 +00002385/// Get the instantiation pattern to use to instantiate the definition of a
2386/// given ClassTemplateSpecializationDecl (either the pattern of the primary
2387/// template or of a partial specialization).
2388static CXXRecordDecl *
2389getPatternForClassTemplateSpecialization(
2390 Sema &S, SourceLocation PointOfInstantiation,
Larisse Voufo72caf2b2013-08-22 00:59:14 +00002391 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2392 TemplateSpecializationKind TSK, bool Complain) {
Richard Smith32b43762017-01-08 22:45:21 +00002393 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2394 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
2395 return nullptr;
2396
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002397 llvm::PointerUnion<ClassTemplateDecl *,
2398 ClassTemplatePartialSpecializationDecl *>
2399 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2400 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
2401 // Find best matching specialization.
2402 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregor2373c592009-05-31 09:31:02 +00002403
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002404 // C++ [temp.class.spec.match]p1:
2405 // When a class template is used in a context that requires an
2406 // instantiation of the class, it is necessary to determine
2407 // whether the instantiation is to be generated using the primary
2408 // template or one of the partial specializations. This is done by
2409 // matching the template arguments of the class template
2410 // specialization with the template argument lists of the partial
2411 // specializations.
2412 typedef PartialSpecMatchResult MatchResult;
2413 SmallVector<MatchResult, 4> Matched;
2414 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2415 Template->getPartialSpecializations(PartialSpecs);
2416 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2417 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2418 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2419 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2420 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
2421 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
2422 // Store the failed-deduction information for use in diagnostics, later.
2423 // TODO: Actually use the failed-deduction info?
2424 FailedCandidates.addCandidate().set(
2425 DeclAccessPair::make(Template, AS_public), Partial,
2426 MakeDeductionFailureInfo(S.Context, Result, Info));
2427 (void)Result;
2428 } else {
2429 Matched.push_back(PartialSpecMatchResult());
2430 Matched.back().Partial = Partial;
2431 Matched.back().Args = Info.take();
2432 }
2433 }
2434
2435 // If we're dealing with a member template where the template parameters
2436 // have been instantiated, this provides the original template parameters
2437 // from which the member template's parameters were instantiated.
2438
2439 if (Matched.size() >= 1) {
2440 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
2441 if (Matched.size() == 1) {
2442 // -- If exactly one matching specialization is found, the
2443 // instantiation is generated from that specialization.
2444 // We don't need to do anything for this.
2445 } else {
2446 // -- If more than one matching specialization is found, the
2447 // partial order rules (14.5.4.2) are used to determine
2448 // whether one of the specializations is more specialized
2449 // than the others. If none of the specializations is more
2450 // specialized than all of the other matching
2451 // specializations, then the use of the class template is
2452 // ambiguous and the program is ill-formed.
2453 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2454 PEnd = Matched.end();
2455 P != PEnd; ++P) {
2456 if (S.getMoreSpecializedPartialSpecialization(
2457 P->Partial, Best->Partial, PointOfInstantiation) ==
2458 P->Partial)
2459 Best = P;
2460 }
2461
2462 // Determine if the best partial specialization is more specialized than
2463 // the others.
2464 bool Ambiguous = false;
2465 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2466 PEnd = Matched.end();
2467 P != PEnd; ++P) {
2468 if (P != Best && S.getMoreSpecializedPartialSpecialization(
2469 P->Partial, Best->Partial,
2470 PointOfInstantiation) != Best->Partial) {
2471 Ambiguous = true;
2472 break;
2473 }
2474 }
2475
2476 if (Ambiguous) {
2477 // Partial ordering did not produce a clear winner. Complain.
2478 Inst.Clear();
2479 ClassTemplateSpec->setInvalidDecl();
2480 S.Diag(PointOfInstantiation,
2481 diag::err_partial_spec_ordering_ambiguous)
2482 << ClassTemplateSpec;
2483
2484 // Print the matching partial specializations.
2485 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2486 PEnd = Matched.end();
2487 P != PEnd; ++P)
2488 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2489 << S.getTemplateArgumentBindingsText(
2490 P->Partial->getTemplateParameters(), *P->Args);
2491
2492 return nullptr;
2493 }
2494 }
2495
2496 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002497 } else {
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002498 // -- If no matches are found, the instantiation is generated
2499 // from the primary template.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002500 }
Douglas Gregor2373c592009-05-31 09:31:02 +00002501 }
2502
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002503 CXXRecordDecl *Pattern = nullptr;
2504 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2505 if (auto *PartialSpec =
2506 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
Douglas Gregorbe999392009-09-15 16:23:51 +00002507 // Instantiate using the best class template partial specialization.
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002508 while (PartialSpec->getInstantiatedFromMember()) {
Douglas Gregor21610382009-10-29 00:04:11 +00002509 // If we've found an explicit specialization of this class template,
2510 // stop here and use that as the pattern.
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002511 if (PartialSpec->isMemberSpecialization())
Douglas Gregor21610382009-10-29 00:04:11 +00002512 break;
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002513
2514 PartialSpec = PartialSpec->getInstantiatedFromMember();
Douglas Gregor21610382009-10-29 00:04:11 +00002515 }
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002516 Pattern = PartialSpec;
Douglas Gregor170bc422009-06-12 22:31:52 +00002517 } else {
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002518 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2519 while (Template->getInstantiatedFromMemberTemplate()) {
Douglas Gregorcf915552009-10-13 16:30:37 +00002520 // If we've found an explicit specialization of this class template,
2521 // stop here and use that as the pattern.
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002522 if (Template->isMemberSpecialization())
Douglas Gregorcf915552009-10-13 16:30:37 +00002523 break;
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002524
2525 Template = Template->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00002526 }
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002527 Pattern = Template->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00002528 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002529
Richard Smith32b43762017-01-08 22:45:21 +00002530 return Pattern;
2531}
Mike Stump11289f42009-09-09 15:08:12 +00002532
Richard Smith32b43762017-01-08 22:45:21 +00002533bool Sema::InstantiateClassTemplateSpecialization(
2534 SourceLocation PointOfInstantiation,
2535 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2536 TemplateSpecializationKind TSK, bool Complain) {
2537 // Perform the actual instantiation on the canonical declaration.
2538 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2539 ClassTemplateSpec->getCanonicalDecl());
2540 if (ClassTemplateSpec->isInvalidDecl())
2541 return true;
2542
2543 CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization(
2544 *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
2545 if (!Pattern)
2546 return true;
2547
2548 return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
2549 getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
2550 Complain);
Douglas Gregor463421d2009-03-03 04:44:36 +00002551}
Douglas Gregor90a1a652009-03-19 17:26:29 +00002552
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002553/// Instantiates the definitions of all of the member
John McCall76d824f2009-08-25 22:02:44 +00002554/// of the given class, which is an instantiation of a class template
2555/// or a member class of a template.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002556void
2557Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002558 CXXRecordDecl *Instantiation,
2559 const MultiLevelTemplateArgumentList &TemplateArgs,
2560 TemplateSpecializationKind TSK) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00002561 // FIXME: We need to notify the ASTMutationListener that we did all of these
2562 // things, in case we have an explicit instantiation definition in a PCM, a
2563 // module, or preamble, and the declaration is in an imported AST.
David Majnemer192d1792013-11-27 08:20:38 +00002564 assert(
2565 (TSK == TSK_ExplicitInstantiationDefinition ||
2566 TSK == TSK_ExplicitInstantiationDeclaration ||
2567 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2568 "Unexpected template specialization kind!");
Aaron Ballman629afae2014-03-07 19:56:05 +00002569 for (auto *D : Instantiation->decls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002570 bool SuppressNew = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002571 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002572 if (FunctionDecl *Pattern
2573 = Function->getInstantiatedFromMemberFunction()) {
2574 MemberSpecializationInfo *MSInfo
2575 = Function->getMemberSpecializationInfo();
2576 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002577 if (MSInfo->getTemplateSpecializationKind()
2578 == TSK_ExplicitSpecialization)
2579 continue;
2580
Douglas Gregor1d957a32009-10-27 18:42:08 +00002581 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2582 Function,
2583 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002584 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002585 SuppressNew) ||
2586 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002587 continue;
Richard Smitheb36ddf2014-04-24 22:45:46 +00002588
2589 // C++11 [temp.explicit]p8:
2590 // An explicit instantiation definition that names a class template
2591 // specialization explicitly instantiates the class template
2592 // specialization and is only an explicit instantiation definition
2593 // of members whose definition is visible at the point of
2594 // instantiation.
2595 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002596 continue;
2597
Richard Smitheb36ddf2014-04-24 22:45:46 +00002598 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2599
2600 if (Function->isDefined()) {
2601 // Let the ASTConsumer know that this function has been explicitly
2602 // instantiated now, and its linkage might have changed.
2603 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2604 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002605 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Richard Smitheb36ddf2014-04-24 22:45:46 +00002606 } else if (TSK == TSK_ImplicitInstantiation) {
2607 PendingLocalImplicitInstantiations.push_back(
2608 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor1d957a32009-10-27 18:42:08 +00002609 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002610 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002611 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002612 if (isa<VarTemplateSpecializationDecl>(Var))
2613 continue;
2614
Douglas Gregor86d142a2009-10-08 07:24:58 +00002615 if (Var->isStaticDataMember()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002616 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2617 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002618 if (MSInfo->getTemplateSpecializationKind()
2619 == TSK_ExplicitSpecialization)
2620 continue;
2621
Douglas Gregor1d957a32009-10-27 18:42:08 +00002622 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2623 Var,
2624 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002625 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002626 SuppressNew) ||
2627 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002628 continue;
2629
Douglas Gregor1d957a32009-10-27 18:42:08 +00002630 if (TSK == TSK_ExplicitInstantiationDefinition) {
2631 // C++0x [temp.explicit]p8:
2632 // An explicit instantiation definition that names a class template
2633 // specialization explicitly instantiates the class template
2634 // specialization and is only an explicit instantiation definition
2635 // of members whose definition is visible at the point of
2636 // instantiation.
Richard Smith62f19e72016-06-25 00:15:56 +00002637 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002638 continue;
2639
2640 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00002641 InstantiateVariableDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00002642 } else {
2643 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2644 }
2645 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002646 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Douglas Gregor1da22252010-04-18 18:11:38 +00002647 // Always skip the injected-class-name, along with any
2648 // redeclarations of nested classes, since both would cause us
2649 // to try to instantiate the members of a class twice.
Richard Smith069ecf62014-11-20 22:56:34 +00002650 // Skip closure types; they'll get instantiated when we instantiate
2651 // the corresponding lambda-expression.
2652 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2653 Record->isLambda())
Douglas Gregord801b062009-10-07 23:56:10 +00002654 continue;
2655
Douglas Gregor1d957a32009-10-27 18:42:08 +00002656 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2657 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002658
2659 if (MSInfo->getTemplateSpecializationKind()
2660 == TSK_ExplicitSpecialization)
2661 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00002662
Shoaib Meenaia9047452017-04-20 01:11:42 +00002663 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2664 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00002665 TSK == TSK_ExplicitInstantiationDeclaration) {
Shoaib Meenaia9047452017-04-20 01:11:42 +00002666 // In MSVC and Windows Itanium mode, explicit instantiation decl of the
2667 // outer class doesn't affect the inner class.
Hans Wennborga86a83b2016-05-26 19:42:56 +00002668 continue;
2669 }
2670
Douglas Gregor1d957a32009-10-27 18:42:08 +00002671 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2672 Record,
2673 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002674 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002675 SuppressNew) ||
2676 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002677 continue;
2678
Douglas Gregor1d957a32009-10-27 18:42:08 +00002679 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2680 assert(Pattern && "Missing instantiated-from-template information");
2681
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002682 if (!Record->getDefinition()) {
2683 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002684 // C++0x [temp.explicit]p8:
2685 // An explicit instantiation definition that names a class template
2686 // specialization explicitly instantiates the class template
2687 // specialization and is only an explicit instantiation definition
2688 // of members whose definition is visible at the point of
2689 // instantiation.
2690 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2691 MSInfo->setTemplateSpecializationKind(TSK);
2692 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2693 }
2694
2695 continue;
2696 }
2697
2698 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002699 TemplateArgs,
2700 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002701 } else {
2702 if (TSK == TSK_ExplicitInstantiationDefinition &&
2703 Record->getTemplateSpecializationKind() ==
2704 TSK_ExplicitInstantiationDeclaration) {
2705 Record->setTemplateSpecializationKind(TSK);
2706 MarkVTableUsed(PointOfInstantiation, Record, true);
2707 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002708 }
Douglas Gregorc093c1d2009-10-08 01:19:17 +00002709
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002710 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002711 if (Pattern)
2712 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2713 TSK);
Aaron Ballman629afae2014-03-07 19:56:05 +00002714 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smith4b38ded2012-03-14 23:13:10 +00002715 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2716 assert(MSInfo && "No member specialization information?");
2717
2718 if (MSInfo->getTemplateSpecializationKind()
2719 == TSK_ExplicitSpecialization)
2720 continue;
2721
2722 if (CheckSpecializationInstantiationRedecl(
2723 PointOfInstantiation, TSK, Enum,
2724 MSInfo->getTemplateSpecializationKind(),
2725 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2726 SuppressNew)
2727 continue;
2728
2729 if (Enum->getDefinition())
2730 continue;
2731
Richard Smith6739a102016-05-05 00:56:12 +00002732 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
Richard Smith4b38ded2012-03-14 23:13:10 +00002733 assert(Pattern && "Missing instantiated-from-template information");
2734
2735 if (TSK == TSK_ExplicitInstantiationDefinition) {
2736 if (!Pattern->getDefinition())
2737 continue;
2738
2739 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2740 } else {
2741 MSInfo->setTemplateSpecializationKind(TSK);
2742 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2743 }
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002744 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2745 // No need to instantiate in-class initializers during explicit
2746 // instantiation.
2747 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2748 CXXRecordDecl *ClassPattern =
2749 Instantiation->getTemplateInstantiationPattern();
2750 DeclContext::lookup_result Lookup =
2751 ClassPattern->lookup(Field->getDeclName());
David Majnemer76a25622016-06-09 05:26:56 +00002752 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002753 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2754 TemplateArgs);
2755 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002756 }
2757 }
2758}
2759
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002760/// Instantiate the definitions of all of the members of the
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002761/// given class template specialization, which was named as part of an
2762/// explicit instantiation.
Mike Stump11289f42009-09-09 15:08:12 +00002763void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002764Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002765 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002766 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2767 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002768 // C++0x [temp.explicit]p7:
2769 // An explicit instantiation that names a class template
2770 // specialization is an explicit instantion of the same kind
2771 // (declaration or definition) of each of its members (not
2772 // including members inherited from base classes) that has not
2773 // been previously explicitly specialized in the translation unit
2774 // containing the explicit instantiation, except as described
2775 // below.
2776 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002777 getTemplateInstantiationArgs(ClassTemplateSpec),
2778 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002779}
2780
John McCalldadc5752010-08-24 06:29:42 +00002781StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002782Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002783 if (!S)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002784 return S;
Douglas Gregorebe10102009-08-20 07:17:43 +00002785
2786 TemplateInstantiator Instantiator(*this, TemplateArgs,
2787 SourceLocation(),
2788 DeclarationName());
2789 return Instantiator.TransformStmt(S);
2790}
2791
John McCalldadc5752010-08-24 06:29:42 +00002792ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002793Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002794 if (!E)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002795 return E;
Mike Stump11289f42009-09-09 15:08:12 +00002796
Douglas Gregora16548e2009-08-11 05:31:07 +00002797 TemplateInstantiator Instantiator(*this, TemplateArgs,
2798 SourceLocation(),
2799 DeclarationName());
2800 return Instantiator.TransformExpr(E);
2801}
2802
Richard Smithd59b8322012-12-19 01:39:02 +00002803ExprResult Sema::SubstInitializer(Expr *Init,
2804 const MultiLevelTemplateArgumentList &TemplateArgs,
2805 bool CXXDirectInit) {
2806 TemplateInstantiator Instantiator(*this, TemplateArgs,
2807 SourceLocation(),
2808 DeclarationName());
2809 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2810}
2811
Craig Topper99d23532015-12-24 23:58:29 +00002812bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002813 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002814 SmallVectorImpl<Expr *> &Outputs) {
Craig Topper99d23532015-12-24 23:58:29 +00002815 if (Exprs.empty())
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002816 return false;
Richard Smithd59b8322012-12-19 01:39:02 +00002817
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002818 TemplateInstantiator Instantiator(*this, TemplateArgs,
2819 SourceLocation(),
2820 DeclarationName());
Craig Topper99d23532015-12-24 23:58:29 +00002821 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2822 IsCall, Outputs);
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002823}
2824
Douglas Gregor14454802011-02-25 02:25:35 +00002825NestedNameSpecifierLoc
2826Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2827 const MultiLevelTemplateArgumentList &TemplateArgs) {
2828 if (!NNS)
2829 return NestedNameSpecifierLoc();
2830
2831 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2832 DeclarationName());
2833 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2834}
2835
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002836/// Do template substitution on declaration name info.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002837DeclarationNameInfo
2838Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2839 const MultiLevelTemplateArgumentList &TemplateArgs) {
2840 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2841 NameInfo.getName());
2842 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2843}
2844
Douglas Gregoraa594892009-03-31 18:38:02 +00002845TemplateName
Douglas Gregordf846d12011-03-02 18:46:51 +00002846Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2847 TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002848 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002849 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2850 DeclarationName());
Douglas Gregordf846d12011-03-02 18:46:51 +00002851 CXXScopeSpec SS;
2852 SS.Adopt(QualifierLoc);
2853 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregoraa594892009-03-31 18:38:02 +00002854}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002855
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002856bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2857 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002858 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002859 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2860 DeclarationName());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002861
2862 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00002863}
Douglas Gregor14cf7522010-04-30 18:55:50 +00002864
Richard Smith70b13042015-01-09 01:19:56 +00002865static const Decl *getCanonicalParmVarDecl(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002866 // When storing ParmVarDecls in the local instantiation scope, we always
2867 // want to use the ParmVarDecl from the canonical function declaration,
2868 // since the map is then valid for any redeclaration or definition of that
2869 // function.
2870 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2871 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2872 unsigned i = PV->getFunctionScopeIndex();
Richard Smith70b13042015-01-09 01:19:56 +00002873 // This parameter might be from a freestanding function type within the
2874 // function and isn't necessarily referring to one of FD's parameters.
2875 if (FD->getParamDecl(i) == PV)
2876 return FD->getCanonicalDecl()->getParamDecl(i);
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002877 }
2878 }
2879 return D;
2880}
2881
2882
Douglas Gregorf3010112011-01-07 16:43:16 +00002883llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2884LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002885 D = getCanonicalParmVarDecl(D);
Chris Lattnercab02a62011-02-17 20:34:02 +00002886 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002887 Current = Current->Outer) {
Chris Lattnercab02a62011-02-17 20:34:02 +00002888
Douglas Gregor14cf7522010-04-30 18:55:50 +00002889 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002890 const Decl *CheckD = D;
2891 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00002892 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002893 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00002894 return &Found->second;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002895
2896 // If this is a tag declaration, it's possible that we need to look for
2897 // a previous declaration.
2898 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregorec9fd132012-01-14 16:38:05 +00002899 CheckD = Tag->getPreviousDecl();
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002900 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002901 CheckD = nullptr;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002902 } while (CheckD);
2903
Douglas Gregor14cf7522010-04-30 18:55:50 +00002904 // If we aren't combined with our outer scope, we're done.
2905 if (!Current->CombineWithOuterScope)
2906 break;
2907 }
Chris Lattnercab02a62011-02-17 20:34:02 +00002908
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002909 // If we're performing a partial substitution during template argument
2910 // deduction, we may not have values for template parameters yet.
2911 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2912 isa<TemplateTemplateParmDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00002913 return nullptr;
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002914
Serge Pavlove7ad8312015-05-15 10:10:28 +00002915 // Local types referenced prior to definition may require instantiation.
2916 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2917 if (RD->isLocalClass())
2918 return nullptr;
2919
2920 // Enumeration types referenced prior to definition may appear as a result of
2921 // error recovery.
2922 if (isa<EnumDecl>(D))
Serge Pavlov4c511742015-05-04 16:44:39 +00002923 return nullptr;
2924
Chris Lattnercab02a62011-02-17 20:34:02 +00002925 // If we didn't find the decl, then we either have a sema bug, or we have a
2926 // forward reference to a label declaration. Return null to indicate that
2927 // we have an uninstantiated label.
2928 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Craig Topperc3ec1492014-05-26 06:22:03 +00002929 return nullptr;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002930}
2931
John McCall19c1bfd2010-08-25 05:32:35 +00002932void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002933 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002934 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Richard Smith70b13042015-01-09 01:19:56 +00002935 if (Stored.isNull()) {
2936#ifndef NDEBUG
2937 // It should not be present in any surrounding scope either.
2938 LocalInstantiationScope *Current = this;
2939 while (Current->CombineWithOuterScope && Current->Outer) {
2940 Current = Current->Outer;
2941 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2942 "Instantiated local in inner and outer scopes");
2943 }
2944#endif
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002945 Stored = Inst;
Richard Smith70b13042015-01-09 01:19:56 +00002946 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
James Y Knight48fefa32015-09-30 14:04:23 +00002947 Pack->push_back(cast<ParmVarDecl>(Inst));
Richard Smith70b13042015-01-09 01:19:56 +00002948 } else {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002949 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Richard Smith70b13042015-01-09 01:19:56 +00002950 }
Douglas Gregor14cf7522010-04-30 18:55:50 +00002951}
Douglas Gregorf3010112011-01-07 16:43:16 +00002952
James Y Knight48fefa32015-09-30 14:04:23 +00002953void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2954 ParmVarDecl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002955 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002956 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2957 Pack->push_back(Inst);
2958}
2959
2960void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
Richard Smith70b13042015-01-09 01:19:56 +00002961#ifndef NDEBUG
2962 // This should be the first time we've been told about this decl.
2963 for (LocalInstantiationScope *Current = this;
2964 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2965 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2966 "Creating local pack after instantiation of local");
2967#endif
2968
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002969 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002970 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregorf3010112011-01-07 16:43:16 +00002971 DeclArgumentPack *Pack = new DeclArgumentPack;
2972 Stored = Pack;
2973 ArgumentPacks.push_back(Pack);
2974}
2975
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002976void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2977 const TemplateArgument *ExplicitArgs,
2978 unsigned NumExplicitArgs) {
2979 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2980 "Already have a partially-substituted pack");
2981 assert((!PartiallySubstitutedPack
2982 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2983 "Wrong number of arguments in partially-substituted pack");
2984 PartiallySubstitutedPack = Pack;
2985 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2986 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2987}
2988
2989NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2990 const TemplateArgument **ExplicitArgs,
2991 unsigned *NumExplicitArgs) const {
2992 if (ExplicitArgs)
Craig Topperc3ec1492014-05-26 06:22:03 +00002993 *ExplicitArgs = nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002994 if (NumExplicitArgs)
2995 *NumExplicitArgs = 0;
2996
2997 for (const LocalInstantiationScope *Current = this; Current;
2998 Current = Current->Outer) {
2999 if (Current->PartiallySubstitutedPack) {
3000 if (ExplicitArgs)
3001 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
3002 if (NumExplicitArgs)
3003 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
3004
3005 return Current->PartiallySubstitutedPack;
3006 }
3007
3008 if (!Current->CombineWithOuterScope)
3009 break;
3010 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003011
3012 return nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003013}