blob: 16f7381330807fe927d1a86234b5ea231dd3571e [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"
21#include "clang/Basic/LangOptions.h"
John McCall8b0666c2010-08-20 18:27:03 +000022#include "clang/Sema/DeclSpec.h"
Richard Smith938f40b2011-06-11 17:19:42 +000023#include "clang/Sema/Initialization.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000024#include "clang/Sema/Lookup.h"
Richard Smithe19b95d2016-05-26 20:23:13 +000025#include "clang/Sema/PrettyDeclStackTrace.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"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000028
29using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000030using namespace sema;
Douglas Gregorfe1e1102009-02-27 19:31:52 +000031
Douglas Gregor4ea568f2009-03-10 18:03:33 +000032//===----------------------------------------------------------------------===/
33// Template Instantiation Support
34//===----------------------------------------------------------------------===/
35
Douglas Gregor01afeef2009-08-28 20:31:08 +000036/// \brief Retrieve the template argument list(s) that should be used to
37/// instantiate the definition of the given declaration.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000038///
39/// \param D the declaration for which we are computing template instantiation
40/// arguments.
41///
42/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor8c702532010-02-05 07:33:43 +000043///
44/// \param RelativeToPrimary true if we should get the template
45/// arguments relative to the primary template, even when we're
46/// dealing with a specialization. This is only relevant for function
47/// template specializations.
Douglas Gregor1bd7a942010-05-03 23:29:10 +000048///
49/// \param Pattern If non-NULL, indicates the pattern from which we will be
50/// instantiating the definition of the given declaration, \p D. This is
51/// used to determine the proper set of template instantiation arguments for
52/// friend function template specializations.
Douglas Gregora654dd82009-08-28 17:37:35 +000053MultiLevelTemplateArgumentList
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000054Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor8c702532010-02-05 07:33:43 +000055 const TemplateArgumentList *Innermost,
Douglas Gregor1bd7a942010-05-03 23:29:10 +000056 bool RelativeToPrimary,
57 const FunctionDecl *Pattern) {
Douglas Gregora654dd82009-08-28 17:37:35 +000058 // Accumulate the set of template argument lists in this structure.
59 MultiLevelTemplateArgumentList Result;
Mike Stump11289f42009-09-09 15:08:12 +000060
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000061 if (Innermost)
62 Result.addOuterTemplateArguments(Innermost);
63
Douglas Gregora654dd82009-08-28 17:37:35 +000064 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregora51c9cc2011-05-22 00:21:10 +000065 if (!Ctx) {
Douglas Gregora654dd82009-08-28 17:37:35 +000066 Ctx = D->getDeclContext();
Larisse Voufo39a1e502013-08-06 01:03:05 +000067
68 // Add template arguments from a variable template instantiation.
69 if (VarTemplateSpecializationDecl *Spec =
70 dyn_cast<VarTemplateSpecializationDecl>(D)) {
71 // We're done when we hit an explicit specialization.
72 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
73 !isa<VarTemplatePartialSpecializationDecl>(Spec))
74 return Result;
75
76 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
77
78 // If this variable template specialization was instantiated from a
79 // specialized member that is a variable template, we're done.
80 assert(Spec->getSpecializedTemplate() && "No variable template?");
Richard Smithbeef3452014-01-16 23:39:20 +000081 llvm::PointerUnion<VarTemplateDecl*,
82 VarTemplatePartialSpecializationDecl*> Specialized
83 = Spec->getSpecializedTemplateOrPartial();
84 if (VarTemplatePartialSpecializationDecl *Partial =
85 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
86 if (Partial->isMemberSpecialization())
87 return Result;
88 } else {
89 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
90 if (Tmpl->isMemberSpecialization())
91 return Result;
92 }
Larisse Voufo39a1e502013-08-06 01:03:05 +000093 }
94
Douglas Gregor55462622011-06-15 14:20:42 +000095 // If we have a template template parameter with translation unit context,
96 // then we're performing substitution into a default template argument of
97 // this template template parameter before we've constructed the template
98 // that will own this template template parameter. In this case, we
99 // use empty template parameter lists for all of the outer templates
100 // to avoid performing any substitutions.
101 if (Ctx->isTranslationUnit()) {
102 if (TemplateTemplateParmDecl *TTP
103 = dyn_cast<TemplateTemplateParmDecl>(D)) {
104 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +0000105 Result.addOuterTemplateArguments(None);
Douglas Gregor55462622011-06-15 14:20:42 +0000106 return Result;
107 }
108 }
Douglas Gregora51c9cc2011-05-22 00:21:10 +0000109 }
110
John McCall970d5302009-08-29 03:16:09 +0000111 while (!Ctx->isFileContext()) {
Douglas Gregora654dd82009-08-28 17:37:35 +0000112 // Add template arguments from a class template instantiation.
Mike Stump11289f42009-09-09 15:08:12 +0000113 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregora654dd82009-08-28 17:37:35 +0000114 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
115 // We're done when we hit an explicit specialization.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000116 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
117 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregora654dd82009-08-28 17:37:35 +0000118 break;
Mike Stump11289f42009-09-09 15:08:12 +0000119
Douglas Gregora654dd82009-08-28 17:37:35 +0000120 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000121
122 // If this class template specialization was instantiated from a
123 // specialized member that is a class template, we're done.
124 assert(Spec->getSpecializedTemplate() && "No class template?");
125 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
126 break;
Mike Stump11289f42009-09-09 15:08:12 +0000127 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000128 // Add template arguments from a function template specialization.
John McCall970d5302009-08-29 03:16:09 +0000129 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor8c702532010-02-05 07:33:43 +0000130 if (!RelativeToPrimary &&
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000131 (Function->getTemplateSpecializationKind() ==
132 TSK_ExplicitSpecialization &&
133 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorcf915552009-10-13 16:30:37 +0000134 break;
135
Douglas Gregora654dd82009-08-28 17:37:35 +0000136 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorcf915552009-10-13 16:30:37 +0000137 = Function->getTemplateSpecializationArgs()) {
138 // Add the template arguments for this specialization.
Douglas Gregora654dd82009-08-28 17:37:35 +0000139 Result.addOuterTemplateArguments(TemplateArgs);
John McCall970d5302009-08-29 03:16:09 +0000140
Douglas Gregorcf915552009-10-13 16:30:37 +0000141 // If this function was instantiated from a specialized member that is
142 // a function template, we're done.
143 assert(Function->getPrimaryTemplate() && "No function template?");
144 if (Function->getPrimaryTemplate()->isMemberSpecialization())
145 break;
Faisal Vali2cba1332013-10-23 06:44:28 +0000146
147 // If this function is a generic lambda specialization, we are done.
148 if (isGenericLambdaCallOperatorSpecialization(Function))
149 break;
150
Douglas Gregor43669f82011-03-05 17:54:25 +0000151 } else if (FunctionTemplateDecl *FunTmpl
152 = Function->getDescribedFunctionTemplate()) {
153 // Add the "injected" template arguments.
Richard Smith841d8b22013-05-17 03:04:50 +0000154 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000155 }
156
John McCall970d5302009-08-29 03:16:09 +0000157 // If this is a friend declaration and it declares an entity at
158 // namespace scope, take arguments from its lexical parent
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000159 // instead of its semantic parent, unless of course the pattern we're
160 // instantiating actually comes from the file's context!
John McCall970d5302009-08-29 03:16:09 +0000161 if (Function->getFriendObjectKind() &&
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000162 Function->getDeclContext()->isFileContext() &&
163 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCall970d5302009-08-29 03:16:09 +0000164 Ctx = Function->getLexicalDeclContext();
Douglas Gregor8c702532010-02-05 07:33:43 +0000165 RelativeToPrimary = false;
John McCall970d5302009-08-29 03:16:09 +0000166 continue;
167 }
Douglas Gregor9961ce92010-07-08 18:37:38 +0000168 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
169 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
170 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith841d8b22013-05-17 03:04:50 +0000171 const TemplateSpecializationType *TST =
172 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
173 Result.addOuterTemplateArguments(
174 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor9961ce92010-07-08 18:37:38 +0000175 if (ClassTemplate->isMemberSpecialization())
176 break;
177 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000178 }
John McCall970d5302009-08-29 03:16:09 +0000179
180 Ctx = Ctx->getParent();
Douglas Gregor8c702532010-02-05 07:33:43 +0000181 RelativeToPrimary = false;
Douglas Gregorb4850462009-05-14 23:26:13 +0000182 }
Mike Stump11289f42009-09-09 15:08:12 +0000183
Douglas Gregora654dd82009-08-28 17:37:35 +0000184 return Result;
Douglas Gregorb4850462009-05-14 23:26:13 +0000185}
186
Richard Smith696e3122017-02-23 01:43:54 +0000187bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000188 switch (Kind) {
189 case TemplateInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000190 case ExceptionSpecInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000191 case DefaultTemplateArgumentInstantiation:
192 case DefaultFunctionArgumentInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000193 case ExplicitTemplateArgumentSubstitution:
194 case DeducedTemplateArgumentSubstitution:
195 case PriorTemplateArgumentSubstitution:
Richard Smith8a874c92012-07-08 02:38:24 +0000196 return true;
197
Douglas Gregor84d49a22009-11-11 21:54:23 +0000198 case DefaultTemplateArgumentChecking:
Richard Smith13381222017-02-23 21:43:43 +0000199 case DeclaringSpecialMember:
Richard Smith883dbc42017-05-25 22:47:05 +0000200 case DefiningSynthesizedFunction:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000201 return false;
202 }
David Blaikie8a40f702012-01-17 06:56:22 +0000203
Richard Smith696e3122017-02-23 01:43:54 +0000204 llvm_unreachable("Invalid SynthesisKind!");
Douglas Gregor84d49a22009-11-11 21:54:23 +0000205}
206
Benjamin Kramer7761a042015-03-06 16:36:50 +0000207Sema::InstantiatingTemplate::InstantiatingTemplate(
Richard Smith696e3122017-02-23 01:43:54 +0000208 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000209 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
210 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000211 sema::TemplateDeductionInfo *DeductionInfo)
Richard Smith13381222017-02-23 21:43:43 +0000212 : SemaRef(SemaRef) {
Akira Hatanaka43556c12016-11-03 15:04:58 +0000213 // Don't allow further instantiation if a fatal error and an uncompilable
Akira Hatanaka40c15ab2016-11-03 17:11:28 +0000214 // error have occurred. Any diagnostics we might have raised will not be
Akira Hatanaka43556c12016-11-03 15:04:58 +0000215 // visible, and we do not need to construct a correct AST.
216 if (SemaRef.Diags.hasFatalErrorOccurred() &&
217 SemaRef.Diags.hasUncompilableErrorOccurred()) {
David Majnemer8c969ea2015-01-30 05:01:23 +0000218 Invalid = true;
219 return;
220 }
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000221 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
222 if (!Invalid) {
Richard Smith696e3122017-02-23 01:43:54 +0000223 CodeSynthesisContext Inst;
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000224 Inst.Kind = Kind;
225 Inst.PointOfInstantiation = PointOfInstantiation;
226 Inst.Entity = Entity;
227 Inst.Template = Template;
228 Inst.TemplateArgs = TemplateArgs.data();
229 Inst.NumTemplateArgs = TemplateArgs.size();
230 Inst.DeductionInfo = DeductionInfo;
231 Inst.InstantiationRange = InstantiationRange;
Richard Smith13381222017-02-23 21:43:43 +0000232 SemaRef.pushCodeSynthesisContext(Inst);
233
Richard Smith54f18e82016-08-31 02:15:21 +0000234 AlreadyInstantiating =
235 !SemaRef.InstantiatingSpecializations
236 .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
237 .second;
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000238 }
239}
240
Benjamin Kramer7761a042015-03-06 16:36:50 +0000241Sema::InstantiatingTemplate::InstantiatingTemplate(
242 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
243 SourceRange InstantiationRange)
244 : InstantiatingTemplate(SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000245 CodeSynthesisContext::TemplateInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000246 PointOfInstantiation, InstantiationRange, Entity) {}
Douglas Gregor79cf6032009-03-10 20:44:00 +0000247
Benjamin Kramer7761a042015-03-06 16:36:50 +0000248Sema::InstantiatingTemplate::InstantiatingTemplate(
249 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
250 ExceptionSpecification, SourceRange InstantiationRange)
251 : InstantiatingTemplate(
Richard Smith696e3122017-02-23 01:43:54 +0000252 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000253 PointOfInstantiation, InstantiationRange, Entity) {}
Richard Smithf623c962012-04-17 00:58:00 +0000254
Benjamin Kramer7761a042015-03-06 16:36:50 +0000255Sema::InstantiatingTemplate::InstantiatingTemplate(
Richard Smith54f18e82016-08-31 02:15:21 +0000256 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
257 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
258 SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000259 : InstantiatingTemplate(
260 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000261 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
Richard Smith54f18e82016-08-31 02:15:21 +0000262 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
263 Template, TemplateArgs) {}
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000264
Benjamin Kramer7761a042015-03-06 16:36:50 +0000265Sema::InstantiatingTemplate::InstantiatingTemplate(
266 Sema &SemaRef, SourceLocation PointOfInstantiation,
267 FunctionTemplateDecl *FunctionTemplate,
268 ArrayRef<TemplateArgument> TemplateArgs,
Richard Smith696e3122017-02-23 01:43:54 +0000269 CodeSynthesisContext::SynthesisKind Kind,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000270 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
271 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
272 InstantiationRange, FunctionTemplate, nullptr,
Richard Smith54f18e82016-08-31 02:15:21 +0000273 TemplateArgs, &DeductionInfo) {
274 assert(
Richard Smith696e3122017-02-23 01:43:54 +0000275 Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
276 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution);
Richard Smith54f18e82016-08-31 02:15:21 +0000277}
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000278
Benjamin Kramer7761a042015-03-06 16:36:50 +0000279Sema::InstantiatingTemplate::InstantiatingTemplate(
280 Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith0e617ec2016-12-27 07:56:27 +0000281 TemplateDecl *Template,
282 ArrayRef<TemplateArgument> TemplateArgs,
283 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
284 : InstantiatingTemplate(
285 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000286 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
Richard Smith0e617ec2016-12-27 07:56:27 +0000287 PointOfInstantiation, InstantiationRange, Template, nullptr,
288 TemplateArgs, &DeductionInfo) {}
289
290Sema::InstantiatingTemplate::InstantiatingTemplate(
291 Sema &SemaRef, SourceLocation PointOfInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000292 ClassTemplatePartialSpecializationDecl *PartialSpec,
293 ArrayRef<TemplateArgument> TemplateArgs,
294 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
295 : InstantiatingTemplate(
296 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000297 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000298 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
299 TemplateArgs, &DeductionInfo) {}
Douglas Gregor637d9982009-06-10 23:47:09 +0000300
Larisse Voufo39a1e502013-08-06 01:03:05 +0000301Sema::InstantiatingTemplate::InstantiatingTemplate(
302 Sema &SemaRef, SourceLocation PointOfInstantiation,
303 VarTemplatePartialSpecializationDecl *PartialSpec,
304 ArrayRef<TemplateArgument> TemplateArgs,
305 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000306 : InstantiatingTemplate(
307 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000308 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000309 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
310 TemplateArgs, &DeductionInfo) {}
Larisse Voufo39a1e502013-08-06 01:03:05 +0000311
Benjamin Kramer7761a042015-03-06 16:36:50 +0000312Sema::InstantiatingTemplate::InstantiatingTemplate(
313 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
314 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
315 : InstantiatingTemplate(
316 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000317 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000318 PointOfInstantiation, InstantiationRange, Param, nullptr,
319 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000320
Benjamin Kramer7761a042015-03-06 16:36:50 +0000321Sema::InstantiatingTemplate::InstantiatingTemplate(
322 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
323 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
324 SourceRange InstantiationRange)
325 : InstantiatingTemplate(
326 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000327 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000328 PointOfInstantiation, InstantiationRange, Param, Template,
329 TemplateArgs) {}
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000330
Benjamin Kramer7761a042015-03-06 16:36:50 +0000331Sema::InstantiatingTemplate::InstantiatingTemplate(
332 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
333 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
334 SourceRange InstantiationRange)
335 : InstantiatingTemplate(
336 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000337 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000338 PointOfInstantiation, InstantiationRange, Param, Template,
339 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000340
Benjamin Kramer7761a042015-03-06 16:36:50 +0000341Sema::InstantiatingTemplate::InstantiatingTemplate(
342 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
343 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
344 SourceRange InstantiationRange)
345 : InstantiatingTemplate(
Richard Smith696e3122017-02-23 01:43:54 +0000346 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000347 PointOfInstantiation, InstantiationRange, Param, Template,
348 TemplateArgs) {}
Anders Carlsson657bad42009-09-05 05:14:19 +0000349
Richard Smith13381222017-02-23 21:43:43 +0000350void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
351 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
352 InNonInstantiationSFINAEContext = false;
353
354 CodeSynthesisContexts.push_back(Ctx);
355
356 if (!Ctx.isInstantiationRecord())
357 ++NonInstantiationEntries;
358}
359
360void Sema::popCodeSynthesisContext() {
361 auto &Active = CodeSynthesisContexts.back();
362 if (!Active.isInstantiationRecord()) {
363 assert(NonInstantiationEntries > 0);
364 --NonInstantiationEntries;
365 }
366
367 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
368
369 // Name lookup no longer looks in this template's defining module.
370 assert(CodeSynthesisContexts.size() >=
371 CodeSynthesisContextLookupModules.size() &&
372 "forgot to remove a lookup module for a template instantiation");
373 if (CodeSynthesisContexts.size() ==
374 CodeSynthesisContextLookupModules.size()) {
375 if (Module *M = CodeSynthesisContextLookupModules.back())
376 LookupModulesCache.erase(M);
377 CodeSynthesisContextLookupModules.pop_back();
378 }
379
380 // If we've left the code synthesis context for the current context stack,
381 // stop remembering that we've emitted that stack.
382 if (CodeSynthesisContexts.size() ==
383 LastEmittedCodeSynthesisContextDepth)
384 LastEmittedCodeSynthesisContextDepth = 0;
385
386 CodeSynthesisContexts.pop_back();
387}
388
Douglas Gregor85673582009-05-18 17:01:57 +0000389void Sema::InstantiatingTemplate::Clear() {
390 if (!Invalid) {
Richard Smith13381222017-02-23 21:43:43 +0000391 if (!AlreadyInstantiating) {
392 auto &Active = SemaRef.CodeSynthesisContexts.back();
Richard Smith54f18e82016-08-31 02:15:21 +0000393 SemaRef.InstantiatingSpecializations.erase(
394 std::make_pair(Active.Entity, Active.Kind));
Richard Smith13381222017-02-23 21:43:43 +0000395 }
Richard Smith54f18e82016-08-31 02:15:21 +0000396
Richard Smith13381222017-02-23 21:43:43 +0000397 SemaRef.popCodeSynthesisContext();
398
Douglas Gregor85673582009-05-18 17:01:57 +0000399 Invalid = true;
400 }
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000401}
402
Douglas Gregor79cf6032009-03-10 20:44:00 +0000403bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
404 SourceLocation PointOfInstantiation,
405 SourceRange InstantiationRange) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000406 assert(SemaRef.NonInstantiationEntries <=
Richard Smith696e3122017-02-23 01:43:54 +0000407 SemaRef.CodeSynthesisContexts.size());
408 if ((SemaRef.CodeSynthesisContexts.size() -
Douglas Gregor84d49a22009-11-11 21:54:23 +0000409 SemaRef.NonInstantiationEntries)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000410 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregor79cf6032009-03-10 20:44:00 +0000411 return false;
412
Mike Stump11289f42009-09-09 15:08:12 +0000413 SemaRef.Diag(PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000414 diag::err_template_recursion_depth_exceeded)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000415 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregor79cf6032009-03-10 20:44:00 +0000416 << InstantiationRange;
417 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000418 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000419 return true;
420}
421
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000422/// \brief Prints the current instantiation stack through a series of
423/// notes.
424void Sema::PrintInstantiationStack() {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000425 // Determine which template instantiations to skip, if any.
Richard Smith696e3122017-02-23 01:43:54 +0000426 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000427 unsigned Limit = Diags.getTemplateBacktraceLimit();
Richard Smith696e3122017-02-23 01:43:54 +0000428 if (Limit && Limit < CodeSynthesisContexts.size()) {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000429 SkipStart = Limit / 2 + Limit % 2;
Richard Smith696e3122017-02-23 01:43:54 +0000430 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000431 }
432
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000433 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000434 unsigned InstantiationIdx = 0;
Richard Smith696e3122017-02-23 01:43:54 +0000435 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
436 Active = CodeSynthesisContexts.rbegin(),
437 ActiveEnd = CodeSynthesisContexts.rend();
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000438 Active != ActiveEnd;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000439 ++Active, ++InstantiationIdx) {
440 // Skip this instantiation?
441 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
442 if (InstantiationIdx == SkipStart) {
443 // Note that we're skipping instantiations.
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000444 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000445 diag::note_instantiation_contexts_suppressed)
Richard Smith696e3122017-02-23 01:43:54 +0000446 << unsigned(CodeSynthesisContexts.size() - Limit);
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000447 }
448 continue;
449 }
450
Douglas Gregor79cf6032009-03-10 20:44:00 +0000451 switch (Active->Kind) {
Richard Smith696e3122017-02-23 01:43:54 +0000452 case CodeSynthesisContext::TemplateInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000453 Decl *D = Active->Entity;
Douglas Gregor85673582009-05-18 17:01:57 +0000454 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
455 unsigned DiagID = diag::note_template_member_class_here;
456 if (isa<ClassTemplateSpecializationDecl>(Record))
457 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000458 Diags.Report(Active->PointOfInstantiation, DiagID)
Richard Smith792c22d2016-12-24 04:09:05 +0000459 << Record << Active->InstantiationRange;
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000460 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +0000461 unsigned DiagID;
462 if (Function->getPrimaryTemplate())
463 DiagID = diag::note_function_template_spec_here;
464 else
465 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000466 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000467 << Function
468 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000469 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000470 Diags.Report(Active->PointOfInstantiation,
Larisse Voufodbd65772013-08-14 20:15:02 +0000471 VD->isStaticDataMember()?
472 diag::note_template_static_data_member_def_here
473 : diag::note_template_variable_def_here)
Richard Smith3f1b5d02011-05-05 21:57:07 +0000474 << VD
475 << Active->InstantiationRange;
Richard Smith4b38ded2012-03-14 23:13:10 +0000476 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
477 Diags.Report(Active->PointOfInstantiation,
478 diag::note_template_enum_def_here)
479 << ED
480 << Active->InstantiationRange;
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000481 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
482 Diags.Report(Active->PointOfInstantiation,
483 diag::note_template_nsdmi_here)
484 << FD << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000485 } else {
486 Diags.Report(Active->PointOfInstantiation,
487 diag::note_template_type_alias_instantiation_here)
488 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000489 << Active->InstantiationRange;
Douglas Gregor85673582009-05-18 17:01:57 +0000490 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000491 break;
492 }
493
Richard Smith696e3122017-02-23 01:43:54 +0000494 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
Richard Smith54f18e82016-08-31 02:15:21 +0000495 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000496 SmallVector<char, 128> TemplateArgsStr;
497 llvm::raw_svector_ostream OS(TemplateArgsStr);
498 Template->printName(OS);
David Majnemer6fbeee32016-07-07 04:43:07 +0000499 TemplateSpecializationType::PrintTemplateArgumentList(
500 OS, Active->template_arguments(), getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000501 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000502 diag::note_default_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000503 << OS.str()
Douglas Gregor79cf6032009-03-10 20:44:00 +0000504 << Active->InstantiationRange;
505 break;
506 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000507
Richard Smith696e3122017-02-23 01:43:54 +0000508 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000509 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000510 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000511 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000512 << FnTmpl
513 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
514 Active->TemplateArgs,
515 Active->NumTemplateArgs)
516 << Active->InstantiationRange;
Douglas Gregor637d9982009-06-10 23:47:09 +0000517 break;
518 }
Mike Stump11289f42009-09-09 15:08:12 +0000519
Richard Smith696e3122017-02-23 01:43:54 +0000520 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
Richard Smithe68a38f2016-12-24 04:20:31 +0000521 if (FunctionTemplateDecl *FnTmpl =
522 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000523 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000524 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000525 << FnTmpl
526 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
527 Active->TemplateArgs,
528 Active->NumTemplateArgs)
529 << Active->InstantiationRange;
Richard Smithe68a38f2016-12-24 04:20:31 +0000530 } else {
531 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
532 isa<VarTemplateSpecializationDecl>(Active->Entity);
Richard Smith0e617ec2016-12-27 07:56:27 +0000533 bool IsTemplate = false;
Richard Smithe68a38f2016-12-24 04:20:31 +0000534 TemplateParameterList *Params;
Richard Smith0e617ec2016-12-27 07:56:27 +0000535 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
536 IsTemplate = true;
537 Params = D->getTemplateParameters();
538 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
Richard Smithe68a38f2016-12-24 04:20:31 +0000539 Active->Entity)) {
540 Params = D->getTemplateParameters();
541 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
542 Active->Entity)) {
543 Params = D->getTemplateParameters();
544 } else {
545 llvm_unreachable("unexpected template kind");
546 }
547
Richard Smithe68a38f2016-12-24 04:20:31 +0000548 Diags.Report(Active->PointOfInstantiation,
549 diag::note_deduced_template_arg_substitution_here)
Richard Smith0e617ec2016-12-27 07:56:27 +0000550 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
Richard Smithe68a38f2016-12-24 04:20:31 +0000551 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
552 Active->NumTemplateArgs)
553 << Active->InstantiationRange;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000554 }
555 break;
Richard Smithe68a38f2016-12-24 04:20:31 +0000556 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000557
Richard Smith696e3122017-02-23 01:43:54 +0000558 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000559 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson657bad42009-09-05 05:14:19 +0000560 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +0000561
Benjamin Kramer9170e912013-02-22 15:46:01 +0000562 SmallVector<char, 128> TemplateArgsStr;
563 llvm::raw_svector_ostream OS(TemplateArgsStr);
564 FD->printName(OS);
David Majnemer6fbeee32016-07-07 04:43:07 +0000565 TemplateSpecializationType::PrintTemplateArgumentList(
566 OS, Active->template_arguments(), getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000567 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000568 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000569 << OS.str()
Anders Carlsson657bad42009-09-05 05:14:19 +0000570 << Active->InstantiationRange;
571 break;
572 }
Mike Stump11289f42009-09-09 15:08:12 +0000573
Richard Smith696e3122017-02-23 01:43:54 +0000574 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000575 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000576 std::string Name;
577 if (!Parm->getName().empty())
578 Name = std::string(" '") + Parm->getName().str() + "'";
Craig Topperc3ec1492014-05-26 06:22:03 +0000579
580 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000581 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
582 TemplateParams = Template->getTemplateParameters();
583 else
584 TemplateParams =
585 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
586 ->getTemplateParameters();
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000587 Diags.Report(Active->PointOfInstantiation,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000588 diag::note_prior_template_arg_substitution)
589 << isa<TemplateTemplateParmDecl>(Parm)
590 << Name
Douglas Gregorca4686d2011-01-04 23:35:54 +0000591 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000592 Active->TemplateArgs,
593 Active->NumTemplateArgs)
594 << Active->InstantiationRange;
595 break;
596 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000597
Richard Smith696e3122017-02-23 01:43:54 +0000598 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
Craig Topperc3ec1492014-05-26 06:22:03 +0000599 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000600 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
601 TemplateParams = Template->getTemplateParameters();
602 else
603 TemplateParams =
604 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
605 ->getTemplateParameters();
606
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000607 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000608 diag::note_template_default_arg_checking)
Douglas Gregorca4686d2011-01-04 23:35:54 +0000609 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000610 Active->TemplateArgs,
611 Active->NumTemplateArgs)
612 << Active->InstantiationRange;
613 break;
614 }
Richard Smithf623c962012-04-17 00:58:00 +0000615
Richard Smith696e3122017-02-23 01:43:54 +0000616 case CodeSynthesisContext::ExceptionSpecInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000617 Diags.Report(Active->PointOfInstantiation,
618 diag::note_template_exception_spec_instantiation_here)
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000619 << cast<FunctionDecl>(Active->Entity)
Richard Smithf623c962012-04-17 00:58:00 +0000620 << Active->InstantiationRange;
621 break;
Richard Smith13381222017-02-23 21:43:43 +0000622
623 case CodeSynthesisContext::DeclaringSpecialMember:
624 Diags.Report(Active->PointOfInstantiation,
625 diag::note_in_declaration_of_implicit_special_member)
626 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
627 break;
Richard Smith883dbc42017-05-25 22:47:05 +0000628
629 case CodeSynthesisContext::DefiningSynthesizedFunction:
630 // FIXME: For synthesized members other than special members, produce a note.
631 auto *MD = dyn_cast<CXXMethodDecl>(Active->Entity);
632 auto CSM = MD ? getSpecialMember(MD) : CXXInvalid;
633 if (CSM != CXXInvalid) {
634 Diags.Report(Active->PointOfInstantiation,
635 diag::note_member_synthesized_at)
636 << CSM << Context.getTagDeclType(MD->getParent());
637 }
638 break;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000639 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000640 }
641}
642
David Blaikie05785d12013-02-20 22:23:23 +0000643Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregoredb76852011-01-27 22:31:44 +0000644 if (InNonInstantiationSFINAEContext)
Craig Topperc3ec1492014-05-26 06:22:03 +0000645 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregoredb76852011-01-27 22:31:44 +0000646
Richard Smith696e3122017-02-23 01:43:54 +0000647 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
648 Active = CodeSynthesisContexts.rbegin(),
649 ActiveEnd = CodeSynthesisContexts.rend();
Douglas Gregor33834512009-06-14 07:33:30 +0000650 Active != ActiveEnd;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000651 ++Active)
652 {
Richard Smith13381222017-02-23 21:43:43 +0000653 switch (Active->Kind) {
Richard Smith696e3122017-02-23 01:43:54 +0000654 case CodeSynthesisContext::TemplateInstantiation:
Richard Smith72249ba2012-04-26 07:24:08 +0000655 // An instantiation of an alias template may or may not be a SFINAE
656 // context, depending on what else is on the stack.
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000657 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smith72249ba2012-04-26 07:24:08 +0000658 break;
659 // Fall through.
Richard Smith696e3122017-02-23 01:43:54 +0000660 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
661 case CodeSynthesisContext::ExceptionSpecInstantiation:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000662 // This is a template instantiation, so there is no SFINAE.
David Blaikie7a30dc52013-02-21 01:47:18 +0000663 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000664
Richard Smith696e3122017-02-23 01:43:54 +0000665 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
666 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
667 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000668 // A default template argument instantiation and substitution into
669 // template parameters with arguments for prior parameters may or may
670 // not be a SFINAE context; look further up the stack.
Douglas Gregor33834512009-06-14 07:33:30 +0000671 break;
Mike Stump11289f42009-09-09 15:08:12 +0000672
Richard Smith696e3122017-02-23 01:43:54 +0000673 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
674 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000675 // We're either substitution explicitly-specified template arguments
676 // or deduced template arguments, so SFINAE applies.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000677 assert(Active->DeductionInfo && "Missing deduction info pointer");
678 return Active->DeductionInfo;
Richard Smith13381222017-02-23 21:43:43 +0000679
680 case CodeSynthesisContext::DeclaringSpecialMember:
Richard Smith883dbc42017-05-25 22:47:05 +0000681 case CodeSynthesisContext::DefiningSynthesizedFunction:
Richard Smith13381222017-02-23 21:43:43 +0000682 // This happens in a context unrelated to template instantiation, so
683 // there is no SFINAE.
684 return None;
Douglas Gregor33834512009-06-14 07:33:30 +0000685 }
Richard Smith13381222017-02-23 21:43:43 +0000686
687 // The inner context was transparent for SFINAE. If it occurred within a
688 // non-instantiation SFINAE context, then SFINAE applies.
689 if (Active->SavedInNonInstantiationSFINAEContext)
690 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregor33834512009-06-14 07:33:30 +0000691 }
692
David Blaikie7a30dc52013-02-21 01:47:18 +0000693 return None;
Douglas Gregor33834512009-06-14 07:33:30 +0000694}
695
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000696/// \brief Retrieve the depth and index of a parameter pack.
697static std::pair<unsigned, unsigned>
698getDepthAndIndex(NamedDecl *ND) {
699 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
700 return std::make_pair(TTP->getDepth(), TTP->getIndex());
701
702 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
703 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
704
705 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
706 return std::make_pair(TTP->getDepth(), TTP->getIndex());
707}
708
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000709//===----------------------------------------------------------------------===/
710// Template Instantiation for Types
711//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000712namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000713 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000714 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000715 SourceLocation Loc;
716 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000717
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000718 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000719 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000720
721 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000722 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000723 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000724 DeclarationName Entity)
725 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000726 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000727
Mike Stump11289f42009-09-09 15:08:12 +0000728 /// \brief Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-08-04 16:50:30 +0000729 /// transformed.
730 ///
731 /// For the purposes of template instantiation, a type has already been
732 /// transformed if it is NULL or if it is not dependent.
Douglas Gregor5597ab42010-05-07 23:12:07 +0000733 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000734
Douglas Gregord6ff3322009-08-04 16:50:30 +0000735 /// \brief Returns the location of the entity being instantiated, if known.
736 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000737
Douglas Gregord6ff3322009-08-04 16:50:30 +0000738 /// \brief Returns the name of the entity being instantiated, if any.
739 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000740
Douglas Gregoref6ab412009-10-27 06:26:26 +0000741 /// \brief Sets the "base" location and entity when that
742 /// information is known based on another transformation.
743 void setBase(SourceLocation Loc, DeclarationName Entity) {
744 this->Loc = Loc;
745 this->Entity = Entity;
746 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000747
748 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
749 SourceRange PatternRange,
Robert Wilhelm16e94b92013-08-09 18:02:13 +0000750 ArrayRef<UnexpandedParameterPack> Unexpanded,
751 bool &ShouldExpand, bool &RetainExpansion,
David Blaikie05785d12013-02-20 22:23:23 +0000752 Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000753 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
754 PatternRange, Unexpanded,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000755 TemplateArgs,
756 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000757 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000758 NumExpansions);
759 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000760
Douglas Gregorf3010112011-01-07 16:43:16 +0000761 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
762 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
763 }
764
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000765 TemplateArgument ForgetPartiallySubstitutedPack() {
766 TemplateArgument Result;
767 if (NamedDecl *PartialPack
768 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
769 MultiLevelTemplateArgumentList &TemplateArgs
770 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
771 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000772 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000773 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
774 Result = TemplateArgs(Depth, Index);
775 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
776 }
777 }
778
779 return Result;
780 }
781
782 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
783 if (Arg.isNull())
784 return;
785
786 if (NamedDecl *PartialPack
787 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
788 MultiLevelTemplateArgumentList &TemplateArgs
789 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
790 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000791 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000792 TemplateArgs.setArgument(Depth, Index, Arg);
793 }
794 }
795
Douglas Gregord6ff3322009-08-04 16:50:30 +0000796 /// \brief Transform the given declaration by instantiating a reference to
797 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000798 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000799
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000800 void transformAttrs(Decl *Old, Decl *New) {
801 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
802 }
803
804 void transformedLocalDecl(Decl *Old, Decl *New) {
Richard Smithc38498f2015-04-27 21:27:54 +0000805 // If we've instantiated the call operator of a lambda or the call
806 // operator template of a generic lambda, update the "instantiation of"
807 // information.
808 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
809 if (NewMD && isLambdaCallOperator(NewMD)) {
810 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
811 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
812 NewTD->setInstantiatedFromMemberTemplate(
813 OldMD->getDescribedFunctionTemplate());
814 else
815 NewMD->setInstantiationOfMemberFunction(OldMD,
816 TSK_ImplicitInstantiation);
817 }
818
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000819 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
Richard Smithc7649dc2016-03-23 20:07:07 +0000820
821 // We recreated a local declaration, but not by instantiating it. There
822 // may be pending dependent diagnostics to produce.
823 if (auto *DC = dyn_cast<DeclContext>(Old))
824 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000825 }
826
Mike Stump11289f42009-09-09 15:08:12 +0000827 /// \brief Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000828 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000829 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000830
Dmitri Gribenko00bcdd32012-09-12 17:01:48 +0000831 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000832 /// declaration.
833 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
834
Douglas Gregorebe10102009-08-20 07:17:43 +0000835 /// \brief Rebuild the exception declaration and register the declaration
836 /// as an instantiated local.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000837 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000838 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000839 SourceLocation StartLoc,
840 SourceLocation NameLoc,
841 IdentifierInfo *Name);
Mike Stump11289f42009-09-09 15:08:12 +0000842
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000843 /// \brief Rebuild the Objective-C exception declaration and register the
844 /// declaration as an instantiated local.
845 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
846 TypeSourceInfo *TSInfo, QualType T);
847
John McCall7f41d982009-09-11 04:59:25 +0000848 /// \brief Check for tag mismatches when instantiating an
849 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000850 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
851 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000852 NestedNameSpecifierLoc QualifierLoc,
853 QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000854
Craig Topperc3ec1492014-05-26 06:22:03 +0000855 TemplateName
856 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
857 SourceLocation NameLoc,
858 QualType ObjectType = QualType(),
Richard Smithfd3dae02017-01-20 00:20:39 +0000859 NamedDecl *FirstQualifierInScope = nullptr,
860 bool AllowInjectedClassName = false);
Douglas Gregor9db53502011-03-02 18:07:45 +0000861
Tyler Nowickic724a83e2014-10-12 20:46:07 +0000862 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
863
John McCalldadc5752010-08-24 06:29:42 +0000864 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
865 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
866 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000867
John McCalldadc5752010-08-24 06:29:42 +0000868 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000869 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000870 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
871 SubstNonTypeTemplateParmPackExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000872
873 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
874 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
875
876 /// \brief Transform a reference to a function parameter pack.
877 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
878 ParmVarDecl *PD);
879
880 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
881 /// expand a function parameter pack reference which refers to an expanded
882 /// pack.
883 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
884
Hans Wennborge113c202014-09-18 16:01:32 +0000885 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
Richard Smith2e321552014-11-12 02:00:47 +0000886 FunctionProtoTypeLoc TL) {
887 // Call the base version; it will forward to our overridden version below.
888 return inherited::TransformFunctionProtoType(TLB, TL);
889 }
890
891 template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +0000892 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
893 FunctionProtoTypeLoc TL,
894 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +0000895 unsigned ThisTypeQuals,
896 Fn TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +0000897
Douglas Gregor715e4612011-01-14 22:40:04 +0000898 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +0000899 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +0000900 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +0000901 bool ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +0000902
Mike Stump11289f42009-09-09 15:08:12 +0000903 /// \brief Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +0000904 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +0000905 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000906 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000907
Douglas Gregorada4b792011-01-14 02:55:32 +0000908 /// \brief Transforms an already-substituted template type parameter pack
909 /// into either itself (if we aren't substituting into its pack expansion)
910 /// or the appropriate substituted argument.
911 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
912 SubstTemplateTypeParmPackTypeLoc TL);
913
Richard Smith2589b9802012-07-25 03:56:55 +0000914 ExprResult TransformLambdaExpr(LambdaExpr *E) {
915 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
916 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
917 }
918
David Majnemerb1004102014-03-02 18:46:05 +0000919 TemplateParameterList *TransformTemplateParameterList(
Faisal Vali2cba1332013-10-23 06:44:28 +0000920 TemplateParameterList *OrigTPL) {
921 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
922
923 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
924 TemplateDeclInstantiator DeclInstantiator(getSema(),
925 /* DeclContext *Owner */ Owner, TemplateArgs);
926 return DeclInstantiator.SubstTemplateParams(OrigTPL);
927 }
John McCall7c454bb2011-07-15 05:09:51 +0000928 private:
929 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
930 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +0000931 TemplateArgument arg);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000932 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000933}
Douglas Gregor04318252009-07-06 15:59:29 +0000934
Douglas Gregor5597ab42010-05-07 23:12:07 +0000935bool TemplateInstantiator::AlreadyTransformed(QualType T) {
936 if (T.isNull())
937 return true;
938
Douglas Gregor678d76c2011-07-01 01:22:09 +0000939 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +0000940 return false;
941
942 getSema().MarkDeclarationsReferencedInType(Loc, T);
943 return true;
944}
945
Eli Friedman8917ad52013-07-19 19:40:38 +0000946static TemplateArgument
947getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
948 assert(S.ArgumentPackSubstitutionIndex >= 0);
949 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
950 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
951 if (Arg.isPackExpansion())
952 Arg = Arg.getPackExpansionPattern();
953 return Arg;
954}
955
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000956Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000957 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +0000958 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000959
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000960 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000961 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +0000962 // If the corresponding template argument is NULL or non-existent, it's
963 // because we are performing instantiation from explicitly-specified
964 // template arguments in a function template, but there were some
965 // arguments left unspecified.
966 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
967 TTP->getPosition()))
968 return D;
969
Douglas Gregorf5500772011-01-05 15:48:55 +0000970 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
971
972 if (TTP->isParameterPack()) {
973 assert(Arg.getKind() == TemplateArgument::Pack &&
974 "Missing argument pack");
Eli Friedman8917ad52013-07-19 19:40:38 +0000975 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorf5500772011-01-05 15:48:55 +0000976 }
977
Richard Smith1abacfc2017-08-29 22:14:43 +0000978 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000979 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +0000980 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000981 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +0000982 }
Mike Stump11289f42009-09-09 15:08:12 +0000983
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000984 // Fall through to find the instantiated declaration for this template
985 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +0000986 }
Mike Stump11289f42009-09-09 15:08:12 +0000987
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000988 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000989}
990
Douglas Gregor25289362010-03-01 17:25:41 +0000991Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +0000992 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +0000993 if (!Inst)
Craig Topperc3ec1492014-05-26 06:22:03 +0000994 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000995
Douglas Gregorebe10102009-08-20 07:17:43 +0000996 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
997 return Inst;
998}
999
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001000NamedDecl *
1001TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1002 SourceLocation Loc) {
1003 // If the first part of the nested-name-specifier was a template type
1004 // parameter, instantiate that type parameter down to a tag type.
1005 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1006 const TemplateTypeParmType *TTP
1007 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001008
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001009 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001010 // FIXME: This needs testing w/ member access expressions.
1011 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1012
1013 if (TTP->isParameterPack()) {
1014 assert(Arg.getKind() == TemplateArgument::Pack &&
1015 "Missing argument pack");
1016
Douglas Gregore1d60df2011-01-14 23:41:42 +00001017 if (getSema().ArgumentPackSubstitutionIndex == -1)
Craig Topperc3ec1492014-05-26 06:22:03 +00001018 return nullptr;
1019
Eli Friedman8917ad52013-07-19 19:40:38 +00001020 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001021 }
1022
1023 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001024 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001025 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001026
1027 if (const TagType *Tag = T->getAs<TagType>())
1028 return Tag->getDecl();
1029
1030 // The resulting type is not a tag; complain.
1031 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
Craig Topperc3ec1492014-05-26 06:22:03 +00001032 return nullptr;
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001033 }
1034 }
1035
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001036 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001037}
1038
Douglas Gregorebe10102009-08-20 07:17:43 +00001039VarDecl *
1040TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +00001041 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001042 SourceLocation StartLoc,
1043 SourceLocation NameLoc,
1044 IdentifierInfo *Name) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00001045 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001046 StartLoc, NameLoc, Name);
Douglas Gregorf4e837f2010-04-26 17:57:08 +00001047 if (Var)
1048 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1049 return Var;
1050}
1051
1052VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1053 TypeSourceInfo *TSInfo,
1054 QualType T) {
1055 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1056 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +00001057 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1058 return Var;
1059}
1060
John McCall7f41d982009-09-11 04:59:25 +00001061QualType
John McCall954b5de2010-11-04 19:04:38 +00001062TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1063 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001064 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara6150c882010-05-11 21:36:43 +00001065 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +00001066 if (const TagType *TT = T->getAs<TagType>()) {
1067 TagDecl* TD = TT->getDecl();
1068
John McCall954b5de2010-11-04 19:04:38 +00001069 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +00001070
John McCall7f41d982009-09-11 04:59:25 +00001071 IdentifierInfo *Id = TD->getIdentifier();
1072
1073 // TODO: should we even warn on struct/class mismatches for this? Seems
1074 // like it's likely to produce a lot of spurious errors.
Richard Smith80b3c5a2012-08-17 00:12:27 +00001075 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001076 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieucaa33d32011-06-10 03:11:26 +00001077 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001078 TagLocation, Id)) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001079 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1080 << Id
1081 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1082 TD->getKindName());
1083 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1084 }
John McCall7f41d982009-09-11 04:59:25 +00001085 }
1086 }
1087
John McCall954b5de2010-11-04 19:04:38 +00001088 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1089 Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001090 QualifierLoc,
1091 T);
John McCall7f41d982009-09-11 04:59:25 +00001092}
1093
Richard Smithfd3dae02017-01-20 00:20:39 +00001094TemplateName TemplateInstantiator::TransformTemplateName(
1095 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1096 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1097 bool AllowInjectedClassName) {
Douglas Gregor9db53502011-03-02 18:07:45 +00001098 if (TemplateTemplateParmDecl *TTP
1099 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1100 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1101 // If the corresponding template argument is NULL or non-existent, it's
1102 // because we are performing instantiation from explicitly-specified
1103 // template arguments in a function template, but there were some
1104 // arguments left unspecified.
1105 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1106 TTP->getPosition()))
1107 return Name;
1108
1109 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1110
1111 if (TTP->isParameterPack()) {
1112 assert(Arg.getKind() == TemplateArgument::Pack &&
1113 "Missing argument pack");
1114
1115 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1116 // We have the template argument pack to substitute, but we're not
1117 // actually expanding the enclosing pack expansion yet. So, just
1118 // keep the entire argument pack.
1119 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1120 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001121
1122 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor9db53502011-03-02 18:07:45 +00001123 }
1124
Richard Smith1abacfc2017-08-29 22:14:43 +00001125 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001126 assert(!Template.isNull() && "Null template template argument");
Richard Smith1abacfc2017-08-29 22:14:43 +00001127 assert(!Template.getAsQualifiedTemplateName() &&
1128 "template decl to substitute is qualified?");
John McCalld9dfe3a2011-06-30 08:33:18 +00001129
1130 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregor9db53502011-03-02 18:07:45 +00001131 return Template;
1132 }
1133 }
1134
1135 if (SubstTemplateTemplateParmPackStorage *SubstPack
1136 = Name.getAsSubstTemplateTemplateParmPack()) {
1137 if (getSema().ArgumentPackSubstitutionIndex == -1)
1138 return Name;
1139
Eli Friedman8917ad52013-07-19 19:40:38 +00001140 TemplateArgument Arg = SubstPack->getArgumentPack();
1141 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Richard Smith1abacfc2017-08-29 22:14:43 +00001142 return Arg.getAsTemplate().getNameToSubstitute();
Douglas Gregor9db53502011-03-02 18:07:45 +00001143 }
Richard Smithfd3dae02017-01-20 00:20:39 +00001144
1145 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1146 FirstQualifierInScope,
1147 AllowInjectedClassName);
Douglas Gregor9db53502011-03-02 18:07:45 +00001148}
1149
John McCalldadc5752010-08-24 06:29:42 +00001150ExprResult
John McCall47f29ea2009-12-08 09:21:05 +00001151TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +00001152 if (!E->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001153 return E;
Anders Carlsson0b209a82009-09-11 01:22:35 +00001154
Wei Panc354d212013-09-16 13:57:27 +00001155 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
Anders Carlsson0b209a82009-09-11 01:22:35 +00001156}
1157
John McCalldadc5752010-08-24 06:29:42 +00001158ExprResult
John McCall13481c52010-02-06 08:42:39 +00001159TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001160 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +00001161 // If the corresponding template argument is NULL or non-existent, it's
1162 // because we are performing instantiation from explicitly-specified
1163 // template arguments in a function template, but there were some
1164 // arguments left unspecified.
1165 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1166 NTTP->getPosition()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001167 return E;
Mike Stump11289f42009-09-09 15:08:12 +00001168
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001169 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
Richard Smithb4f96252017-02-21 06:30:38 +00001170
1171 if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1172 // We're performing a partial substitution, so the substituted argument
1173 // could be dependent. As a result we can't create a SubstNonType*Expr
1174 // node now, since that represents a fully-substituted argument.
1175 // FIXME: We should have some AST representation for this.
1176 if (Arg.getKind() == TemplateArgument::Pack) {
1177 // FIXME: This won't work for alias templates.
1178 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1179 "unexpected pack arguments in partial substitution");
1180 Arg = Arg.pack_begin()->getPackExpansionPattern();
1181 }
1182 assert(Arg.getKind() == TemplateArgument::Expression &&
1183 "unexpected nontype template argument kind in partial substitution");
1184 return Arg.getAsExpr();
1185 }
1186
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001187 if (NTTP->isParameterPack()) {
1188 assert(Arg.getKind() == TemplateArgument::Pack &&
1189 "Missing argument pack");
1190
1191 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001192 // We have an argument pack, but we can't select a particular argument
1193 // out of it yet. Therefore, we'll build an expression to hold on to that
1194 // argument pack.
1195 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1196 E->getLocation(),
1197 NTTP->getDeclName());
1198 if (TargetType.isNull())
1199 return ExprError();
1200
1201 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1202 NTTP,
1203 E->getLocation(),
1204 Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001205 }
1206
Eli Friedman8917ad52013-07-19 19:40:38 +00001207 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001208 }
Mike Stump11289f42009-09-09 15:08:12 +00001209
John McCall7c454bb2011-07-15 05:09:51 +00001210 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1211}
1212
Tyler Nowickic724a83e2014-10-12 20:46:07 +00001213const LoopHintAttr *
1214TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1215 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1216
1217 if (TransformedExpr == LH->getValue())
1218 return LH;
1219
1220 // Generate error if there is a problem with the value.
1221 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1222 return LH;
1223
1224 // Create new LoopHintValueAttr with integral expression in place of the
1225 // non-type template parameter.
1226 return LoopHintAttr::CreateImplicit(
1227 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1228 LH->getState(), TransformedExpr, LH->getRange());
1229}
1230
John McCall7c454bb2011-07-15 05:09:51 +00001231ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1232 NonTypeTemplateParmDecl *parm,
1233 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001234 TemplateArgument arg) {
John McCall7c454bb2011-07-15 05:09:51 +00001235 ExprResult result;
1236 QualType type;
1237
John McCall13481c52010-02-06 08:42:39 +00001238 // The template argument itself might be an expression, in which
1239 // case we just return that expression.
John McCall7c454bb2011-07-15 05:09:51 +00001240 if (arg.getKind() == TemplateArgument::Expression) {
1241 Expr *argExpr = arg.getAsExpr();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001242 result = argExpr;
John McCall7c454bb2011-07-15 05:09:51 +00001243 type = argExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001244
Eli Friedmanb826a002012-09-26 02:36:12 +00001245 } else if (arg.getKind() == TemplateArgument::Declaration ||
1246 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001247 ValueDecl *VD;
Eli Friedmanb826a002012-09-26 02:36:12 +00001248 if (arg.getKind() == TemplateArgument::Declaration) {
1249 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001250
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001251 // Find the instantiation of the template argument. This is
1252 // required for nested templates.
1253 VD = cast_or_null<ValueDecl>(
1254 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1255 if (!VD)
1256 return ExprError();
1257 } else {
1258 // Propagate NULL template argument.
Craig Topperc3ec1492014-05-26 06:22:03 +00001259 VD = nullptr;
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001260 }
1261
John McCall15dda372010-02-06 10:23:53 +00001262 // Derive the type we want the substituted decl to have. This had
1263 // better be non-dependent, or these checks will have serious problems.
John McCall7c454bb2011-07-15 05:09:51 +00001264 if (parm->isExpandedParameterPack()) {
1265 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1266 } else if (parm->isParameterPack() &&
1267 isa<PackExpansionType>(parm->getType())) {
1268 type = SemaRef.SubstType(
1269 cast<PackExpansionType>(parm->getType())->getPattern(),
1270 TemplateArgs, loc, parm->getDeclName());
1271 } else {
Richard Smith5f274382016-09-28 23:55:27 +00001272 type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1273 TemplateArgs, loc, parm->getDeclName());
John McCall7c454bb2011-07-15 05:09:51 +00001274 }
1275 assert(!type.isNull() && "type substitution failed for param type");
1276 assert(!type->isDependentType() && "param type still dependent");
1277 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCall13481c52010-02-06 08:42:39 +00001278
John McCall7c454bb2011-07-15 05:09:51 +00001279 if (!result.isInvalid()) type = result.get()->getType();
1280 } else {
1281 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1282
1283 // Note that this type can be different from the type of 'result',
1284 // e.g. if it's an enum type.
1285 type = arg.getIntegralType();
1286 }
1287 if (result.isInvalid()) return ExprError();
1288
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001289 Expr *resultExpr = result.get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001290 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1291 type, resultExpr->getValueKind(), loc, parm, resultExpr);
John McCall13481c52010-02-06 08:42:39 +00001292}
1293
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001294ExprResult
1295TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1296 SubstNonTypeTemplateParmPackExpr *E) {
1297 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1298 // We aren't expanding the parameter pack, so just return ourselves.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001299 return E;
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001300 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001301
1302 TemplateArgument Arg = E->getArgumentPack();
1303 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall7c454bb2011-07-15 05:09:51 +00001304 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1305 E->getParameterPackLocation(),
1306 Arg);
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001307}
John McCall13481c52010-02-06 08:42:39 +00001308
John McCalldadc5752010-08-24 06:29:42 +00001309ExprResult
Richard Smithb15fe3a2012-09-12 00:56:43 +00001310TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1311 SourceLocation Loc) {
1312 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1313 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1314}
1315
1316ExprResult
1317TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1318 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1319 // We can expand this parameter pack now.
1320 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1321 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1322 if (!VD)
1323 return ExprError();
1324 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1325 }
1326
1327 QualType T = TransformType(E->getType());
1328 if (T.isNull())
1329 return ExprError();
1330
1331 // Transform each of the parameter expansions into the corresponding
1332 // parameters in the instantiation of the function decl.
James Y Knight48fefa32015-09-30 14:04:23 +00001333 SmallVector<ParmVarDecl *, 8> Parms;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001334 Parms.reserve(E->getNumExpansions());
1335 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1336 I != End; ++I) {
1337 ParmVarDecl *D =
1338 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1339 if (!D)
1340 return ExprError();
1341 Parms.push_back(D);
1342 }
1343
1344 return FunctionParmPackExpr::Create(getSema().Context, T,
1345 E->getParameterPack(),
1346 E->getParameterPackLocation(), Parms);
1347}
1348
1349ExprResult
1350TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1351 ParmVarDecl *PD) {
1352 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1353 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1354 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1355 assert(Found && "no instantiation for parameter pack");
1356
1357 Decl *TransformedDecl;
1358 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
Nico Weberc153d242014-07-28 00:02:09 +00001359 // If this is a reference to a function parameter pack which we can
1360 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
Richard Smithb15fe3a2012-09-12 00:56:43 +00001361 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1362 QualType T = TransformType(E->getType());
1363 if (T.isNull())
1364 return ExprError();
1365 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1366 E->getExprLoc(), *Pack);
1367 }
1368
1369 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1370 } else {
1371 TransformedDecl = Found->get<Decl*>();
1372 }
1373
1374 // We have either an unexpanded pack or a specific expansion.
1375 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1376 E->getExprLoc());
1377}
1378
1379ExprResult
John McCall13481c52010-02-06 08:42:39 +00001380TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1381 NamedDecl *D = E->getDecl();
Richard Smithb15fe3a2012-09-12 00:56:43 +00001382
1383 // Handle references to non-type template parameters and non-type template
1384 // parameter packs.
John McCall13481c52010-02-06 08:42:39 +00001385 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1386 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1387 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor954de172009-10-31 17:21:17 +00001388
1389 // We have a non-type template parameter that isn't fully substituted;
1390 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001391 }
Mike Stump11289f42009-09-09 15:08:12 +00001392
Richard Smithb15fe3a2012-09-12 00:56:43 +00001393 // Handle references to function parameter packs.
1394 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1395 if (PD->isParameterPack())
1396 return TransformFunctionParmPackRefExpr(E, PD);
1397
John McCall47f29ea2009-12-08 09:21:05 +00001398 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001399}
1400
John McCalldadc5752010-08-24 06:29:42 +00001401ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001402 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001403 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1404 getDescribedFunctionTemplate() &&
1405 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001406 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1407 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1408 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001409}
1410
Richard Smith2e321552014-11-12 02:00:47 +00001411template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +00001412QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1413 FunctionProtoTypeLoc TL,
1414 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +00001415 unsigned ThisTypeQuals,
1416 Fn TransformExceptionSpec) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001417 // We need a local instantiation scope for this function prototype.
1418 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
Richard Smith2e321552014-11-12 02:00:47 +00001419 return inherited::TransformFunctionProtoType(
1420 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +00001421}
1422
John McCall58f10c32010-03-11 09:03:00 +00001423ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001424TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001425 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001426 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001427 bool ExpectParameterPack) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001428 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001429 NumExpansions, ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +00001430}
1431
Mike Stump11289f42009-09-09 15:08:12 +00001432QualType
John McCall550e0c22009-10-21 00:40:46 +00001433TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001434 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001435 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001436 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001437 // Replace the template type parameter with its corresponding
1438 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001439
1440 // If the corresponding template argument is NULL or doesn't exist, it's
1441 // because we are performing instantiation from explicitly-specified
1442 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001443 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001444 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1445 TemplateTypeParmTypeLoc NewTL
1446 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1447 NewTL.setNameLoc(TL.getNameLoc());
1448 return TL.getType();
1449 }
Mike Stump11289f42009-09-09 15:08:12 +00001450
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001451 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1452
1453 if (T->isParameterPack()) {
1454 assert(Arg.getKind() == TemplateArgument::Pack &&
1455 "Missing argument pack");
1456
1457 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001458 // We have the template argument pack, but we're not expanding the
1459 // enclosing pack expansion yet. Just save the template argument
1460 // pack for later substitution.
1461 QualType Result
1462 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1463 SubstTemplateTypeParmPackTypeLoc NewTL
1464 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1465 NewTL.setNameLoc(TL.getNameLoc());
1466 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001467 }
1468
Eli Friedman8917ad52013-07-19 19:40:38 +00001469 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001470 }
1471
1472 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001473 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001474
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001475 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001476
1477 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001478 QualType Result
1479 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1480 SubstTemplateTypeParmTypeLoc NewTL
1481 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1482 NewTL.setNameLoc(TL.getNameLoc());
1483 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001484 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001485
1486 // The template type parameter comes from an inner template (e.g.,
1487 // the template parameter list of a member template inside the
1488 // template we are instantiating). Create a new template type
1489 // parameter with the template "level" reduced by one.
Craig Topperc3ec1492014-05-26 06:22:03 +00001490 TemplateTypeParmDecl *NewTTPDecl = nullptr;
Chandler Carruth08836322011-05-01 00:51:33 +00001491 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1492 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1493 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1494
Richard Smithb4f96252017-02-21 06:30:38 +00001495 QualType Result = getSema().Context.getTemplateTypeParmType(
1496 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1497 T->isParameterPack(), NewTTPDecl);
John McCall550e0c22009-10-21 00:40:46 +00001498 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1499 NewTL.setNameLoc(TL.getNameLoc());
1500 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001501}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001502
Douglas Gregorada4b792011-01-14 02:55:32 +00001503QualType
1504TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1505 TypeLocBuilder &TLB,
1506 SubstTemplateTypeParmPackTypeLoc TL) {
1507 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1508 // We aren't expanding the parameter pack, so just return ourselves.
1509 SubstTemplateTypeParmPackTypeLoc NewTL
1510 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1511 NewTL.setNameLoc(TL.getNameLoc());
1512 return TL.getType();
1513 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001514
1515 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1516 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1517 QualType Result = Arg.getAsType();
1518
Douglas Gregorada4b792011-01-14 02:55:32 +00001519 Result = getSema().Context.getSubstTemplateTypeParmType(
1520 TL.getTypePtr()->getReplacedParameter(),
1521 Result);
1522 SubstTemplateTypeParmTypeLoc NewTL
1523 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1524 NewTL.setNameLoc(TL.getNameLoc());
1525 return Result;
1526}
1527
John McCall76d824f2009-08-25 22:02:44 +00001528/// \brief Perform substitution on the type T with a given set of template
1529/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001530///
1531/// This routine substitutes the given template arguments into the
1532/// type T and produces the instantiated type.
1533///
1534/// \param T the type into which the template arguments will be
1535/// substituted. If this type is not dependent, it will be returned
1536/// immediately.
1537///
James Dennett634962f2012-06-14 21:40:34 +00001538/// \param Args the template arguments that will be
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001539/// substituted for the top-level template parameters within T.
1540///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001541/// \param Loc the location in the source code where this substitution
1542/// is being performed. It will typically be the location of the
1543/// declarator (if we're instantiating the type of some declaration)
1544/// or the location of the type in the source code (if, e.g., we're
1545/// instantiating the type of a cast expression).
1546///
1547/// \param Entity the name of the entity associated with a declaration
1548/// being instantiated (if any). May be empty to indicate that there
1549/// is no such entity (if, e.g., this is a type that occurs as part of
1550/// a cast expression) or that the entity has no name (e.g., an
1551/// unnamed function parameter).
1552///
Richard Smithee579842017-01-30 20:39:26 +00001553/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1554/// acceptable as the top level type of the result.
1555///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001556/// \returns If the instantiation succeeds, the instantiated
1557/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001558TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001559 const MultiLevelTemplateArgumentList &Args,
1560 SourceLocation Loc,
Richard Smithee579842017-01-30 20:39:26 +00001561 DeclarationName Entity,
1562 bool AllowDeducedTST) {
Richard Smith696e3122017-02-23 01:43:54 +00001563 assert(!CodeSynthesisContexts.empty() &&
John McCall609459e2009-10-21 00:58:09 +00001564 "Cannot perform an instantiation without some context on the "
1565 "instantiation stack");
1566
Douglas Gregor678d76c2011-07-01 01:22:09 +00001567 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001568 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001569 return T;
1570
1571 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
Richard Smithee579842017-01-30 20:39:26 +00001572 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
1573 : Instantiator.TransformType(T);
John McCall609459e2009-10-21 00:58:09 +00001574}
1575
Douglas Gregor5499af42011-01-05 23:12:31 +00001576TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1577 const MultiLevelTemplateArgumentList &Args,
1578 SourceLocation Loc,
1579 DeclarationName Entity) {
Richard Smith696e3122017-02-23 01:43:54 +00001580 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001581 "Cannot perform an instantiation without some context on the "
1582 "instantiation stack");
1583
1584 if (TL.getType().isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001585 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001586
Douglas Gregor678d76c2011-07-01 01:22:09 +00001587 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001588 !TL.getType()->isVariablyModifiedType()) {
1589 // FIXME: Make a copy of the TypeLoc data here, so that we can
1590 // return a new TypeSourceInfo. Inefficient!
1591 TypeLocBuilder TLB;
1592 TLB.pushFullCopy(TL);
1593 return TLB.getTypeSourceInfo(Context, TL.getType());
1594 }
1595
1596 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1597 TypeLocBuilder TLB;
1598 TLB.reserve(TL.getFullDataSize());
1599 QualType Result = Instantiator.TransformType(TLB, TL);
1600 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001601 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001602
1603 return TLB.getTypeSourceInfo(Context, Result);
1604}
1605
John McCall609459e2009-10-21 00:58:09 +00001606/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001607QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001608 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001609 SourceLocation Loc, DeclarationName Entity) {
Richard Smith696e3122017-02-23 01:43:54 +00001610 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregor79cf6032009-03-10 20:44:00 +00001611 "Cannot perform an instantiation without some context on the "
1612 "instantiation stack");
1613
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001614 // If T is not a dependent type or a variably-modified type, there
1615 // is nothing to do.
Douglas Gregor678d76c2011-07-01 01:22:09 +00001616 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001617 return T;
1618
Douglas Gregord6ff3322009-08-04 16:50:30 +00001619 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1620 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001621}
Douglas Gregor463421d2009-03-03 04:44:36 +00001622
John McCallb29f78f2010-04-09 17:38:44 +00001623static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Nico Weberc0973372016-02-01 22:31:51 +00001624 if (T->getType()->isInstantiationDependentType() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00001625 T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001626 return true;
1627
Abramo Bagnara6d810632010-12-14 22:11:44 +00001628 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00001629 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCallb29f78f2010-04-09 17:38:44 +00001630 return false;
1631
David Blaikie6adc78e2013-02-18 22:06:02 +00001632 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Nico Weberc0973372016-02-01 22:31:51 +00001633 for (ParmVarDecl *P : FP.getParams()) {
Reid Klecknera09e44c2013-07-31 21:00:18 +00001634 // This must be synthesized from a typedef.
1635 if (!P) continue;
1636
Nico Weberc0973372016-02-01 22:31:51 +00001637 // If there are any parameters, a new TypeSourceInfo that refers to the
1638 // instantiated parameters must be built.
1639 return true;
John McCallb29f78f2010-04-09 17:38:44 +00001640 }
1641
1642 return false;
1643}
1644
1645/// A form of SubstType intended specifically for instantiating the
1646/// type of a FunctionDecl. Its purpose is solely to force the
Richard Smith2e321552014-11-12 02:00:47 +00001647/// instantiation of default-argument expressions and to avoid
1648/// instantiating an exception-specification.
John McCallb29f78f2010-04-09 17:38:44 +00001649TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1650 const MultiLevelTemplateArgumentList &Args,
1651 SourceLocation Loc,
Douglas Gregor3024f072012-04-16 07:05:22 +00001652 DeclarationName Entity,
1653 CXXRecordDecl *ThisContext,
1654 unsigned ThisTypeQuals) {
Richard Smith696e3122017-02-23 01:43:54 +00001655 assert(!CodeSynthesisContexts.empty() &&
John McCallb29f78f2010-04-09 17:38:44 +00001656 "Cannot perform an instantiation without some context on the "
1657 "instantiation stack");
Nico Weberc0973372016-02-01 22:31:51 +00001658
John McCallb29f78f2010-04-09 17:38:44 +00001659 if (!NeedsInstantiationAsFunctionType(T))
1660 return T;
1661
1662 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1663
1664 TypeLocBuilder TLB;
1665
1666 TypeLoc TL = T->getTypeLoc();
1667 TLB.reserve(TL.getFullDataSize());
1668
Douglas Gregor3024f072012-04-16 07:05:22 +00001669 QualType Result;
David Blaikie6adc78e2013-02-18 22:06:02 +00001670
Richard Smith2e321552014-11-12 02:00:47 +00001671 if (FunctionProtoTypeLoc Proto =
1672 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1673 // Instantiate the type, other than its exception specification. The
1674 // exception specification is instantiated in InitFunctionInstantiation
1675 // once we've built the FunctionDecl.
1676 // FIXME: Set the exception specification to EST_Uninstantiated here,
1677 // instead of rebuilding the function type again later.
1678 Result = Instantiator.TransformFunctionProtoType(
1679 TLB, Proto, ThisContext, ThisTypeQuals,
1680 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1681 bool &Changed) { return false; });
Douglas Gregor3024f072012-04-16 07:05:22 +00001682 } else {
1683 Result = Instantiator.TransformType(TLB, TL);
1684 }
John McCallb29f78f2010-04-09 17:38:44 +00001685 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001686 return nullptr;
John McCallb29f78f2010-04-09 17:38:44 +00001687
1688 return TLB.getTypeSourceInfo(Context, Result);
1689}
1690
Richard Smithcd198152017-06-07 21:46:22 +00001691bool Sema::SubstExceptionSpec(SourceLocation Loc,
1692 FunctionProtoType::ExceptionSpecInfo &ESI,
1693 SmallVectorImpl<QualType> &ExceptionStorage,
1694 const MultiLevelTemplateArgumentList &Args) {
1695 assert(ESI.Type != EST_Uninstantiated);
1696
1697 bool Changed = false;
1698 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
1699 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
1700 Changed);
1701}
1702
Richard Smith2e321552014-11-12 02:00:47 +00001703void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1704 const MultiLevelTemplateArgumentList &Args) {
1705 FunctionProtoType::ExceptionSpecInfo ESI =
1706 Proto->getExtProtoInfo().ExceptionSpec;
Richard Smith2e321552014-11-12 02:00:47 +00001707
1708 SmallVector<QualType, 4> ExceptionStorage;
Richard Smithcd198152017-06-07 21:46:22 +00001709 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getLocEnd(),
1710 ESI, ExceptionStorage, Args))
Richard Smith2e321552014-11-12 02:00:47 +00001711 // On error, recover by dropping the exception specification.
1712 ESI.Type = EST_None;
1713
1714 UpdateExceptionSpec(New, ESI);
1715}
1716
Douglas Gregor940bca72010-04-12 07:48:19 +00001717ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001718 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall8fb0d9d2011-05-01 22:35:37 +00001719 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001720 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001721 bool ExpectParameterPack) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001722 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Craig Topperc3ec1492014-05-26 06:22:03 +00001723 TypeSourceInfo *NewDI = nullptr;
1724
Douglas Gregor5499af42011-01-05 23:12:31 +00001725 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00001726 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1727
Douglas Gregor5499af42011-01-05 23:12:31 +00001728 // We have a function parameter pack. Substitute into the pattern of the
1729 // expansion.
1730 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1731 OldParm->getLocation(), OldParm->getDeclName());
1732 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001733 return nullptr;
1734
Douglas Gregor5499af42011-01-05 23:12:31 +00001735 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1736 // We still have unexpanded parameter packs, which means that
1737 // our function parameter is still a function parameter pack.
1738 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001739 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001740 NumExpansions);
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001741 } else if (ExpectParameterPack) {
1742 // We expected to get a parameter pack but didn't (because the type
1743 // itself is not a pack expansion type), so complain. This can occur when
1744 // the substitution goes through an alias template that "loses" the
1745 // pack expansion.
1746 Diag(OldParm->getLocation(),
1747 diag::err_function_parameter_pack_without_parameter_packs)
1748 << NewDI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001749 return nullptr;
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001750 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001751 } else {
1752 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1753 OldParm->getDeclName());
1754 }
1755
Douglas Gregor940bca72010-04-12 07:48:19 +00001756 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001757 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001758
1759 if (NewDI->getType()->isVoidType()) {
1760 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
Craig Topperc3ec1492014-05-26 06:22:03 +00001761 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001762 }
1763
1764 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001765 OldParm->getInnerLocStart(),
Douglas Gregor940bca72010-04-12 07:48:19 +00001766 OldParm->getLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001767 OldParm->getIdentifier(),
1768 NewDI->getType(), NewDI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001769 OldParm->getStorageClass());
Douglas Gregor940bca72010-04-12 07:48:19 +00001770 if (!NewParm)
Craig Topperc3ec1492014-05-26 06:22:03 +00001771 return nullptr;
1772
Douglas Gregor940bca72010-04-12 07:48:19 +00001773 // Mark the (new) default argument as uninstantiated (if any).
1774 if (OldParm->hasUninstantiatedDefaultArg()) {
1775 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1776 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001777 } else if (OldParm->hasUnparsedDefaultArg()) {
1778 NewParm->setUnparsedDefaultArg();
1779 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001780 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1781 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
Serge Pavlov73c6a242015-08-23 10:22:28 +00001782 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1783 // Instantiate default arguments for methods of local classes (DR1484)
1784 // and non-defining declarations.
1785 Sema::ContextRAII SavedContext(*this, OwningFunc);
Akira Hatanakad644e022016-12-16 03:19:41 +00001786 LocalInstantiationScope Local(*this, true);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001787 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
John McCalldc40b612015-12-11 01:56:36 +00001788 if (NewArg.isUsable()) {
1789 // It would be nice if we still had this.
1790 SourceLocation EqualLoc = NewArg.get()->getLocStart();
1791 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1792 }
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001793 } else {
1794 // FIXME: if we non-lazily instantiated non-dependent default args for
1795 // non-dependent parameter types we could remove a bunch of duplicate
1796 // conversion warnings for such arguments.
1797 NewParm->setUninstantiatedDefaultArg(Arg);
1798 }
1799 }
Douglas Gregor940bca72010-04-12 07:48:19 +00001800
1801 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001802
Douglas Gregorf3010112011-01-07 16:43:16 +00001803 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smith928be492012-01-25 02:14:59 +00001804 // Add the new parameter to the instantiated parameter pack.
Douglas Gregorf3010112011-01-07 16:43:16 +00001805 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1806 } else {
1807 // Introduce an Old -> New mapping
Douglas Gregor5499af42011-01-05 23:12:31 +00001808 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001809 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001810
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001811 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1812 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001813 NewParm->setDeclContext(CurContext);
John McCall8fb0d9d2011-05-01 22:35:37 +00001814
1815 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1816 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rosea0a86be2013-03-08 22:25:36 +00001817
1818 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1819
Douglas Gregor940bca72010-04-12 07:48:19 +00001820 return NewParm;
1821}
1822
Douglas Gregordd472162011-01-07 00:20:55 +00001823/// \brief Substitute the given template arguments into the given set of
1824/// parameters, producing the set of parameter types that would be generated
1825/// from such a substitution.
David Majnemer59f77922016-06-24 04:05:48 +00001826bool Sema::SubstParmTypes(
1827 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1828 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1829 const MultiLevelTemplateArgumentList &TemplateArgs,
1830 SmallVectorImpl<QualType> &ParamTypes,
1831 SmallVectorImpl<ParmVarDecl *> *OutParams,
1832 ExtParameterInfoBuilder &ParamInfos) {
Richard Smith696e3122017-02-23 01:43:54 +00001833 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregordd472162011-01-07 00:20:55 +00001834 "Cannot perform an instantiation without some context on the "
1835 "instantiation stack");
1836
1837 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1838 DeclarationName());
David Majnemer59f77922016-06-24 04:05:48 +00001839 return Instantiator.TransformFunctionTypeParams(
1840 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
Douglas Gregordd472162011-01-07 00:20:55 +00001841}
1842
John McCall76d824f2009-08-25 22:02:44 +00001843/// \brief Perform substitution on the base class specifiers of the
1844/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001845///
1846/// Produces a diagnostic and returns true on error, returns false and
1847/// attaches the instantiated base classes to the class template
1848/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001849bool
John McCall76d824f2009-08-25 22:02:44 +00001850Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1851 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001852 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001853 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001854 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Richard Trieub5841332015-04-15 01:21:42 +00001855 for (const auto &Base : Pattern->bases()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001856 if (!Base.getType()->isDependentType()) {
1857 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay76d0b462013-06-21 18:58:32 +00001858 if (RD->isInvalidDecl())
1859 Instantiation->setInvalidDecl();
1860 }
Aaron Ballman574705e2014-03-13 15:41:46 +00001861 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001862 continue;
1863 }
1864
Douglas Gregor752a5952011-01-03 22:36:02 +00001865 SourceLocation EllipsisLoc;
Douglas Gregorc52264e2011-03-02 02:04:06 +00001866 TypeSourceInfo *BaseTypeLoc;
Aaron Ballman574705e2014-03-13 15:41:46 +00001867 if (Base.isPackExpansion()) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001868 // This is a pack expansion. See whether we should expand it now, or
1869 // wait until later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001870 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Aaron Ballman574705e2014-03-13 15:41:46 +00001871 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001872 Unexpanded);
1873 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001874 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001875 Optional<unsigned> NumExpansions;
Aaron Ballman574705e2014-03-13 15:41:46 +00001876 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1877 Base.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001878 Unexpanded,
Douglas Gregor752a5952011-01-03 22:36:02 +00001879 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001880 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001881 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001882 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001883 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001884 }
1885
1886 // If we should expand this pack expansion now, do so.
1887 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001888 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001889 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1890
Aaron Ballman574705e2014-03-13 15:41:46 +00001891 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001892 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001893 Base.getSourceRange().getBegin(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001894 DeclarationName());
1895 if (!BaseTypeLoc) {
1896 Invalid = true;
1897 continue;
1898 }
1899
1900 if (CXXBaseSpecifier *InstantiatedBase
1901 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001902 Base.getSourceRange(),
1903 Base.isVirtual(),
1904 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001905 BaseTypeLoc,
1906 SourceLocation()))
1907 InstantiatedBases.push_back(InstantiatedBase);
1908 else
1909 Invalid = true;
1910 }
1911
1912 continue;
1913 }
1914
1915 // The resulting base specifier will (still) be a pack expansion.
Aaron Ballman574705e2014-03-13 15:41:46 +00001916 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregorc52264e2011-03-02 02:04:06 +00001917 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Aaron Ballman574705e2014-03-13 15:41:46 +00001918 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001919 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001920 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001921 DeclarationName());
1922 } else {
Aaron Ballman574705e2014-03-13 15:41:46 +00001923 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001924 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001925 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001926 DeclarationName());
Douglas Gregor752a5952011-01-03 22:36:02 +00001927 }
1928
Nick Lewycky19b9f952010-07-26 16:56:01 +00001929 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001930 Invalid = true;
1931 continue;
1932 }
1933
1934 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001935 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001936 Base.getSourceRange(),
1937 Base.isVirtual(),
1938 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001939 BaseTypeLoc,
1940 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001941 InstantiatedBases.push_back(InstantiatedBase);
1942 else
1943 Invalid = true;
1944 }
1945
Craig Topperaa700cb2015-12-27 21:55:19 +00001946 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
Douglas Gregor463421d2009-03-03 04:44:36 +00001947 Invalid = true;
1948
1949 return Invalid;
1950}
1951
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001952// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00001953namespace clang {
1954 namespace sema {
1955 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1956 const MultiLevelTemplateArgumentList &TemplateArgs);
Erich Keanea32910d2017-03-23 18:51:54 +00001957 Attr *instantiateTemplateAttributeForDecl(
1958 const Attr *At, ASTContext &C, Sema &S,
1959 const MultiLevelTemplateArgumentList &TemplateArgs);
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00001960 }
1961}
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001962
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001963/// \brief Instantiate the definition of a class from a given pattern.
1964///
1965/// \param PointOfInstantiation The point of instantiation within the
1966/// source code.
1967///
1968/// \param Instantiation is the declaration whose definition is being
1969/// instantiated. This will be either a class template specialization
1970/// or a member class of a class template specialization.
1971///
1972/// \param Pattern is the pattern from which the instantiation
1973/// occurs. This will be either the declaration of a class template or
1974/// the declaration of a member class of a class template.
1975///
1976/// \param TemplateArgs The template arguments to be substituted into
1977/// the pattern.
1978///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001979/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001980///
1981/// \param Complain whether to complain if the class cannot be instantiated due
1982/// to the lack of a definition.
1983///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001984/// \returns true if an error occurred, false otherwise.
1985bool
1986Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1987 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001988 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001989 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001990 bool Complain) {
Mike Stump11289f42009-09-09 15:08:12 +00001991 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001992 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Vassil Vassilevb21ee082016-08-18 22:01:25 +00001993 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00001994 Instantiation->getInstantiatedFromMemberClass(),
1995 Pattern, PatternDef, TSK, Complain))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001996 return true;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001997 Pattern = PatternDef;
1998
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001999 // \brief Record the point of instantiation.
2000 if (MemberSpecializationInfo *MSInfo
2001 = Instantiation->getMemberSpecializationInfo()) {
2002 MSInfo->setTemplateSpecializationKind(TSK);
2003 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregoref6ab412009-10-27 06:26:26 +00002004 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weber3ffc4c92011-12-20 20:32:49 +00002005 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregoref6ab412009-10-27 06:26:26 +00002006 Spec->setTemplateSpecializationKind(TSK);
2007 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00002008 }
Richard Smitha1087602014-03-10 00:04:29 +00002009
Douglas Gregorf3430ae2009-03-25 21:23:52 +00002010 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002011 if (Inst.isInvalid())
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002012 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002013 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
Richard Smithe19b95d2016-05-26 20:23:13 +00002014 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2015 "instantiating class definition");
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002016
2017 // Enter the scope of this instantiation. We don't use
2018 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00002019 ContextRAII SavedContext(*this, Instantiation);
Faisal Valid143a0c2017-04-01 21:30:49 +00002020 EnterExpressionEvaluationContext EvalContext(
2021 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002022
Douglas Gregor51121572010-03-24 01:33:17 +00002023 // If this is an instantiation of a local class, merge this local
2024 // instantiation scope with the enclosing scope. Otherwise, every
2025 // instantiation of a class has its own local instantiation scope.
2026 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00002027 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00002028
Volodymyr Sapsai4fbaa622017-09-21 19:54:12 +00002029 // Some class state isn't processed immediately but delayed till class
2030 // instantiation completes. We may not be ready to handle any delayed state
2031 // already on the stack as it might correspond to a different class, so save
2032 // it now and put it back later.
2033 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
Reid Kleckner5b640342016-02-26 19:51:02 +00002034
John McCall6602bb12010-08-01 02:01:53 +00002035 // Pull attributes from the pattern onto the instantiation.
2036 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2037
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002038 // Start the definition of this instantiation.
2039 Instantiation->startDefinition();
Richard Smitha1087602014-03-10 00:04:29 +00002040
2041 // The instantiation is visible here, even if it was first declared in an
2042 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00002043 Instantiation->setVisibleDespiteOwningModule();
Richard Smitha1087602014-03-10 00:04:29 +00002044
2045 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregore9029562010-05-06 00:28:52 +00002046 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002047
John McCall76d824f2009-08-25 22:02:44 +00002048 // Do substitution on the base class specifiers.
2049 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002050 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002051
Douglas Gregor869853e2010-11-10 19:44:59 +00002052 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002053 SmallVector<Decl*, 4> Fields;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002054 // Delay instantiation of late parsed attributes.
2055 LateInstantiatedAttrVec LateAttrs;
2056 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2057
Aaron Ballman629afae2014-03-07 19:56:05 +00002058 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002059 // Don't instantiate members not belonging in this semantic context.
2060 // e.g. for:
2061 // @code
2062 // template <int i> class A {
2063 // class B *g;
2064 // };
2065 // @endcode
2066 // 'class B' has the template as lexical context but semantically it is
2067 // introduced in namespace scope.
Aaron Ballman629afae2014-03-07 19:56:05 +00002068 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002069 continue;
2070
Aaron Ballman629afae2014-03-07 19:56:05 +00002071 if (Member->isInvalidDecl()) {
Richard Smithded9c2e2012-07-11 22:37:56 +00002072 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002073 continue;
2074 }
2075
Aaron Ballman629afae2014-03-07 19:56:05 +00002076 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002077 if (NewMember) {
Richard Smith938f40b2011-06-11 17:19:42 +00002078 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCall48871652010-08-21 09:40:31 +00002079 Fields.push_back(Field);
Richard Smith7d137e32012-03-23 03:33:32 +00002080 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2081 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2082 // specialization causes the implicit instantiation of the definitions
2083 // of unscoped member enumerations.
2084 // Record a point of instantiation for this implicit instantiation.
Richard Smithb66d7772012-03-23 23:09:08 +00002085 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2086 Enum->isCompleteDefinition()) {
Richard Smith7d137e32012-03-23 03:33:32 +00002087 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2088 assert(MSInfo && "no spec info for member enum specialization");
2089 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2090 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2091 }
Richard Smithded9c2e2012-07-11 22:37:56 +00002092 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2093 if (SA->isFailed()) {
2094 // A static_assert failed. Bail out; instantiating this
2095 // class is probably not meaningful.
2096 Instantiation->setInvalidDecl();
2097 break;
2098 }
Richard Smith7d137e32012-03-23 03:33:32 +00002099 }
2100
2101 if (NewMember->isInvalidDecl())
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002102 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002103 } else {
2104 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002105 // instantiations was a semantic disaster, and we'll want to mark the
2106 // declaration invalid.
2107 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002108 }
2109 }
2110
2111 // Finish checking fields.
Craig Topperc3ec1492014-05-26 06:22:03 +00002112 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2113 SourceLocation(), SourceLocation(), nullptr);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002114 CheckCompletedCXXClass(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002115
Reid Kleckner93f661a2015-03-17 21:51:43 +00002116 // Default arguments are parsed, if not instantiated. We can go instantiate
2117 // default arg exprs for default constructors if necessary now.
Hans Wennborg99000c22015-08-15 01:18:16 +00002118 ActOnFinishCXXNonNestedClass(Instantiation);
Reid Kleckner93f661a2015-03-17 21:51:43 +00002119
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002120 // Instantiate late parsed attributes, and attach them to their decls.
2121 // See Sema::InstantiateAttrs
2122 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2123 E = LateAttrs.end(); I != E; ++I) {
2124 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2125 CurrentInstantiationScope = I->Scope;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002126
2127 // Allow 'this' within late-parsed attributes.
2128 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2129 CXXRecordDecl *ThisContext =
2130 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2131 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2132 ND && ND->isCXXInstanceMember());
2133
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002134 Attr *NewAttr =
2135 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2136 I->NewDecl->addAttr(NewAttr);
2137 LocalInstantiationScope::deleteScopes(I->Scope,
2138 Instantiator.getStartingScope());
2139 }
2140 Instantiator.disableLateAttributeInstantiation();
2141 LateAttrs.clear();
2142
Richard Smithd3b5c9082012-07-27 04:22:15 +00002143 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002144
Richard Smitha1087602014-03-10 00:04:29 +00002145 // FIXME: We should do something similar for explicit instantiations so they
2146 // end up in the right module.
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002147 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidise3789482012-02-11 01:59:57 +00002148 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002149 Instantiation->setLocStart(Pattern->getInnerLocStart());
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00002150 Instantiation->setBraceRange(Pattern->getBraceRange());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002151 }
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002152
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002153 if (!Instantiation->isInvalidDecl()) {
John McCalla0a96892012-08-10 03:15:35 +00002154 // Perform any dependent diagnostics from the pattern.
2155 PerformDependentDiagnostics(Pattern, TemplateArgs);
2156
Douglas Gregor869853e2010-11-10 19:44:59 +00002157 // Instantiate any out-of-line class template partial
2158 // specializations now.
Richard Smith10b55fc2013-09-26 03:49:48 +00002159 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregor869853e2010-11-10 19:44:59 +00002160 P = Instantiator.delayed_partial_spec_begin(),
2161 PEnd = Instantiator.delayed_partial_spec_end();
2162 P != PEnd; ++P) {
2163 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smith10b55fc2013-09-26 03:49:48 +00002164 P->first, P->second)) {
2165 Instantiation->setInvalidDecl();
2166 break;
2167 }
2168 }
2169
2170 // Instantiate any out-of-line variable template partial
2171 // specializations now.
2172 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2173 P = Instantiator.delayed_var_partial_spec_begin(),
2174 PEnd = Instantiator.delayed_var_partial_spec_end();
2175 P != PEnd; ++P) {
2176 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2177 P->first, P->second)) {
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002178 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002179 break;
2180 }
2181 }
2182 }
2183
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002184 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00002185 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002186
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002187 if (!Instantiation->isInvalidDecl()) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00002188 Consumer.HandleTagDeclDefinition(Instantiation);
2189
Douglas Gregor88d292c2010-05-13 16:44:06 +00002190 // Always emit the vtable for an explicit instantiation definition
2191 // of a polymorphic class template specialization.
2192 if (TSK == TSK_ExplicitInstantiationDefinition)
2193 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2194 }
2195
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002196 return Instantiation->isInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002197}
2198
Richard Smith4b38ded2012-03-14 23:13:10 +00002199/// \brief Instantiate the definition of an enum from a given pattern.
2200///
2201/// \param PointOfInstantiation The point of instantiation within the
2202/// source code.
2203/// \param Instantiation is the declaration whose definition is being
2204/// instantiated. This will be a member enumeration of a class
2205/// temploid specialization, or a local enumeration within a
2206/// function temploid specialization.
2207/// \param Pattern The templated declaration from which the instantiation
2208/// occurs.
2209/// \param TemplateArgs The template arguments to be substituted into
2210/// the pattern.
2211/// \param TSK The kind of implicit or explicit instantiation to perform.
2212///
2213/// \return \c true if an error occurred, \c false otherwise.
2214bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2215 EnumDecl *Instantiation, EnumDecl *Pattern,
2216 const MultiLevelTemplateArgumentList &TemplateArgs,
2217 TemplateSpecializationKind TSK) {
2218 EnumDecl *PatternDef = Pattern->getDefinition();
Vassil Vassilevb21ee082016-08-18 22:01:25 +00002219 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00002220 Instantiation->getInstantiatedFromMemberEnum(),
2221 Pattern, PatternDef, TSK,/*Complain*/true))
2222 return true;
2223 Pattern = PatternDef;
2224
2225 // Record the point of instantiation.
2226 if (MemberSpecializationInfo *MSInfo
2227 = Instantiation->getMemberSpecializationInfo()) {
2228 MSInfo->setTemplateSpecializationKind(TSK);
2229 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2230 }
2231
2232 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002233 if (Inst.isInvalid())
Richard Smith4b38ded2012-03-14 23:13:10 +00002234 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002235 if (Inst.isAlreadyInstantiating())
2236 return false;
Richard Smithe19b95d2016-05-26 20:23:13 +00002237 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2238 "instantiating enum definition");
Richard Smith4b38ded2012-03-14 23:13:10 +00002239
Richard Smitha1087602014-03-10 00:04:29 +00002240 // The instantiation is visible here, even if it was first declared in an
2241 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00002242 Instantiation->setVisibleDespiteOwningModule();
Richard Smitha1087602014-03-10 00:04:29 +00002243
Richard Smith4b38ded2012-03-14 23:13:10 +00002244 // Enter the scope of this instantiation. We don't use
2245 // PushDeclContext because we don't have a scope.
2246 ContextRAII SavedContext(*this, Instantiation);
Faisal Valid143a0c2017-04-01 21:30:49 +00002247 EnterExpressionEvaluationContext EvalContext(
2248 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith4b38ded2012-03-14 23:13:10 +00002249
2250 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2251
2252 // Pull attributes from the pattern onto the instantiation.
2253 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2254
2255 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2256 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2257
2258 // Exit the scope of this instantiation.
2259 SavedContext.pop();
2260
2261 return Instantiation->isInvalidDecl();
2262}
2263
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002264
2265/// \brief Instantiate the definition of a field from the given pattern.
2266///
2267/// \param PointOfInstantiation The point of instantiation within the
2268/// source code.
2269/// \param Instantiation is the declaration whose definition is being
2270/// instantiated. This will be a class of a class temploid
2271/// specialization, or a local enumeration within a function temploid
2272/// specialization.
2273/// \param Pattern The templated declaration from which the instantiation
2274/// occurs.
2275/// \param TemplateArgs The template arguments to be substituted into
2276/// the pattern.
2277///
2278/// \return \c true if an error occurred, \c false otherwise.
2279bool Sema::InstantiateInClassInitializer(
2280 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2281 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2282 // If there is no initializer, we don't need to do anything.
2283 if (!Pattern->hasInClassInitializer())
2284 return false;
2285
2286 assert(Instantiation->getInClassInitStyle() ==
2287 Pattern->getInClassInitStyle() &&
2288 "pattern and instantiation disagree about init style");
2289
2290 // Error out if we haven't parsed the initializer of the pattern yet because
2291 // we are waiting for the closing brace of the outer class.
2292 Expr *OldInit = Pattern->getInClassInitializer();
2293 if (!OldInit) {
2294 RecordDecl *PatternRD = Pattern->getParent();
2295 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
Richard Smith8dbc6b22016-11-22 22:55:12 +00002296 Diag(PointOfInstantiation,
2297 diag::err_in_class_initializer_not_yet_parsed)
2298 << OutermostClass << Pattern;
2299 Diag(Pattern->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002300 Instantiation->setInvalidDecl();
2301 return true;
2302 }
2303
2304 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2305 if (Inst.isInvalid())
2306 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002307 if (Inst.isAlreadyInstantiating()) {
2308 // Error out if we hit an instantiation cycle for this initializer.
2309 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2310 << Instantiation;
2311 return true;
2312 }
Richard Smithe19b95d2016-05-26 20:23:13 +00002313 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2314 "instantiating default member init");
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002315
2316 // Enter the scope of this instantiation. We don't use PushDeclContext because
2317 // we don't have a scope.
2318 ContextRAII SavedContext(*this, Instantiation->getParent());
Faisal Valid143a0c2017-04-01 21:30:49 +00002319 EnterExpressionEvaluationContext EvalContext(
2320 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002321
Serge Pavlov907233f2015-04-28 17:58:47 +00002322 LocalInstantiationScope Scope(*this, true);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002323
2324 // Instantiate the initializer.
2325 ActOnStartCXXInClassMemberInitializer();
2326 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2327
2328 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2329 /*CXXDirectInit=*/false);
2330 Expr *Init = NewInit.get();
2331 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2332 ActOnFinishCXXInClassMemberInitializer(
2333 Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2334
Richard Smith4b054b22016-08-24 21:25:37 +00002335 if (auto *L = getASTMutationListener())
2336 L->DefaultMemberInitializerInstantiated(Instantiation);
2337
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002338 // Return true if the in-class initializer is still missing.
2339 return !Instantiation->getInClassInitializer();
2340}
2341
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002342namespace {
2343 /// \brief A partial specialization whose template arguments have matched
2344 /// a given template-id.
2345 struct PartialSpecMatchResult {
2346 ClassTemplatePartialSpecializationDecl *Partial;
2347 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002348 };
2349}
2350
Richard Smithe6d4b772017-06-07 02:42:27 +00002351bool Sema::usesPartialOrExplicitSpecialization(
2352 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
2353 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
2354 TSK_ExplicitSpecialization)
2355 return true;
2356
2357 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2358 ClassTemplateSpec->getSpecializedTemplate()
2359 ->getPartialSpecializations(PartialSpecs);
2360 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2361 TemplateDeductionInfo Info(Loc);
2362 if (!DeduceTemplateArguments(PartialSpecs[I],
2363 ClassTemplateSpec->getTemplateArgs(), Info))
2364 return true;
2365 }
2366
2367 return false;
2368}
2369
Richard Smith32b43762017-01-08 22:45:21 +00002370/// Get the instantiation pattern to use to instantiate the definition of a
2371/// given ClassTemplateSpecializationDecl (either the pattern of the primary
2372/// template or of a partial specialization).
2373static CXXRecordDecl *
2374getPatternForClassTemplateSpecialization(
2375 Sema &S, SourceLocation PointOfInstantiation,
Larisse Voufo72caf2b2013-08-22 00:59:14 +00002376 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2377 TemplateSpecializationKind TSK, bool Complain) {
Richard Smith32b43762017-01-08 22:45:21 +00002378 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2379 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
2380 return nullptr;
2381
Douglas Gregor463421d2009-03-03 04:44:36 +00002382 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +00002383 CXXRecordDecl *Pattern = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00002384
Douglas Gregor170bc422009-06-12 22:31:52 +00002385 // C++ [temp.class.spec.match]p1:
2386 // When a class template is used in a context that requires an
2387 // instantiation of the class, it is necessary to determine
2388 // whether the instantiation is to be generated using the primary
2389 // template or one of the partial specializations. This is done by
2390 // matching the template arguments of the class template
2391 // specialization with the template argument lists of the partial
2392 // specializations.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002393 typedef PartialSpecMatchResult MatchResult;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002394 SmallVector<MatchResult, 4> Matched;
2395 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor407e9612010-04-30 05:56:50 +00002396 Template->getPartialSpecializations(PartialSpecs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00002397 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
Douglas Gregor407e9612010-04-30 05:56:50 +00002398 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2399 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo98b20f12013-07-19 23:00:19 +00002400 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Richard Smith32b43762017-01-08 22:45:21 +00002401 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
2402 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00002403 // Store the failed-deduction information for use in diagnostics, later.
2404 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00002405 FailedCandidates.addCandidate().set(
2406 DeclAccessPair::make(Template, AS_public), Partial,
Richard Smith32b43762017-01-08 22:45:21 +00002407 MakeDeductionFailureInfo(S.Context, Result, Info));
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002408 (void)Result;
2409 } else {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002410 Matched.push_back(PartialSpecMatchResult());
2411 Matched.back().Partial = Partial;
2412 Matched.back().Args = Info.take();
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002413 }
Douglas Gregor2373c592009-05-31 09:31:02 +00002414 }
2415
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002416 // If we're dealing with a member template where the template parameters
2417 // have been instantiated, this provides the original template parameters
2418 // from which the member template's parameters were instantiated.
Alp Toker965f8822013-11-27 05:22:15 +00002419
Douglas Gregor21610382009-10-29 00:04:11 +00002420 if (Matched.size() >= 1) {
Craig Topper2341c0d2013-07-04 03:08:24 +00002421 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregor21610382009-10-29 00:04:11 +00002422 if (Matched.size() == 1) {
2423 // -- If exactly one matching specialization is found, the
2424 // instantiation is generated from that specialization.
2425 // We don't need to do anything for this.
2426 } else {
2427 // -- If more than one matching specialization is found, the
2428 // partial order rules (14.5.4.2) are used to determine
2429 // whether one of the specializations is more specialized
2430 // than the others. If none of the specializations is more
2431 // specialized than all of the other matching
2432 // specializations, then the use of the class template is
2433 // ambiguous and the program is ill-formed.
Craig Topper2341c0d2013-07-04 03:08:24 +00002434 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2435 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002436 P != PEnd; ++P) {
Richard Smith32b43762017-01-08 22:45:21 +00002437 if (S.getMoreSpecializedPartialSpecialization(
2438 P->Partial, Best->Partial, PointOfInstantiation) == P->Partial)
Douglas Gregor21610382009-10-29 00:04:11 +00002439 Best = P;
Douglas Gregorbe999392009-09-15 16:23:51 +00002440 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002441
Douglas Gregor21610382009-10-29 00:04:11 +00002442 // Determine if the best partial specialization is more specialized than
2443 // the others.
2444 bool Ambiguous = false;
Craig Topper2341c0d2013-07-04 03:08:24 +00002445 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2446 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002447 P != PEnd; ++P) {
2448 if (P != Best &&
Richard Smith32b43762017-01-08 22:45:21 +00002449 S.getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2450 PointOfInstantiation) !=
2451 Best->Partial) {
Douglas Gregor21610382009-10-29 00:04:11 +00002452 Ambiguous = true;
2453 break;
2454 }
2455 }
2456
2457 if (Ambiguous) {
2458 // Partial ordering did not produce a clear winner. Complain.
Richard Smith32b43762017-01-08 22:45:21 +00002459 Inst.Clear();
Douglas Gregor21610382009-10-29 00:04:11 +00002460 ClassTemplateSpec->setInvalidDecl();
Richard Smith32b43762017-01-08 22:45:21 +00002461 S.Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
Douglas Gregor21610382009-10-29 00:04:11 +00002462 << ClassTemplateSpec;
2463
2464 // Print the matching partial specializations.
Craig Topper2341c0d2013-07-04 03:08:24 +00002465 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2466 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002467 P != PEnd; ++P)
Richard Smith32b43762017-01-08 22:45:21 +00002468 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2469 << S.getTemplateArgumentBindingsText(
2470 P->Partial->getTemplateParameters(), *P->Args);
Douglas Gregor01afeef2009-08-28 20:31:08 +00002471
Richard Smith32b43762017-01-08 22:45:21 +00002472 return nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00002473 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002474 }
2475
2476 // Instantiate using the best class template partial specialization.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002477 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregor21610382009-10-29 00:04:11 +00002478 while (OrigPartialSpec->getInstantiatedFromMember()) {
2479 // If we've found an explicit specialization of this class template,
2480 // stop here and use that as the pattern.
2481 if (OrigPartialSpec->isMemberSpecialization())
2482 break;
2483
2484 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2485 }
2486
2487 Pattern = OrigPartialSpec;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002488 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor170bc422009-06-12 22:31:52 +00002489 } else {
2490 // -- If no matches are found, the instantiation is generated
2491 // from the primary template.
Douglas Gregor01afeef2009-08-28 20:31:08 +00002492 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorcf915552009-10-13 16:30:37 +00002493 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2494 // If we've found an explicit specialization of this class template,
2495 // stop here and use that as the pattern.
2496 if (OrigTemplate->isMemberSpecialization())
2497 break;
2498
Douglas Gregor01afeef2009-08-28 20:31:08 +00002499 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00002500 }
2501
Douglas Gregor01afeef2009-08-28 20:31:08 +00002502 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00002503 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002504
Richard Smith32b43762017-01-08 22:45:21 +00002505 return Pattern;
2506}
Mike Stump11289f42009-09-09 15:08:12 +00002507
Richard Smith32b43762017-01-08 22:45:21 +00002508bool Sema::InstantiateClassTemplateSpecialization(
2509 SourceLocation PointOfInstantiation,
2510 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2511 TemplateSpecializationKind TSK, bool Complain) {
2512 // Perform the actual instantiation on the canonical declaration.
2513 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2514 ClassTemplateSpec->getCanonicalDecl());
2515 if (ClassTemplateSpec->isInvalidDecl())
2516 return true;
2517
2518 CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization(
2519 *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
2520 if (!Pattern)
2521 return true;
2522
2523 return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
2524 getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
2525 Complain);
Douglas Gregor463421d2009-03-03 04:44:36 +00002526}
Douglas Gregor90a1a652009-03-19 17:26:29 +00002527
John McCall76d824f2009-08-25 22:02:44 +00002528/// \brief Instantiates the definitions of all of the member
2529/// of the given class, which is an instantiation of a class template
2530/// or a member class of a template.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002531void
2532Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002533 CXXRecordDecl *Instantiation,
2534 const MultiLevelTemplateArgumentList &TemplateArgs,
2535 TemplateSpecializationKind TSK) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00002536 // FIXME: We need to notify the ASTMutationListener that we did all of these
2537 // things, in case we have an explicit instantiation definition in a PCM, a
2538 // module, or preamble, and the declaration is in an imported AST.
David Majnemer192d1792013-11-27 08:20:38 +00002539 assert(
2540 (TSK == TSK_ExplicitInstantiationDefinition ||
2541 TSK == TSK_ExplicitInstantiationDeclaration ||
2542 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2543 "Unexpected template specialization kind!");
Aaron Ballman629afae2014-03-07 19:56:05 +00002544 for (auto *D : Instantiation->decls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002545 bool SuppressNew = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002546 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002547 if (FunctionDecl *Pattern
2548 = Function->getInstantiatedFromMemberFunction()) {
2549 MemberSpecializationInfo *MSInfo
2550 = Function->getMemberSpecializationInfo();
2551 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002552 if (MSInfo->getTemplateSpecializationKind()
2553 == TSK_ExplicitSpecialization)
2554 continue;
2555
Douglas Gregor1d957a32009-10-27 18:42:08 +00002556 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2557 Function,
2558 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002559 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002560 SuppressNew) ||
2561 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002562 continue;
Richard Smitheb36ddf2014-04-24 22:45:46 +00002563
2564 // C++11 [temp.explicit]p8:
2565 // An explicit instantiation definition that names a class template
2566 // specialization explicitly instantiates the class template
2567 // specialization and is only an explicit instantiation definition
2568 // of members whose definition is visible at the point of
2569 // instantiation.
2570 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002571 continue;
2572
Richard Smitheb36ddf2014-04-24 22:45:46 +00002573 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2574
2575 if (Function->isDefined()) {
2576 // Let the ASTConsumer know that this function has been explicitly
2577 // instantiated now, and its linkage might have changed.
2578 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2579 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002580 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Richard Smitheb36ddf2014-04-24 22:45:46 +00002581 } else if (TSK == TSK_ImplicitInstantiation) {
2582 PendingLocalImplicitInstantiations.push_back(
2583 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor1d957a32009-10-27 18:42:08 +00002584 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002585 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002586 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002587 if (isa<VarTemplateSpecializationDecl>(Var))
2588 continue;
2589
Douglas Gregor86d142a2009-10-08 07:24:58 +00002590 if (Var->isStaticDataMember()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002591 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2592 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002593 if (MSInfo->getTemplateSpecializationKind()
2594 == TSK_ExplicitSpecialization)
2595 continue;
2596
Douglas Gregor1d957a32009-10-27 18:42:08 +00002597 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2598 Var,
2599 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002600 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002601 SuppressNew) ||
2602 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002603 continue;
2604
Douglas Gregor1d957a32009-10-27 18:42:08 +00002605 if (TSK == TSK_ExplicitInstantiationDefinition) {
2606 // C++0x [temp.explicit]p8:
2607 // An explicit instantiation definition that names a class template
2608 // specialization explicitly instantiates the class template
2609 // specialization and is only an explicit instantiation definition
2610 // of members whose definition is visible at the point of
2611 // instantiation.
Richard Smith62f19e72016-06-25 00:15:56 +00002612 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002613 continue;
2614
2615 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor86d142a2009-10-08 07:24:58 +00002616 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00002617 } else {
2618 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2619 }
2620 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002621 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Douglas Gregor1da22252010-04-18 18:11:38 +00002622 // Always skip the injected-class-name, along with any
2623 // redeclarations of nested classes, since both would cause us
2624 // to try to instantiate the members of a class twice.
Richard Smith069ecf62014-11-20 22:56:34 +00002625 // Skip closure types; they'll get instantiated when we instantiate
2626 // the corresponding lambda-expression.
2627 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2628 Record->isLambda())
Douglas Gregord801b062009-10-07 23:56:10 +00002629 continue;
2630
Douglas Gregor1d957a32009-10-27 18:42:08 +00002631 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2632 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002633
2634 if (MSInfo->getTemplateSpecializationKind()
2635 == TSK_ExplicitSpecialization)
2636 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00002637
Shoaib Meenaia9047452017-04-20 01:11:42 +00002638 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2639 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00002640 TSK == TSK_ExplicitInstantiationDeclaration) {
Shoaib Meenaia9047452017-04-20 01:11:42 +00002641 // In MSVC and Windows Itanium mode, explicit instantiation decl of the
2642 // outer class doesn't affect the inner class.
Hans Wennborga86a83b2016-05-26 19:42:56 +00002643 continue;
2644 }
2645
Douglas Gregor1d957a32009-10-27 18:42:08 +00002646 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2647 Record,
2648 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002649 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002650 SuppressNew) ||
2651 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002652 continue;
2653
Douglas Gregor1d957a32009-10-27 18:42:08 +00002654 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2655 assert(Pattern && "Missing instantiated-from-template information");
2656
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002657 if (!Record->getDefinition()) {
2658 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002659 // C++0x [temp.explicit]p8:
2660 // An explicit instantiation definition that names a class template
2661 // specialization explicitly instantiates the class template
2662 // specialization and is only an explicit instantiation definition
2663 // of members whose definition is visible at the point of
2664 // instantiation.
2665 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2666 MSInfo->setTemplateSpecializationKind(TSK);
2667 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2668 }
2669
2670 continue;
2671 }
2672
2673 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002674 TemplateArgs,
2675 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002676 } else {
2677 if (TSK == TSK_ExplicitInstantiationDefinition &&
2678 Record->getTemplateSpecializationKind() ==
2679 TSK_ExplicitInstantiationDeclaration) {
2680 Record->setTemplateSpecializationKind(TSK);
2681 MarkVTableUsed(PointOfInstantiation, Record, true);
2682 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002683 }
Douglas Gregorc093c1d2009-10-08 01:19:17 +00002684
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002685 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002686 if (Pattern)
2687 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2688 TSK);
Aaron Ballman629afae2014-03-07 19:56:05 +00002689 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smith4b38ded2012-03-14 23:13:10 +00002690 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2691 assert(MSInfo && "No member specialization information?");
2692
2693 if (MSInfo->getTemplateSpecializationKind()
2694 == TSK_ExplicitSpecialization)
2695 continue;
2696
2697 if (CheckSpecializationInstantiationRedecl(
2698 PointOfInstantiation, TSK, Enum,
2699 MSInfo->getTemplateSpecializationKind(),
2700 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2701 SuppressNew)
2702 continue;
2703
2704 if (Enum->getDefinition())
2705 continue;
2706
Richard Smith6739a102016-05-05 00:56:12 +00002707 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
Richard Smith4b38ded2012-03-14 23:13:10 +00002708 assert(Pattern && "Missing instantiated-from-template information");
2709
2710 if (TSK == TSK_ExplicitInstantiationDefinition) {
2711 if (!Pattern->getDefinition())
2712 continue;
2713
2714 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2715 } else {
2716 MSInfo->setTemplateSpecializationKind(TSK);
2717 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2718 }
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002719 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2720 // No need to instantiate in-class initializers during explicit
2721 // instantiation.
2722 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2723 CXXRecordDecl *ClassPattern =
2724 Instantiation->getTemplateInstantiationPattern();
2725 DeclContext::lookup_result Lookup =
2726 ClassPattern->lookup(Field->getDeclName());
David Majnemer76a25622016-06-09 05:26:56 +00002727 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002728 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2729 TemplateArgs);
2730 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002731 }
2732 }
2733}
2734
2735/// \brief Instantiate the definitions of all of the members of the
2736/// given class template specialization, which was named as part of an
2737/// explicit instantiation.
Mike Stump11289f42009-09-09 15:08:12 +00002738void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002739Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002740 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002741 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2742 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002743 // C++0x [temp.explicit]p7:
2744 // An explicit instantiation that names a class template
2745 // specialization is an explicit instantion of the same kind
2746 // (declaration or definition) of each of its members (not
2747 // including members inherited from base classes) that has not
2748 // been previously explicitly specialized in the translation unit
2749 // containing the explicit instantiation, except as described
2750 // below.
2751 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002752 getTemplateInstantiationArgs(ClassTemplateSpec),
2753 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002754}
2755
John McCalldadc5752010-08-24 06:29:42 +00002756StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002757Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002758 if (!S)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002759 return S;
Douglas Gregorebe10102009-08-20 07:17:43 +00002760
2761 TemplateInstantiator Instantiator(*this, TemplateArgs,
2762 SourceLocation(),
2763 DeclarationName());
2764 return Instantiator.TransformStmt(S);
2765}
2766
John McCalldadc5752010-08-24 06:29:42 +00002767ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002768Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002769 if (!E)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002770 return E;
Mike Stump11289f42009-09-09 15:08:12 +00002771
Douglas Gregora16548e2009-08-11 05:31:07 +00002772 TemplateInstantiator Instantiator(*this, TemplateArgs,
2773 SourceLocation(),
2774 DeclarationName());
2775 return Instantiator.TransformExpr(E);
2776}
2777
Richard Smithd59b8322012-12-19 01:39:02 +00002778ExprResult Sema::SubstInitializer(Expr *Init,
2779 const MultiLevelTemplateArgumentList &TemplateArgs,
2780 bool CXXDirectInit) {
2781 TemplateInstantiator Instantiator(*this, TemplateArgs,
2782 SourceLocation(),
2783 DeclarationName());
2784 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2785}
2786
Craig Topper99d23532015-12-24 23:58:29 +00002787bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002788 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002789 SmallVectorImpl<Expr *> &Outputs) {
Craig Topper99d23532015-12-24 23:58:29 +00002790 if (Exprs.empty())
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002791 return false;
Richard Smithd59b8322012-12-19 01:39:02 +00002792
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002793 TemplateInstantiator Instantiator(*this, TemplateArgs,
2794 SourceLocation(),
2795 DeclarationName());
Craig Topper99d23532015-12-24 23:58:29 +00002796 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2797 IsCall, Outputs);
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002798}
2799
Douglas Gregor14454802011-02-25 02:25:35 +00002800NestedNameSpecifierLoc
2801Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2802 const MultiLevelTemplateArgumentList &TemplateArgs) {
2803 if (!NNS)
2804 return NestedNameSpecifierLoc();
2805
2806 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2807 DeclarationName());
2808 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2809}
2810
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002811/// \brief Do template substitution on declaration name info.
2812DeclarationNameInfo
2813Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2814 const MultiLevelTemplateArgumentList &TemplateArgs) {
2815 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2816 NameInfo.getName());
2817 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2818}
2819
Douglas Gregoraa594892009-03-31 18:38:02 +00002820TemplateName
Douglas Gregordf846d12011-03-02 18:46:51 +00002821Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2822 TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002823 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002824 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2825 DeclarationName());
Douglas Gregordf846d12011-03-02 18:46:51 +00002826 CXXScopeSpec SS;
2827 SS.Adopt(QualifierLoc);
2828 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregoraa594892009-03-31 18:38:02 +00002829}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002830
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002831bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2832 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002833 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002834 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2835 DeclarationName());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002836
2837 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00002838}
Douglas Gregor14cf7522010-04-30 18:55:50 +00002839
Richard Smith70b13042015-01-09 01:19:56 +00002840static const Decl *getCanonicalParmVarDecl(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002841 // When storing ParmVarDecls in the local instantiation scope, we always
2842 // want to use the ParmVarDecl from the canonical function declaration,
2843 // since the map is then valid for any redeclaration or definition of that
2844 // function.
2845 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2846 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2847 unsigned i = PV->getFunctionScopeIndex();
Richard Smith70b13042015-01-09 01:19:56 +00002848 // This parameter might be from a freestanding function type within the
2849 // function and isn't necessarily referring to one of FD's parameters.
2850 if (FD->getParamDecl(i) == PV)
2851 return FD->getCanonicalDecl()->getParamDecl(i);
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002852 }
2853 }
2854 return D;
2855}
2856
2857
Douglas Gregorf3010112011-01-07 16:43:16 +00002858llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2859LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002860 D = getCanonicalParmVarDecl(D);
Chris Lattnercab02a62011-02-17 20:34:02 +00002861 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002862 Current = Current->Outer) {
Chris Lattnercab02a62011-02-17 20:34:02 +00002863
Douglas Gregor14cf7522010-04-30 18:55:50 +00002864 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002865 const Decl *CheckD = D;
2866 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00002867 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002868 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00002869 return &Found->second;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002870
2871 // If this is a tag declaration, it's possible that we need to look for
2872 // a previous declaration.
2873 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregorec9fd132012-01-14 16:38:05 +00002874 CheckD = Tag->getPreviousDecl();
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002875 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002876 CheckD = nullptr;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002877 } while (CheckD);
2878
Douglas Gregor14cf7522010-04-30 18:55:50 +00002879 // If we aren't combined with our outer scope, we're done.
2880 if (!Current->CombineWithOuterScope)
2881 break;
2882 }
Chris Lattnercab02a62011-02-17 20:34:02 +00002883
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002884 // If we're performing a partial substitution during template argument
2885 // deduction, we may not have values for template parameters yet.
2886 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2887 isa<TemplateTemplateParmDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00002888 return nullptr;
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002889
Serge Pavlove7ad8312015-05-15 10:10:28 +00002890 // Local types referenced prior to definition may require instantiation.
2891 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2892 if (RD->isLocalClass())
2893 return nullptr;
2894
2895 // Enumeration types referenced prior to definition may appear as a result of
2896 // error recovery.
2897 if (isa<EnumDecl>(D))
Serge Pavlov4c511742015-05-04 16:44:39 +00002898 return nullptr;
2899
Chris Lattnercab02a62011-02-17 20:34:02 +00002900 // If we didn't find the decl, then we either have a sema bug, or we have a
2901 // forward reference to a label declaration. Return null to indicate that
2902 // we have an uninstantiated label.
2903 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Craig Topperc3ec1492014-05-26 06:22:03 +00002904 return nullptr;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002905}
2906
John McCall19c1bfd2010-08-25 05:32:35 +00002907void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002908 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002909 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Richard Smith70b13042015-01-09 01:19:56 +00002910 if (Stored.isNull()) {
2911#ifndef NDEBUG
2912 // It should not be present in any surrounding scope either.
2913 LocalInstantiationScope *Current = this;
2914 while (Current->CombineWithOuterScope && Current->Outer) {
2915 Current = Current->Outer;
2916 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2917 "Instantiated local in inner and outer scopes");
2918 }
2919#endif
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002920 Stored = Inst;
Richard Smith70b13042015-01-09 01:19:56 +00002921 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
James Y Knight48fefa32015-09-30 14:04:23 +00002922 Pack->push_back(cast<ParmVarDecl>(Inst));
Richard Smith70b13042015-01-09 01:19:56 +00002923 } else {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002924 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Richard Smith70b13042015-01-09 01:19:56 +00002925 }
Douglas Gregor14cf7522010-04-30 18:55:50 +00002926}
Douglas Gregorf3010112011-01-07 16:43:16 +00002927
James Y Knight48fefa32015-09-30 14:04:23 +00002928void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2929 ParmVarDecl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002930 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002931 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2932 Pack->push_back(Inst);
2933}
2934
2935void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
Richard Smith70b13042015-01-09 01:19:56 +00002936#ifndef NDEBUG
2937 // This should be the first time we've been told about this decl.
2938 for (LocalInstantiationScope *Current = this;
2939 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2940 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2941 "Creating local pack after instantiation of local");
2942#endif
2943
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002944 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002945 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregorf3010112011-01-07 16:43:16 +00002946 DeclArgumentPack *Pack = new DeclArgumentPack;
2947 Stored = Pack;
2948 ArgumentPacks.push_back(Pack);
2949}
2950
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002951void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2952 const TemplateArgument *ExplicitArgs,
2953 unsigned NumExplicitArgs) {
2954 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2955 "Already have a partially-substituted pack");
2956 assert((!PartiallySubstitutedPack
2957 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2958 "Wrong number of arguments in partially-substituted pack");
2959 PartiallySubstitutedPack = Pack;
2960 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2961 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2962}
2963
2964NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2965 const TemplateArgument **ExplicitArgs,
2966 unsigned *NumExplicitArgs) const {
2967 if (ExplicitArgs)
Craig Topperc3ec1492014-05-26 06:22:03 +00002968 *ExplicitArgs = nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002969 if (NumExplicitArgs)
2970 *NumExplicitArgs = 0;
2971
2972 for (const LocalInstantiationScope *Current = this; Current;
2973 Current = Current->Outer) {
2974 if (Current->PartiallySubstitutedPack) {
2975 if (ExplicitArgs)
2976 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2977 if (NumExplicitArgs)
2978 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2979
2980 return Current->PartiallySubstitutedPack;
2981 }
2982
2983 if (!Current->CombineWithOuterScope)
2984 break;
2985 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002986
2987 return nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002988}