blob: 6db8eb3e5ed6b45babcdc17560514394137ffc04 [file] [log] [blame]
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Douglas Gregorfe1e1102009-02-27 19:31:52 +00006//===----------------------------------------------------------------------===/
7//
8// This file implements C++ template instantiation.
9//
10//===----------------------------------------------------------------------===/
11
John McCall83024632010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregord6ff3322009-08-04 16:50:30 +000013#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
Faisal Vali2cba1332013-10-23 06:44:28 +000016#include "clang/AST/ASTLambda.h"
Richard Smith4b054b22016-08-24 21:25:37 +000017#include "clang/AST/ASTMutationListener.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/Expr.h"
Jordan Rose1e879d82018-03-23 00:07:18 +000020#include "clang/AST/PrettyDeclStackTrace.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Basic/LangOptions.h"
Richard Smith26a92d52019-08-26 18:18:07 +000022#include "clang/Basic/Stack.h"
John McCall8b0666c2010-08-20 18:27:03 +000023#include "clang/Sema/DeclSpec.h"
Richard Smith938f40b2011-06-11 17:19:42 +000024#include "clang/Sema/Initialization.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000025#include "clang/Sema/Lookup.h"
John McCallde6836a2010-08-24 07:21:54 +000026#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000027#include "clang/Sema/TemplateDeduction.h"
Gabor Horvath207e7b12018-02-10 14:04:45 +000028#include "clang/Sema/TemplateInstCallback.h"
Anton Afanasyevd880de22019-03-30 08:42:48 +000029#include "llvm/Support/TimeProfiler.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000030
31using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000032using namespace sema;
Douglas Gregorfe1e1102009-02-27 19:31:52 +000033
Douglas Gregor4ea568f2009-03-10 18:03:33 +000034//===----------------------------------------------------------------------===/
35// Template Instantiation Support
36//===----------------------------------------------------------------------===/
37
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000038/// Retrieve the template argument list(s) that should be used to
Douglas Gregor01afeef2009-08-28 20:31:08 +000039/// instantiate the definition of the given declaration.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000040///
41/// \param D the declaration for which we are computing template instantiation
42/// arguments.
43///
44/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor8c702532010-02-05 07:33:43 +000045///
46/// \param RelativeToPrimary true if we should get the template
47/// arguments relative to the primary template, even when we're
48/// dealing with a specialization. This is only relevant for function
49/// template specializations.
Douglas Gregor1bd7a942010-05-03 23:29:10 +000050///
51/// \param Pattern If non-NULL, indicates the pattern from which we will be
52/// instantiating the definition of the given declaration, \p D. This is
53/// used to determine the proper set of template instantiation arguments for
54/// friend function template specializations.
Douglas Gregora654dd82009-08-28 17:37:35 +000055MultiLevelTemplateArgumentList
Fangrui Song6907ce22018-07-30 19:24:48 +000056Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor8c702532010-02-05 07:33:43 +000057 const TemplateArgumentList *Innermost,
Douglas Gregor1bd7a942010-05-03 23:29:10 +000058 bool RelativeToPrimary,
59 const FunctionDecl *Pattern) {
Douglas Gregora654dd82009-08-28 17:37:35 +000060 // Accumulate the set of template argument lists in this structure.
61 MultiLevelTemplateArgumentList Result;
Mike Stump11289f42009-09-09 15:08:12 +000062
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000063 if (Innermost)
64 Result.addOuterTemplateArguments(Innermost);
Fangrui Song6907ce22018-07-30 19:24:48 +000065
Douglas Gregora654dd82009-08-28 17:37:35 +000066 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregora51c9cc2011-05-22 00:21:10 +000067 if (!Ctx) {
Douglas Gregora654dd82009-08-28 17:37:35 +000068 Ctx = D->getDeclContext();
Larisse Voufo39a1e502013-08-06 01:03:05 +000069
Richard Smith59d05002019-04-26 02:11:23 +000070 // Add template arguments from a variable template instantiation. For a
71 // class-scope explicit specialization, there are no template arguments
72 // at this level, but there may be enclosing template arguments.
73 VarTemplateSpecializationDecl *Spec =
74 dyn_cast<VarTemplateSpecializationDecl>(D);
75 if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +000076 // We're done when we hit an explicit specialization.
77 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
78 !isa<VarTemplatePartialSpecializationDecl>(Spec))
79 return Result;
80
81 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
82
83 // If this variable template specialization was instantiated from a
84 // specialized member that is a variable template, we're done.
85 assert(Spec->getSpecializedTemplate() && "No variable template?");
Richard Smithbeef3452014-01-16 23:39:20 +000086 llvm::PointerUnion<VarTemplateDecl*,
87 VarTemplatePartialSpecializationDecl*> Specialized
88 = Spec->getSpecializedTemplateOrPartial();
89 if (VarTemplatePartialSpecializationDecl *Partial =
90 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
91 if (Partial->isMemberSpecialization())
92 return Result;
93 } else {
94 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
95 if (Tmpl->isMemberSpecialization())
96 return Result;
97 }
Larisse Voufo39a1e502013-08-06 01:03:05 +000098 }
99
Douglas Gregor55462622011-06-15 14:20:42 +0000100 // If we have a template template parameter with translation unit context,
101 // then we're performing substitution into a default template argument of
102 // this template template parameter before we've constructed the template
103 // that will own this template template parameter. In this case, we
104 // use empty template parameter lists for all of the outer templates
105 // to avoid performing any substitutions.
106 if (Ctx->isTranslationUnit()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000107 if (TemplateTemplateParmDecl *TTP
Douglas Gregor55462622011-06-15 14:20:42 +0000108 = dyn_cast<TemplateTemplateParmDecl>(D)) {
109 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +0000110 Result.addOuterTemplateArguments(None);
Douglas Gregor55462622011-06-15 14:20:42 +0000111 return Result;
112 }
113 }
Douglas Gregora51c9cc2011-05-22 00:21:10 +0000114 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000115
John McCall970d5302009-08-29 03:16:09 +0000116 while (!Ctx->isFileContext()) {
Douglas Gregora654dd82009-08-28 17:37:35 +0000117 // Add template arguments from a class template instantiation.
Richard Smith59d05002019-04-26 02:11:23 +0000118 ClassTemplateSpecializationDecl *Spec
119 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
120 if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
Douglas Gregora654dd82009-08-28 17:37:35 +0000121 // We're done when we hit an explicit specialization.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000122 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
123 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregora654dd82009-08-28 17:37:35 +0000124 break;
Mike Stump11289f42009-09-09 15:08:12 +0000125
Douglas Gregora654dd82009-08-28 17:37:35 +0000126 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Fangrui Song6907ce22018-07-30 19:24:48 +0000127
128 // If this class template specialization was instantiated from a
Douglas Gregorcf915552009-10-13 16:30:37 +0000129 // specialized member that is a class template, we're done.
130 assert(Spec->getSpecializedTemplate() && "No class template?");
131 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
132 break;
Mike Stump11289f42009-09-09 15:08:12 +0000133 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000134 // Add template arguments from a function template specialization.
John McCall970d5302009-08-29 03:16:09 +0000135 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor8c702532010-02-05 07:33:43 +0000136 if (!RelativeToPrimary &&
Richard Smithf19a8b02019-05-02 00:49:14 +0000137 Function->getTemplateSpecializationKindForInstantiation() ==
138 TSK_ExplicitSpecialization)
Douglas Gregorcf915552009-10-13 16:30:37 +0000139 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000140
Douglas Gregora654dd82009-08-28 17:37:35 +0000141 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorcf915552009-10-13 16:30:37 +0000142 = Function->getTemplateSpecializationArgs()) {
143 // Add the template arguments for this specialization.
Douglas Gregora654dd82009-08-28 17:37:35 +0000144 Result.addOuterTemplateArguments(TemplateArgs);
John McCall970d5302009-08-29 03:16:09 +0000145
Douglas Gregorcf915552009-10-13 16:30:37 +0000146 // If this function was instantiated from a specialized member that is
147 // a function template, we're done.
148 assert(Function->getPrimaryTemplate() && "No function template?");
149 if (Function->getPrimaryTemplate()->isMemberSpecialization())
150 break;
Faisal Vali2cba1332013-10-23 06:44:28 +0000151
152 // If this function is a generic lambda specialization, we are done.
153 if (isGenericLambdaCallOperatorSpecialization(Function))
154 break;
155
Douglas Gregor43669f82011-03-05 17:54:25 +0000156 } else if (FunctionTemplateDecl *FunTmpl
157 = Function->getDescribedFunctionTemplate()) {
158 // Add the "injected" template arguments.
Richard Smith841d8b22013-05-17 03:04:50 +0000159 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000160 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000161
John McCall970d5302009-08-29 03:16:09 +0000162 // If this is a friend declaration and it declares an entity at
163 // namespace scope, take arguments from its lexical parent
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000164 // instead of its semantic parent, unless of course the pattern we're
165 // instantiating actually comes from the file's context!
John McCall970d5302009-08-29 03:16:09 +0000166 if (Function->getFriendObjectKind() &&
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000167 Function->getDeclContext()->isFileContext() &&
168 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCall970d5302009-08-29 03:16:09 +0000169 Ctx = Function->getLexicalDeclContext();
Douglas Gregor8c702532010-02-05 07:33:43 +0000170 RelativeToPrimary = false;
John McCall970d5302009-08-29 03:16:09 +0000171 continue;
172 }
Douglas Gregor9961ce92010-07-08 18:37:38 +0000173 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
174 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
175 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith841d8b22013-05-17 03:04:50 +0000176 const TemplateSpecializationType *TST =
177 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
178 Result.addOuterTemplateArguments(
179 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor9961ce92010-07-08 18:37:38 +0000180 if (ClassTemplate->isMemberSpecialization())
181 break;
182 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000183 }
John McCall970d5302009-08-29 03:16:09 +0000184
185 Ctx = Ctx->getParent();
Douglas Gregor8c702532010-02-05 07:33:43 +0000186 RelativeToPrimary = false;
Douglas Gregorb4850462009-05-14 23:26:13 +0000187 }
Mike Stump11289f42009-09-09 15:08:12 +0000188
Douglas Gregora654dd82009-08-28 17:37:35 +0000189 return Result;
Douglas Gregorb4850462009-05-14 23:26:13 +0000190}
191
Richard Smith696e3122017-02-23 01:43:54 +0000192bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000193 switch (Kind) {
194 case TemplateInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000195 case ExceptionSpecInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000196 case DefaultTemplateArgumentInstantiation:
197 case DefaultFunctionArgumentInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000198 case ExplicitTemplateArgumentSubstitution:
199 case DeducedTemplateArgumentSubstitution:
200 case PriorTemplateArgumentSubstitution:
Saar Raz5d98ba62019-10-15 15:24:26 +0000201 case ConstraintsCheck:
Richard Smith8a874c92012-07-08 02:38:24 +0000202 return true;
203
Douglas Gregor84d49a22009-11-11 21:54:23 +0000204 case DefaultTemplateArgumentChecking:
Richard Smith13381222017-02-23 21:43:43 +0000205 case DeclaringSpecialMember:
Richard Smithbc240142019-12-10 16:45:02 -0800206 case DeclaringImplicitEqualityComparison:
Richard Smith883dbc42017-05-25 22:47:05 +0000207 case DefiningSynthesizedFunction:
Richard Smith5159bbad2018-09-05 22:30:37 +0000208 case ExceptionSpecEvaluation:
Saar Raz5d98ba62019-10-15 15:24:26 +0000209 case ConstraintSubstitution:
Richard Smith974c8b72019-10-19 00:04:43 +0000210 case RewritingOperatorAsSpaceship:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000211 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000212
Gabor Horvath207e7b12018-02-10 14:04:45 +0000213 // This function should never be called when Kind's value is Memoization.
214 case Memoization:
215 break;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000216 }
David Blaikie8a40f702012-01-17 06:56:22 +0000217
Richard Smith696e3122017-02-23 01:43:54 +0000218 llvm_unreachable("Invalid SynthesisKind!");
Douglas Gregor84d49a22009-11-11 21:54:23 +0000219}
220
Benjamin Kramer7761a042015-03-06 16:36:50 +0000221Sema::InstantiatingTemplate::InstantiatingTemplate(
Richard Smith696e3122017-02-23 01:43:54 +0000222 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000223 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
224 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000225 sema::TemplateDeductionInfo *DeductionInfo)
Richard Smith13381222017-02-23 21:43:43 +0000226 : SemaRef(SemaRef) {
Akira Hatanaka43556c12016-11-03 15:04:58 +0000227 // Don't allow further instantiation if a fatal error and an uncompilable
Akira Hatanaka40c15ab2016-11-03 17:11:28 +0000228 // error have occurred. Any diagnostics we might have raised will not be
Akira Hatanaka43556c12016-11-03 15:04:58 +0000229 // visible, and we do not need to construct a correct AST.
230 if (SemaRef.Diags.hasFatalErrorOccurred() &&
231 SemaRef.Diags.hasUncompilableErrorOccurred()) {
David Majnemer8c969ea2015-01-30 05:01:23 +0000232 Invalid = true;
233 return;
234 }
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000235 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
236 if (!Invalid) {
Richard Smith696e3122017-02-23 01:43:54 +0000237 CodeSynthesisContext Inst;
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000238 Inst.Kind = Kind;
239 Inst.PointOfInstantiation = PointOfInstantiation;
240 Inst.Entity = Entity;
241 Inst.Template = Template;
242 Inst.TemplateArgs = TemplateArgs.data();
243 Inst.NumTemplateArgs = TemplateArgs.size();
244 Inst.DeductionInfo = DeductionInfo;
245 Inst.InstantiationRange = InstantiationRange;
Richard Smith13381222017-02-23 21:43:43 +0000246 SemaRef.pushCodeSynthesisContext(Inst);
247
Richard Smith54f18e82016-08-31 02:15:21 +0000248 AlreadyInstantiating =
249 !SemaRef.InstantiatingSpecializations
250 .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
251 .second;
Gabor Horvath207e7b12018-02-10 14:04:45 +0000252 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000253 }
254}
255
Benjamin Kramer7761a042015-03-06 16:36:50 +0000256Sema::InstantiatingTemplate::InstantiatingTemplate(
257 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
258 SourceRange InstantiationRange)
259 : InstantiatingTemplate(SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000260 CodeSynthesisContext::TemplateInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000261 PointOfInstantiation, InstantiationRange, Entity) {}
Douglas Gregor79cf6032009-03-10 20:44:00 +0000262
Benjamin Kramer7761a042015-03-06 16:36:50 +0000263Sema::InstantiatingTemplate::InstantiatingTemplate(
264 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
265 ExceptionSpecification, SourceRange InstantiationRange)
266 : InstantiatingTemplate(
Richard Smith696e3122017-02-23 01:43:54 +0000267 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000268 PointOfInstantiation, InstantiationRange, Entity) {}
Richard Smithf623c962012-04-17 00:58:00 +0000269
Benjamin Kramer7761a042015-03-06 16:36:50 +0000270Sema::InstantiatingTemplate::InstantiatingTemplate(
Richard Smith54f18e82016-08-31 02:15:21 +0000271 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
272 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
273 SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000274 : InstantiatingTemplate(
275 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000276 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
Richard Smith54f18e82016-08-31 02:15:21 +0000277 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
278 Template, TemplateArgs) {}
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000279
Benjamin Kramer7761a042015-03-06 16:36:50 +0000280Sema::InstantiatingTemplate::InstantiatingTemplate(
281 Sema &SemaRef, SourceLocation PointOfInstantiation,
282 FunctionTemplateDecl *FunctionTemplate,
283 ArrayRef<TemplateArgument> TemplateArgs,
Richard Smith696e3122017-02-23 01:43:54 +0000284 CodeSynthesisContext::SynthesisKind Kind,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000285 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
286 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
287 InstantiationRange, FunctionTemplate, nullptr,
Richard Smith54f18e82016-08-31 02:15:21 +0000288 TemplateArgs, &DeductionInfo) {
289 assert(
Richard Smith696e3122017-02-23 01:43:54 +0000290 Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
291 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution);
Richard Smith54f18e82016-08-31 02:15:21 +0000292}
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000293
Benjamin Kramer7761a042015-03-06 16:36:50 +0000294Sema::InstantiatingTemplate::InstantiatingTemplate(
295 Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith0e617ec2016-12-27 07:56:27 +0000296 TemplateDecl *Template,
297 ArrayRef<TemplateArgument> TemplateArgs,
298 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
299 : InstantiatingTemplate(
300 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000301 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
Richard Smith0e617ec2016-12-27 07:56:27 +0000302 PointOfInstantiation, InstantiationRange, Template, nullptr,
303 TemplateArgs, &DeductionInfo) {}
304
305Sema::InstantiatingTemplate::InstantiatingTemplate(
306 Sema &SemaRef, SourceLocation PointOfInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000307 ClassTemplatePartialSpecializationDecl *PartialSpec,
308 ArrayRef<TemplateArgument> TemplateArgs,
309 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
310 : InstantiatingTemplate(
311 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000312 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000313 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
314 TemplateArgs, &DeductionInfo) {}
Douglas Gregor637d9982009-06-10 23:47:09 +0000315
Larisse Voufo39a1e502013-08-06 01:03:05 +0000316Sema::InstantiatingTemplate::InstantiatingTemplate(
317 Sema &SemaRef, SourceLocation PointOfInstantiation,
318 VarTemplatePartialSpecializationDecl *PartialSpec,
319 ArrayRef<TemplateArgument> TemplateArgs,
320 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000321 : InstantiatingTemplate(
322 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000323 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000324 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
325 TemplateArgs, &DeductionInfo) {}
Larisse Voufo39a1e502013-08-06 01:03:05 +0000326
Benjamin Kramer7761a042015-03-06 16:36:50 +0000327Sema::InstantiatingTemplate::InstantiatingTemplate(
328 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
329 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
330 : InstantiatingTemplate(
331 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000332 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000333 PointOfInstantiation, InstantiationRange, Param, nullptr,
334 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000335
Benjamin Kramer7761a042015-03-06 16:36:50 +0000336Sema::InstantiatingTemplate::InstantiatingTemplate(
337 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
338 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
339 SourceRange InstantiationRange)
340 : InstantiatingTemplate(
341 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000342 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000343 PointOfInstantiation, InstantiationRange, Param, Template,
344 TemplateArgs) {}
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000345
Benjamin Kramer7761a042015-03-06 16:36:50 +0000346Sema::InstantiatingTemplate::InstantiatingTemplate(
347 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
348 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
349 SourceRange InstantiationRange)
350 : InstantiatingTemplate(
351 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000352 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000353 PointOfInstantiation, InstantiationRange, Param, Template,
354 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000355
Benjamin Kramer7761a042015-03-06 16:36:50 +0000356Sema::InstantiatingTemplate::InstantiatingTemplate(
357 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
358 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
359 SourceRange InstantiationRange)
360 : InstantiatingTemplate(
Richard Smith696e3122017-02-23 01:43:54 +0000361 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000362 PointOfInstantiation, InstantiationRange, Param, Template,
363 TemplateArgs) {}
Anders Carlsson657bad42009-09-05 05:14:19 +0000364
Saar Raz5d98ba62019-10-15 15:24:26 +0000365Sema::InstantiatingTemplate::InstantiatingTemplate(
366 Sema &SemaRef, SourceLocation PointOfInstantiation,
Saar Razfdf80e82019-12-06 01:30:21 +0200367 ConstraintsCheck, NamedDecl *Template,
Saar Raz5d98ba62019-10-15 15:24:26 +0000368 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
369 : InstantiatingTemplate(
370 SemaRef, CodeSynthesisContext::ConstraintsCheck,
371 PointOfInstantiation, InstantiationRange, Template, nullptr,
372 TemplateArgs) {}
373
374Sema::InstantiatingTemplate::InstantiatingTemplate(
375 Sema &SemaRef, SourceLocation PointOfInstantiation,
Saar Razfdf80e82019-12-06 01:30:21 +0200376 ConstraintSubstitution, NamedDecl *Template,
Saar Raz5d98ba62019-10-15 15:24:26 +0000377 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
378 : InstantiatingTemplate(
379 SemaRef, CodeSynthesisContext::ConstraintSubstitution,
380 PointOfInstantiation, InstantiationRange, Template, nullptr,
381 {}, &DeductionInfo) {}
382
Richard Smith13381222017-02-23 21:43:43 +0000383void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
384 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
385 InNonInstantiationSFINAEContext = false;
386
387 CodeSynthesisContexts.push_back(Ctx);
388
389 if (!Ctx.isInstantiationRecord())
390 ++NonInstantiationEntries;
Richard Smith26a92d52019-08-26 18:18:07 +0000391
392 // Check to see if we're low on stack space. We can't do anything about this
393 // from here, but we can at least warn the user.
394 if (isStackNearlyExhausted())
395 warnStackExhausted(Ctx.PointOfInstantiation);
Richard Smith13381222017-02-23 21:43:43 +0000396}
397
398void Sema::popCodeSynthesisContext() {
399 auto &Active = CodeSynthesisContexts.back();
400 if (!Active.isInstantiationRecord()) {
401 assert(NonInstantiationEntries > 0);
402 --NonInstantiationEntries;
403 }
404
405 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
406
407 // Name lookup no longer looks in this template's defining module.
408 assert(CodeSynthesisContexts.size() >=
409 CodeSynthesisContextLookupModules.size() &&
410 "forgot to remove a lookup module for a template instantiation");
411 if (CodeSynthesisContexts.size() ==
412 CodeSynthesisContextLookupModules.size()) {
413 if (Module *M = CodeSynthesisContextLookupModules.back())
414 LookupModulesCache.erase(M);
415 CodeSynthesisContextLookupModules.pop_back();
416 }
417
418 // If we've left the code synthesis context for the current context stack,
419 // stop remembering that we've emitted that stack.
420 if (CodeSynthesisContexts.size() ==
421 LastEmittedCodeSynthesisContextDepth)
422 LastEmittedCodeSynthesisContextDepth = 0;
423
424 CodeSynthesisContexts.pop_back();
425}
426
Douglas Gregor85673582009-05-18 17:01:57 +0000427void Sema::InstantiatingTemplate::Clear() {
428 if (!Invalid) {
Richard Smith13381222017-02-23 21:43:43 +0000429 if (!AlreadyInstantiating) {
430 auto &Active = SemaRef.CodeSynthesisContexts.back();
Richard Smith54f18e82016-08-31 02:15:21 +0000431 SemaRef.InstantiatingSpecializations.erase(
432 std::make_pair(Active.Entity, Active.Kind));
Richard Smith13381222017-02-23 21:43:43 +0000433 }
Richard Smith54f18e82016-08-31 02:15:21 +0000434
Gabor Horvath207e7b12018-02-10 14:04:45 +0000435 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
436 SemaRef.CodeSynthesisContexts.back());
Richard Smith13381222017-02-23 21:43:43 +0000437
Gabor Horvath207e7b12018-02-10 14:04:45 +0000438 SemaRef.popCodeSynthesisContext();
Douglas Gregor85673582009-05-18 17:01:57 +0000439 Invalid = true;
440 }
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000441}
442
Douglas Gregor79cf6032009-03-10 20:44:00 +0000443bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
444 SourceLocation PointOfInstantiation,
445 SourceRange InstantiationRange) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000446 assert(SemaRef.NonInstantiationEntries <=
Richard Smith696e3122017-02-23 01:43:54 +0000447 SemaRef.CodeSynthesisContexts.size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000448 if ((SemaRef.CodeSynthesisContexts.size() -
Douglas Gregor84d49a22009-11-11 21:54:23 +0000449 SemaRef.NonInstantiationEntries)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000450 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregor79cf6032009-03-10 20:44:00 +0000451 return false;
452
Mike Stump11289f42009-09-09 15:08:12 +0000453 SemaRef.Diag(PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000454 diag::err_template_recursion_depth_exceeded)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000455 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregor79cf6032009-03-10 20:44:00 +0000456 << InstantiationRange;
457 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000458 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000459 return true;
460}
461
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000462/// Prints the current instantiation stack through a series of
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000463/// notes.
464void Sema::PrintInstantiationStack() {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000465 // Determine which template instantiations to skip, if any.
Richard Smith696e3122017-02-23 01:43:54 +0000466 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000467 unsigned Limit = Diags.getTemplateBacktraceLimit();
Richard Smith696e3122017-02-23 01:43:54 +0000468 if (Limit && Limit < CodeSynthesisContexts.size()) {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000469 SkipStart = Limit / 2 + Limit % 2;
Richard Smith696e3122017-02-23 01:43:54 +0000470 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000471 }
472
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000473 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000474 unsigned InstantiationIdx = 0;
Richard Smith696e3122017-02-23 01:43:54 +0000475 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
476 Active = CodeSynthesisContexts.rbegin(),
477 ActiveEnd = CodeSynthesisContexts.rend();
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000478 Active != ActiveEnd;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000479 ++Active, ++InstantiationIdx) {
480 // Skip this instantiation?
481 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
482 if (InstantiationIdx == SkipStart) {
483 // Note that we're skipping instantiations.
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000484 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000485 diag::note_instantiation_contexts_suppressed)
Richard Smith696e3122017-02-23 01:43:54 +0000486 << unsigned(CodeSynthesisContexts.size() - Limit);
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000487 }
488 continue;
489 }
490
Douglas Gregor79cf6032009-03-10 20:44:00 +0000491 switch (Active->Kind) {
Richard Smith696e3122017-02-23 01:43:54 +0000492 case CodeSynthesisContext::TemplateInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000493 Decl *D = Active->Entity;
Douglas Gregor85673582009-05-18 17:01:57 +0000494 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
495 unsigned DiagID = diag::note_template_member_class_here;
496 if (isa<ClassTemplateSpecializationDecl>(Record))
497 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000498 Diags.Report(Active->PointOfInstantiation, DiagID)
Richard Smith792c22d2016-12-24 04:09:05 +0000499 << Record << Active->InstantiationRange;
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000500 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +0000501 unsigned DiagID;
502 if (Function->getPrimaryTemplate())
503 DiagID = diag::note_function_template_spec_here;
504 else
505 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000506 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000507 << Function
508 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000509 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000510 Diags.Report(Active->PointOfInstantiation,
Larisse Voufodbd65772013-08-14 20:15:02 +0000511 VD->isStaticDataMember()?
512 diag::note_template_static_data_member_def_here
513 : diag::note_template_variable_def_here)
Richard Smith3f1b5d02011-05-05 21:57:07 +0000514 << VD
515 << Active->InstantiationRange;
Richard Smith4b38ded2012-03-14 23:13:10 +0000516 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
517 Diags.Report(Active->PointOfInstantiation,
518 diag::note_template_enum_def_here)
519 << ED
520 << Active->InstantiationRange;
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000521 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
522 Diags.Report(Active->PointOfInstantiation,
523 diag::note_template_nsdmi_here)
524 << FD << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000525 } else {
526 Diags.Report(Active->PointOfInstantiation,
527 diag::note_template_type_alias_instantiation_here)
528 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000529 << Active->InstantiationRange;
Douglas Gregor85673582009-05-18 17:01:57 +0000530 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000531 break;
532 }
533
Richard Smith696e3122017-02-23 01:43:54 +0000534 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
Richard Smith54f18e82016-08-31 02:15:21 +0000535 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000536 SmallVector<char, 128> TemplateArgsStr;
537 llvm::raw_svector_ostream OS(TemplateArgsStr);
538 Template->printName(OS);
Serge Pavlov03e672c2017-11-28 16:14:14 +0000539 printTemplateArgumentList(OS, Active->template_arguments(),
540 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000541 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000542 diag::note_default_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000543 << OS.str()
Douglas Gregor79cf6032009-03-10 20:44:00 +0000544 << Active->InstantiationRange;
545 break;
546 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000547
Richard Smith696e3122017-02-23 01:43:54 +0000548 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000549 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000550 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000551 diag::note_explicit_template_arg_substitution_here)
Fangrui Song6907ce22018-07-30 19:24:48 +0000552 << FnTmpl
553 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
554 Active->TemplateArgs,
Douglas Gregor607f1412010-03-30 20:35:20 +0000555 Active->NumTemplateArgs)
556 << Active->InstantiationRange;
Douglas Gregor637d9982009-06-10 23:47:09 +0000557 break;
558 }
Mike Stump11289f42009-09-09 15:08:12 +0000559
Richard Smith696e3122017-02-23 01:43:54 +0000560 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
Richard Smithe68a38f2016-12-24 04:20:31 +0000561 if (FunctionTemplateDecl *FnTmpl =
562 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000563 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000564 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000565 << FnTmpl
Fangrui Song6907ce22018-07-30 19:24:48 +0000566 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
567 Active->TemplateArgs,
Douglas Gregor607f1412010-03-30 20:35:20 +0000568 Active->NumTemplateArgs)
569 << Active->InstantiationRange;
Richard Smithe68a38f2016-12-24 04:20:31 +0000570 } else {
571 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
572 isa<VarTemplateSpecializationDecl>(Active->Entity);
Richard Smith0e617ec2016-12-27 07:56:27 +0000573 bool IsTemplate = false;
Richard Smithe68a38f2016-12-24 04:20:31 +0000574 TemplateParameterList *Params;
Richard Smith0e617ec2016-12-27 07:56:27 +0000575 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
576 IsTemplate = true;
577 Params = D->getTemplateParameters();
578 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
Richard Smithe68a38f2016-12-24 04:20:31 +0000579 Active->Entity)) {
580 Params = D->getTemplateParameters();
581 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
582 Active->Entity)) {
583 Params = D->getTemplateParameters();
584 } else {
585 llvm_unreachable("unexpected template kind");
586 }
587
Richard Smithe68a38f2016-12-24 04:20:31 +0000588 Diags.Report(Active->PointOfInstantiation,
589 diag::note_deduced_template_arg_substitution_here)
Richard Smith0e617ec2016-12-27 07:56:27 +0000590 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
Fangrui Song6907ce22018-07-30 19:24:48 +0000591 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
Richard Smithe68a38f2016-12-24 04:20:31 +0000592 Active->NumTemplateArgs)
593 << Active->InstantiationRange;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000594 }
595 break;
Richard Smithe68a38f2016-12-24 04:20:31 +0000596 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000597
Richard Smith696e3122017-02-23 01:43:54 +0000598 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000599 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson657bad42009-09-05 05:14:19 +0000600 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +0000601
Benjamin Kramer9170e912013-02-22 15:46:01 +0000602 SmallVector<char, 128> TemplateArgsStr;
603 llvm::raw_svector_ostream OS(TemplateArgsStr);
604 FD->printName(OS);
Serge Pavlov03e672c2017-11-28 16:14:14 +0000605 printTemplateArgumentList(OS, Active->template_arguments(),
606 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000607 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000608 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000609 << OS.str()
Anders Carlsson657bad42009-09-05 05:14:19 +0000610 << Active->InstantiationRange;
611 break;
612 }
Mike Stump11289f42009-09-09 15:08:12 +0000613
Richard Smith696e3122017-02-23 01:43:54 +0000614 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000615 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000616 std::string Name;
617 if (!Parm->getName().empty())
618 Name = std::string(" '") + Parm->getName().str() + "'";
Craig Topperc3ec1492014-05-26 06:22:03 +0000619
620 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000621 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
622 TemplateParams = Template->getTemplateParameters();
623 else
624 TemplateParams =
625 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
626 ->getTemplateParameters();
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000627 Diags.Report(Active->PointOfInstantiation,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000628 diag::note_prior_template_arg_substitution)
629 << isa<TemplateTemplateParmDecl>(Parm)
630 << Name
Fangrui Song6907ce22018-07-30 19:24:48 +0000631 << getTemplateArgumentBindingsText(TemplateParams,
632 Active->TemplateArgs,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000633 Active->NumTemplateArgs)
634 << Active->InstantiationRange;
635 break;
636 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000637
Richard Smith696e3122017-02-23 01:43:54 +0000638 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
Craig Topperc3ec1492014-05-26 06:22:03 +0000639 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000640 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
641 TemplateParams = Template->getTemplateParameters();
642 else
643 TemplateParams =
644 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
645 ->getTemplateParameters();
646
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000647 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000648 diag::note_template_default_arg_checking)
Fangrui Song6907ce22018-07-30 19:24:48 +0000649 << getTemplateArgumentBindingsText(TemplateParams,
650 Active->TemplateArgs,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000651 Active->NumTemplateArgs)
652 << Active->InstantiationRange;
653 break;
654 }
Richard Smithf623c962012-04-17 00:58:00 +0000655
Richard Smith5159bbad2018-09-05 22:30:37 +0000656 case CodeSynthesisContext::ExceptionSpecEvaluation:
657 Diags.Report(Active->PointOfInstantiation,
658 diag::note_evaluating_exception_spec_here)
659 << cast<FunctionDecl>(Active->Entity);
660 break;
661
Richard Smith696e3122017-02-23 01:43:54 +0000662 case CodeSynthesisContext::ExceptionSpecInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000663 Diags.Report(Active->PointOfInstantiation,
664 diag::note_template_exception_spec_instantiation_here)
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000665 << cast<FunctionDecl>(Active->Entity)
Richard Smithf623c962012-04-17 00:58:00 +0000666 << Active->InstantiationRange;
667 break;
Richard Smith13381222017-02-23 21:43:43 +0000668
669 case CodeSynthesisContext::DeclaringSpecialMember:
670 Diags.Report(Active->PointOfInstantiation,
671 diag::note_in_declaration_of_implicit_special_member)
672 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
673 break;
Richard Smith883dbc42017-05-25 22:47:05 +0000674
Richard Smithbc240142019-12-10 16:45:02 -0800675 case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
676 Diags.Report(Active->Entity->getLocation(),
677 diag::note_in_declaration_of_implicit_equality_comparison);
678 break;
679
Gabor Horvath207e7b12018-02-10 14:04:45 +0000680 case CodeSynthesisContext::DefiningSynthesizedFunction: {
Richard Smithcafc7412019-12-04 15:25:27 -0800681 // FIXME: For synthesized functions that are not defaulted,
682 // produce a note.
683 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
684 DefaultedFunctionKind DFK =
685 FD ? getDefaultedFunctionKind(FD) : DefaultedFunctionKind();
686 if (DFK.isSpecialMember()) {
687 auto *MD = cast<CXXMethodDecl>(FD);
Richard Smith883dbc42017-05-25 22:47:05 +0000688 Diags.Report(Active->PointOfInstantiation,
689 diag::note_member_synthesized_at)
Richard Smithcafc7412019-12-04 15:25:27 -0800690 << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
691 << Context.getTagDeclType(MD->getParent());
692 } else if (DFK.isComparison()) {
693 Diags.Report(Active->PointOfInstantiation,
694 diag::note_comparison_synthesized_at)
695 << (int)DFK.asComparison()
696 << Context.getTagDeclType(
697 cast<CXXRecordDecl>(FD->getLexicalDeclContext()));
Richard Smith883dbc42017-05-25 22:47:05 +0000698 }
699 break;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000700 }
Gabor Horvath207e7b12018-02-10 14:04:45 +0000701
Richard Smith974c8b72019-10-19 00:04:43 +0000702 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
703 Diags.Report(Active->Entity->getLocation(),
704 diag::note_rewriting_operator_as_spaceship);
705 break;
706
Gabor Horvath207e7b12018-02-10 14:04:45 +0000707 case CodeSynthesisContext::Memoization:
708 break;
Saar Raz5d98ba62019-10-15 15:24:26 +0000709
Saar Razfdf80e82019-12-06 01:30:21 +0200710 case CodeSynthesisContext::ConstraintsCheck: {
711 unsigned DiagID = 0;
712 if (isa<ConceptDecl>(Active->Entity))
713 DiagID = diag::note_concept_specialization_here;
714 else if (isa<TemplateDecl>(Active->Entity))
715 DiagID = diag::note_checking_constraints_for_template_id_here;
716 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
717 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
718 else {
719 assert(isa<ClassTemplatePartialSpecializationDecl>(Active->Entity));
720 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
Saar Raz5d98ba62019-10-15 15:24:26 +0000721 }
Saar Razfdf80e82019-12-06 01:30:21 +0200722 SmallVector<char, 128> TemplateArgsStr;
723 llvm::raw_svector_ostream OS(TemplateArgsStr);
724 cast<NamedDecl>(Active->Entity)->printName(OS);
725 printTemplateArgumentList(OS, Active->template_arguments(),
726 getPrintingPolicy());
727 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
728 << Active->InstantiationRange;
Saar Raz5d98ba62019-10-15 15:24:26 +0000729 break;
Saar Razfdf80e82019-12-06 01:30:21 +0200730 }
Saar Raz5d98ba62019-10-15 15:24:26 +0000731 case CodeSynthesisContext::ConstraintSubstitution:
732 Diags.Report(Active->PointOfInstantiation,
733 diag::note_constraint_substitution_here)
734 << Active->InstantiationRange;
735 break;
Gabor Horvath207e7b12018-02-10 14:04:45 +0000736 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000737 }
738}
739
David Blaikie05785d12013-02-20 22:23:23 +0000740Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregoredb76852011-01-27 22:31:44 +0000741 if (InNonInstantiationSFINAEContext)
Craig Topperc3ec1492014-05-26 06:22:03 +0000742 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregoredb76852011-01-27 22:31:44 +0000743
Richard Smith696e3122017-02-23 01:43:54 +0000744 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
745 Active = CodeSynthesisContexts.rbegin(),
746 ActiveEnd = CodeSynthesisContexts.rend();
Douglas Gregor33834512009-06-14 07:33:30 +0000747 Active != ActiveEnd;
Fangrui Song6907ce22018-07-30 19:24:48 +0000748 ++Active)
Douglas Gregor84d49a22009-11-11 21:54:23 +0000749 {
Richard Smith13381222017-02-23 21:43:43 +0000750 switch (Active->Kind) {
Richard Smith696e3122017-02-23 01:43:54 +0000751 case CodeSynthesisContext::TemplateInstantiation:
Richard Smith72249ba2012-04-26 07:24:08 +0000752 // An instantiation of an alias template may or may not be a SFINAE
753 // context, depending on what else is on the stack.
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000754 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smith72249ba2012-04-26 07:24:08 +0000755 break;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +0000756 LLVM_FALLTHROUGH;
Richard Smith696e3122017-02-23 01:43:54 +0000757 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
758 case CodeSynthesisContext::ExceptionSpecInstantiation:
Saar Raz5d98ba62019-10-15 15:24:26 +0000759 case CodeSynthesisContext::ConstraintsCheck:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000760 // This is a template instantiation, so there is no SFINAE.
David Blaikie7a30dc52013-02-21 01:47:18 +0000761 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000762
Richard Smith696e3122017-02-23 01:43:54 +0000763 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
764 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
765 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000766 // A default template argument instantiation and substitution into
Fangrui Song6907ce22018-07-30 19:24:48 +0000767 // template parameters with arguments for prior parameters may or may
Douglas Gregore62e6a02009-11-11 19:13:48 +0000768 // not be a SFINAE context; look further up the stack.
Douglas Gregor33834512009-06-14 07:33:30 +0000769 break;
Mike Stump11289f42009-09-09 15:08:12 +0000770
Richard Smith696e3122017-02-23 01:43:54 +0000771 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
772 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
Saar Raz5d98ba62019-10-15 15:24:26 +0000773 case CodeSynthesisContext::ConstraintSubstitution:
774 // We're either substituting explicitly-specified template arguments
775 // or deduced template arguments or a constraint expression, so SFINAE
776 // applies.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000777 assert(Active->DeductionInfo && "Missing deduction info pointer");
778 return Active->DeductionInfo;
Richard Smith13381222017-02-23 21:43:43 +0000779
780 case CodeSynthesisContext::DeclaringSpecialMember:
Richard Smithbc240142019-12-10 16:45:02 -0800781 case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
Richard Smith883dbc42017-05-25 22:47:05 +0000782 case CodeSynthesisContext::DefiningSynthesizedFunction:
Richard Smith974c8b72019-10-19 00:04:43 +0000783 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
Richard Smith13381222017-02-23 21:43:43 +0000784 // This happens in a context unrelated to template instantiation, so
785 // there is no SFINAE.
786 return None;
Gabor Horvath207e7b12018-02-10 14:04:45 +0000787
Richard Smith5159bbad2018-09-05 22:30:37 +0000788 case CodeSynthesisContext::ExceptionSpecEvaluation:
789 // FIXME: This should not be treated as a SFINAE context, because
790 // we will cache an incorrect exception specification. However, clang
791 // bootstrap relies this! See PR31692.
792 break;
793
Gabor Horvath207e7b12018-02-10 14:04:45 +0000794 case CodeSynthesisContext::Memoization:
795 break;
Douglas Gregor33834512009-06-14 07:33:30 +0000796 }
Richard Smith13381222017-02-23 21:43:43 +0000797
798 // The inner context was transparent for SFINAE. If it occurred within a
799 // non-instantiation SFINAE context, then SFINAE applies.
800 if (Active->SavedInNonInstantiationSFINAEContext)
801 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregor33834512009-06-14 07:33:30 +0000802 }
803
David Blaikie7a30dc52013-02-21 01:47:18 +0000804 return None;
Douglas Gregor33834512009-06-14 07:33:30 +0000805}
806
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000807//===----------------------------------------------------------------------===/
808// Template Instantiation for Types
809//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000810namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000811 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000812 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000813 SourceLocation Loc;
814 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000815
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000816 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000817 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000818
819 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000820 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000821 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000822 DeclarationName Entity)
823 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000824 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000825
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000826 /// Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-08-04 16:50:30 +0000827 /// transformed.
828 ///
829 /// For the purposes of template instantiation, a type has already been
830 /// transformed if it is NULL or if it is not dependent.
Douglas Gregor5597ab42010-05-07 23:12:07 +0000831 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000832
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000833 /// Returns the location of the entity being instantiated, if known.
Douglas Gregord6ff3322009-08-04 16:50:30 +0000834 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000835
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000836 /// Returns the name of the entity being instantiated, if any.
Douglas Gregord6ff3322009-08-04 16:50:30 +0000837 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000838
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000839 /// Sets the "base" location and entity when that
Douglas Gregoref6ab412009-10-27 06:26:26 +0000840 /// information is known based on another transformation.
841 void setBase(SourceLocation Loc, DeclarationName Entity) {
842 this->Loc = Loc;
843 this->Entity = Entity;
844 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000845
846 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
847 SourceRange PatternRange,
Robert Wilhelm16e94b92013-08-09 18:02:13 +0000848 ArrayRef<UnexpandedParameterPack> Unexpanded,
849 bool &ShouldExpand, bool &RetainExpansion,
David Blaikie05785d12013-02-20 22:23:23 +0000850 Optional<unsigned> &NumExpansions) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000851 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000852 PatternRange, Unexpanded,
Fangrui Song6907ce22018-07-30 19:24:48 +0000853 TemplateArgs,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000854 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000855 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000856 NumExpansions);
857 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000858
Fangrui Song6907ce22018-07-30 19:24:48 +0000859 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
Douglas Gregorf3010112011-01-07 16:43:16 +0000860 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
861 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000862
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000863 TemplateArgument ForgetPartiallySubstitutedPack() {
864 TemplateArgument Result;
865 if (NamedDecl *PartialPack
866 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
867 MultiLevelTemplateArgumentList &TemplateArgs
868 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
869 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000870 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000871 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
872 Result = TemplateArgs(Depth, Index);
873 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
874 }
875 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000876
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000877 return Result;
878 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000879
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000880 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
881 if (Arg.isNull())
882 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000883
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000884 if (NamedDecl *PartialPack
885 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
886 MultiLevelTemplateArgumentList &TemplateArgs
887 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
888 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000889 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000890 TemplateArgs.setArgument(Depth, Index, Arg);
891 }
892 }
893
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000894 /// Transform the given declaration by instantiating a reference to
Douglas Gregord6ff3322009-08-04 16:50:30 +0000895 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000896 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000897
Fangrui Song6907ce22018-07-30 19:24:48 +0000898 void transformAttrs(Decl *Old, Decl *New) {
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000899 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
900 }
901
Richard Smithb2997f52019-05-21 20:10:50 +0000902 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
903 if (Old->isParameterPack()) {
904 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);
905 for (auto *New : NewDecls)
906 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
907 Old, cast<VarDecl>(New));
908 return;
909 }
910
911 assert(NewDecls.size() == 1 &&
912 "should only have multiple expansions for a pack");
913 Decl *New = NewDecls.front();
914
Richard Smithc38498f2015-04-27 21:27:54 +0000915 // If we've instantiated the call operator of a lambda or the call
916 // operator template of a generic lambda, update the "instantiation of"
917 // information.
918 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
919 if (NewMD && isLambdaCallOperator(NewMD)) {
920 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
921 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
922 NewTD->setInstantiatedFromMemberTemplate(
923 OldMD->getDescribedFunctionTemplate());
924 else
925 NewMD->setInstantiationOfMemberFunction(OldMD,
926 TSK_ImplicitInstantiation);
927 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000928
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000929 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
Richard Smithc7649dc2016-03-23 20:07:07 +0000930
931 // We recreated a local declaration, but not by instantiating it. There
932 // may be pending dependent diagnostics to produce.
933 if (auto *DC = dyn_cast<DeclContext>(Old))
934 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000935 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000936
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000937 /// Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000938 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000939 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000940
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000941 /// Transform the first qualifier within a scope by instantiating the
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000942 /// declaration.
943 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
Fangrui Song6907ce22018-07-30 19:24:48 +0000944
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000945 /// Rebuild the exception declaration and register the declaration
Douglas Gregorebe10102009-08-20 07:17:43 +0000946 /// as an instantiated local.
Fangrui Song6907ce22018-07-30 19:24:48 +0000947 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000948 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000949 SourceLocation StartLoc,
950 SourceLocation NameLoc,
951 IdentifierInfo *Name);
Mike Stump11289f42009-09-09 15:08:12 +0000952
Fangrui Song6907ce22018-07-30 19:24:48 +0000953 /// Rebuild the Objective-C exception declaration and register the
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000954 /// declaration as an instantiated local.
Fangrui Song6907ce22018-07-30 19:24:48 +0000955 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000956 TypeSourceInfo *TSInfo, QualType T);
Fangrui Song6907ce22018-07-30 19:24:48 +0000957
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000958 /// Check for tag mismatches when instantiating an
John McCall7f41d982009-09-11 04:59:25 +0000959 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000960 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
961 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000962 NestedNameSpecifierLoc QualifierLoc,
963 QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000964
Craig Topperc3ec1492014-05-26 06:22:03 +0000965 TemplateName
966 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
967 SourceLocation NameLoc,
968 QualType ObjectType = QualType(),
Richard Smithfd3dae02017-01-20 00:20:39 +0000969 NamedDecl *FirstQualifierInScope = nullptr,
970 bool AllowInjectedClassName = false);
Douglas Gregor9db53502011-03-02 18:07:45 +0000971
Tyler Nowickic724a83e2014-10-12 20:46:07 +0000972 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
973
John McCalldadc5752010-08-24 06:29:42 +0000974 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
975 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
976 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000977
John McCalldadc5752010-08-24 06:29:42 +0000978 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000979 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000980 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
981 SubstNonTypeTemplateParmPackExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000982
Richard Smithb2997f52019-05-21 20:10:50 +0000983 /// Rebuild a DeclRefExpr for a VarDecl reference.
984 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000985
Richard Smithb2997f52019-05-21 20:10:50 +0000986 /// Transform a reference to a function or init-capture parameter pack.
987 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000988
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000989 /// Transform a FunctionParmPackExpr which was built when we couldn't
Richard Smithb15fe3a2012-09-12 00:56:43 +0000990 /// expand a function parameter pack reference which refers to an expanded
991 /// pack.
992 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
993
Hans Wennborge113c202014-09-18 16:01:32 +0000994 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
Richard Smith2e321552014-11-12 02:00:47 +0000995 FunctionProtoTypeLoc TL) {
996 // Call the base version; it will forward to our overridden version below.
997 return inherited::TransformFunctionProtoType(TLB, TL);
998 }
999
1000 template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +00001001 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1002 FunctionProtoTypeLoc TL,
1003 CXXRecordDecl *ThisContext,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001004 Qualifiers ThisTypeQuals,
Richard Smith2e321552014-11-12 02:00:47 +00001005 Fn TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +00001006
Douglas Gregor715e4612011-01-14 22:40:04 +00001007 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001008 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001009 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001010 bool ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +00001011
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001012 /// Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +00001013 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +00001014 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001015 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001016
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001017 /// Transforms an already-substituted template type parameter pack
Douglas Gregorada4b792011-01-14 02:55:32 +00001018 /// into either itself (if we aren't substituting into its pack expansion)
1019 /// or the appropriate substituted argument.
1020 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1021 SubstTemplateTypeParmPackTypeLoc TL);
1022
Richard Smith2589b9802012-07-25 03:56:55 +00001023 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1024 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1025 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
1026 }
1027
David Majnemerb1004102014-03-02 18:46:05 +00001028 TemplateParameterList *TransformTemplateParameterList(
Faisal Vali2cba1332013-10-23 06:44:28 +00001029 TemplateParameterList *OrigTPL) {
1030 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
Fangrui Song6907ce22018-07-30 19:24:48 +00001031
Faisal Vali2cba1332013-10-23 06:44:28 +00001032 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
Fangrui Song6907ce22018-07-30 19:24:48 +00001033 TemplateDeclInstantiator DeclInstantiator(getSema(),
Faisal Vali2cba1332013-10-23 06:44:28 +00001034 /* DeclContext *Owner */ Owner, TemplateArgs);
Fangrui Song6907ce22018-07-30 19:24:48 +00001035 return DeclInstantiator.SubstTemplateParams(OrigTPL);
Faisal Vali2cba1332013-10-23 06:44:28 +00001036 }
John McCall7c454bb2011-07-15 05:09:51 +00001037 private:
1038 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
1039 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001040 TemplateArgument arg);
Douglas Gregord6ff3322009-08-04 16:50:30 +00001041 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001042}
Douglas Gregor04318252009-07-06 15:59:29 +00001043
Douglas Gregor5597ab42010-05-07 23:12:07 +00001044bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1045 if (T.isNull())
1046 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00001047
Douglas Gregor678d76c2011-07-01 01:22:09 +00001048 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +00001049 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001050
Douglas Gregor5597ab42010-05-07 23:12:07 +00001051 getSema().MarkDeclarationsReferencedInType(Loc, T);
1052 return true;
1053}
1054
Eli Friedman8917ad52013-07-19 19:40:38 +00001055static TemplateArgument
1056getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001057 assert(S.ArgumentPackSubstitutionIndex >= 0);
Eli Friedman8917ad52013-07-19 19:40:38 +00001058 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1059 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
1060 if (Arg.isPackExpansion())
1061 Arg = Arg.getPackExpansionPattern();
1062 return Arg;
1063}
1064
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001065Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +00001066 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +00001067 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001068
Douglas Gregor2b6ca462009-09-03 21:38:09 +00001069 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +00001070 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +00001071 // If the corresponding template argument is NULL or non-existent, it's
1072 // because we are performing instantiation from explicitly-specified
1073 // template arguments in a function template, but there were some
1074 // arguments left unspecified.
1075 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1076 TTP->getPosition()))
1077 return D;
1078
Douglas Gregorf5500772011-01-05 15:48:55 +00001079 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
Fangrui Song6907ce22018-07-30 19:24:48 +00001080
Douglas Gregorf5500772011-01-05 15:48:55 +00001081 if (TTP->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001082 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregorf5500772011-01-05 15:48:55 +00001083 "Missing argument pack");
Eli Friedman8917ad52013-07-19 19:40:38 +00001084 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorf5500772011-01-05 15:48:55 +00001085 }
1086
Richard Smith1abacfc2017-08-29 22:14:43 +00001087 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001088 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +00001089 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001090 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001091 }
Mike Stump11289f42009-09-09 15:08:12 +00001092
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001093 // Fall through to find the instantiated declaration for this template
1094 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +00001095 }
Mike Stump11289f42009-09-09 15:08:12 +00001096
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001097 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +00001098}
1099
Douglas Gregor25289362010-03-01 17:25:41 +00001100Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +00001101 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +00001102 if (!Inst)
Craig Topperc3ec1492014-05-26 06:22:03 +00001103 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001104
Douglas Gregorebe10102009-08-20 07:17:43 +00001105 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1106 return Inst;
1107}
1108
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001109NamedDecl *
Fangrui Song6907ce22018-07-30 19:24:48 +00001110TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001111 SourceLocation Loc) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001112 // If the first part of the nested-name-specifier was a template type
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001113 // parameter, instantiate that type parameter down to a tag type.
1114 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001115 const TemplateTypeParmType *TTP
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001116 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Fangrui Song6907ce22018-07-30 19:24:48 +00001117
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001118 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001119 // FIXME: This needs testing w/ member access expressions.
1120 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
Fangrui Song6907ce22018-07-30 19:24:48 +00001121
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001122 if (TTP->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001123 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001124 "Missing argument pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001125
Douglas Gregore1d60df2011-01-14 23:41:42 +00001126 if (getSema().ArgumentPackSubstitutionIndex == -1)
Craig Topperc3ec1492014-05-26 06:22:03 +00001127 return nullptr;
1128
Eli Friedman8917ad52013-07-19 19:40:38 +00001129 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001130 }
1131
1132 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001133 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001134 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Fangrui Song6907ce22018-07-30 19:24:48 +00001135
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001136 if (const TagType *Tag = T->getAs<TagType>())
1137 return Tag->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001138
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001139 // The resulting type is not a tag; complain.
1140 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
Craig Topperc3ec1492014-05-26 06:22:03 +00001141 return nullptr;
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001142 }
1143 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001144
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001145 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001146}
1147
Douglas Gregorebe10102009-08-20 07:17:43 +00001148VarDecl *
1149TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +00001150 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001151 SourceLocation StartLoc,
1152 SourceLocation NameLoc,
1153 IdentifierInfo *Name) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00001154 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001155 StartLoc, NameLoc, Name);
Douglas Gregorf4e837f2010-04-26 17:57:08 +00001156 if (Var)
1157 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1158 return Var;
1159}
1160
Fangrui Song6907ce22018-07-30 19:24:48 +00001161VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1162 TypeSourceInfo *TSInfo,
Douglas Gregorf4e837f2010-04-26 17:57:08 +00001163 QualType T) {
1164 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1165 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +00001166 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1167 return Var;
1168}
1169
John McCall7f41d982009-09-11 04:59:25 +00001170QualType
John McCall954b5de2010-11-04 19:04:38 +00001171TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1172 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001173 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara6150c882010-05-11 21:36:43 +00001174 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +00001175 if (const TagType *TT = T->getAs<TagType>()) {
1176 TagDecl* TD = TT->getDecl();
1177
John McCall954b5de2010-11-04 19:04:38 +00001178 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +00001179
John McCall7f41d982009-09-11 04:59:25 +00001180 IdentifierInfo *Id = TD->getIdentifier();
1181
1182 // TODO: should we even warn on struct/class mismatches for this? Seems
1183 // like it's likely to produce a lot of spurious errors.
Richard Smith80b3c5a2012-08-17 00:12:27 +00001184 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001185 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieucaa33d32011-06-10 03:11:26 +00001186 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001187 TagLocation, Id)) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001188 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1189 << Id
1190 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1191 TD->getKindName());
1192 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1193 }
John McCall7f41d982009-09-11 04:59:25 +00001194 }
1195 }
1196
John McCall954b5de2010-11-04 19:04:38 +00001197 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1198 Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001199 QualifierLoc,
1200 T);
John McCall7f41d982009-09-11 04:59:25 +00001201}
1202
Richard Smithfd3dae02017-01-20 00:20:39 +00001203TemplateName TemplateInstantiator::TransformTemplateName(
1204 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1205 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1206 bool AllowInjectedClassName) {
Douglas Gregor9db53502011-03-02 18:07:45 +00001207 if (TemplateTemplateParmDecl *TTP
1208 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1209 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1210 // If the corresponding template argument is NULL or non-existent, it's
1211 // because we are performing instantiation from explicitly-specified
1212 // template arguments in a function template, but there were some
1213 // arguments left unspecified.
1214 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1215 TTP->getPosition()))
1216 return Name;
Fangrui Song6907ce22018-07-30 19:24:48 +00001217
Douglas Gregor9db53502011-03-02 18:07:45 +00001218 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
Fangrui Song6907ce22018-07-30 19:24:48 +00001219
Douglas Gregor9db53502011-03-02 18:07:45 +00001220 if (TTP->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001221 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregor9db53502011-03-02 18:07:45 +00001222 "Missing argument pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001223
Douglas Gregor9db53502011-03-02 18:07:45 +00001224 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1225 // We have the template argument pack to substitute, but we're not
1226 // actually expanding the enclosing pack expansion yet. So, just
1227 // keep the entire argument pack.
1228 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1229 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001230
1231 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor9db53502011-03-02 18:07:45 +00001232 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001233
Richard Smith1abacfc2017-08-29 22:14:43 +00001234 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001235 assert(!Template.isNull() && "Null template template argument");
Richard Smith1abacfc2017-08-29 22:14:43 +00001236 assert(!Template.getAsQualifiedTemplateName() &&
1237 "template decl to substitute is qualified?");
John McCalld9dfe3a2011-06-30 08:33:18 +00001238
1239 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregor9db53502011-03-02 18:07:45 +00001240 return Template;
1241 }
1242 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001243
Douglas Gregor9db53502011-03-02 18:07:45 +00001244 if (SubstTemplateTemplateParmPackStorage *SubstPack
1245 = Name.getAsSubstTemplateTemplateParmPack()) {
1246 if (getSema().ArgumentPackSubstitutionIndex == -1)
1247 return Name;
Fangrui Song6907ce22018-07-30 19:24:48 +00001248
Eli Friedman8917ad52013-07-19 19:40:38 +00001249 TemplateArgument Arg = SubstPack->getArgumentPack();
1250 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Richard Smith1abacfc2017-08-29 22:14:43 +00001251 return Arg.getAsTemplate().getNameToSubstitute();
Douglas Gregor9db53502011-03-02 18:07:45 +00001252 }
Richard Smithfd3dae02017-01-20 00:20:39 +00001253
1254 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1255 FirstQualifierInScope,
1256 AllowInjectedClassName);
Douglas Gregor9db53502011-03-02 18:07:45 +00001257}
1258
Fangrui Song6907ce22018-07-30 19:24:48 +00001259ExprResult
John McCall47f29ea2009-12-08 09:21:05 +00001260TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +00001261 if (!E->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001262 return E;
Anders Carlsson0b209a82009-09-11 01:22:35 +00001263
Bruno Ricci17ff0262018-10-27 19:21:19 +00001264 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
Anders Carlsson0b209a82009-09-11 01:22:35 +00001265}
1266
John McCalldadc5752010-08-24 06:29:42 +00001267ExprResult
John McCall13481c52010-02-06 08:42:39 +00001268TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001269 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +00001270 // If the corresponding template argument is NULL or non-existent, it's
1271 // because we are performing instantiation from explicitly-specified
1272 // template arguments in a function template, but there were some
1273 // arguments left unspecified.
1274 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1275 NTTP->getPosition()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001276 return E;
Mike Stump11289f42009-09-09 15:08:12 +00001277
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001278 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
Richard Smithb4f96252017-02-21 06:30:38 +00001279
1280 if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1281 // We're performing a partial substitution, so the substituted argument
1282 // could be dependent. As a result we can't create a SubstNonType*Expr
1283 // node now, since that represents a fully-substituted argument.
1284 // FIXME: We should have some AST representation for this.
1285 if (Arg.getKind() == TemplateArgument::Pack) {
1286 // FIXME: This won't work for alias templates.
1287 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1288 "unexpected pack arguments in partial substitution");
1289 Arg = Arg.pack_begin()->getPackExpansionPattern();
1290 }
1291 assert(Arg.getKind() == TemplateArgument::Expression &&
1292 "unexpected nontype template argument kind in partial substitution");
1293 return Arg.getAsExpr();
1294 }
1295
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001296 if (NTTP->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001297 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001298 "Missing argument pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001299
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001300 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001301 // We have an argument pack, but we can't select a particular argument
1302 // out of it yet. Therefore, we'll build an expression to hold on to that
1303 // argument pack.
1304 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
Fangrui Song6907ce22018-07-30 19:24:48 +00001305 E->getLocation(),
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001306 NTTP->getDeclName());
1307 if (TargetType.isNull())
1308 return ExprError();
Richard Smithf1f20e62018-02-14 02:07:53 +00001309
1310 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1311 TargetType.getNonLValueExprType(SemaRef.Context),
1312 TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP,
1313 E->getLocation(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001314 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001315
Eli Friedman8917ad52013-07-19 19:40:38 +00001316 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001317 }
Mike Stump11289f42009-09-09 15:08:12 +00001318
John McCall7c454bb2011-07-15 05:09:51 +00001319 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1320}
1321
Tyler Nowickic724a83e2014-10-12 20:46:07 +00001322const LoopHintAttr *
1323TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1324 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1325
1326 if (TransformedExpr == LH->getValue())
1327 return LH;
1328
1329 // Generate error if there is a problem with the value.
1330 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1331 return LH;
1332
1333 // Create new LoopHintValueAttr with integral expression in place of the
1334 // non-type template parameter.
Erich Keane6a24e802019-09-13 17:39:31 +00001335 return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
1336 LH->getState(), TransformedExpr, *LH);
Tyler Nowickic724a83e2014-10-12 20:46:07 +00001337}
1338
John McCall7c454bb2011-07-15 05:09:51 +00001339ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1340 NonTypeTemplateParmDecl *parm,
1341 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001342 TemplateArgument arg) {
John McCall7c454bb2011-07-15 05:09:51 +00001343 ExprResult result;
1344 QualType type;
1345
John McCall13481c52010-02-06 08:42:39 +00001346 // The template argument itself might be an expression, in which
1347 // case we just return that expression.
John McCall7c454bb2011-07-15 05:09:51 +00001348 if (arg.getKind() == TemplateArgument::Expression) {
1349 Expr *argExpr = arg.getAsExpr();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001350 result = argExpr;
John McCall7c454bb2011-07-15 05:09:51 +00001351 type = argExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001352
Eli Friedmanb826a002012-09-26 02:36:12 +00001353 } else if (arg.getKind() == TemplateArgument::Declaration ||
1354 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001355 ValueDecl *VD;
Eli Friedmanb826a002012-09-26 02:36:12 +00001356 if (arg.getKind() == TemplateArgument::Declaration) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00001357 VD = arg.getAsDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001358
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001359 // Find the instantiation of the template argument. This is
1360 // required for nested templates.
1361 VD = cast_or_null<ValueDecl>(
1362 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1363 if (!VD)
1364 return ExprError();
1365 } else {
1366 // Propagate NULL template argument.
Craig Topperc3ec1492014-05-26 06:22:03 +00001367 VD = nullptr;
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001368 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001369
John McCall15dda372010-02-06 10:23:53 +00001370 // Derive the type we want the substituted decl to have. This had
1371 // better be non-dependent, or these checks will have serious problems.
John McCall7c454bb2011-07-15 05:09:51 +00001372 if (parm->isExpandedParameterPack()) {
1373 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
Fangrui Song6907ce22018-07-30 19:24:48 +00001374 } else if (parm->isParameterPack() &&
John McCall7c454bb2011-07-15 05:09:51 +00001375 isa<PackExpansionType>(parm->getType())) {
1376 type = SemaRef.SubstType(
1377 cast<PackExpansionType>(parm->getType())->getPattern(),
1378 TemplateArgs, loc, parm->getDeclName());
1379 } else {
Richard Smith5f274382016-09-28 23:55:27 +00001380 type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1381 TemplateArgs, loc, parm->getDeclName());
John McCall7c454bb2011-07-15 05:09:51 +00001382 }
1383 assert(!type.isNull() && "type substitution failed for param type");
1384 assert(!type->isDependentType() && "param type still dependent");
1385 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCall13481c52010-02-06 08:42:39 +00001386
John McCall7c454bb2011-07-15 05:09:51 +00001387 if (!result.isInvalid()) type = result.get()->getType();
1388 } else {
1389 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1390
1391 // Note that this type can be different from the type of 'result',
1392 // e.g. if it's an enum type.
1393 type = arg.getIntegralType();
1394 }
1395 if (result.isInvalid()) return ExprError();
1396
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001397 Expr *resultExpr = result.get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001398 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1399 type, resultExpr->getValueKind(), loc, parm, resultExpr);
John McCall13481c52010-02-06 08:42:39 +00001400}
Fangrui Song6907ce22018-07-30 19:24:48 +00001401
1402ExprResult
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001403TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1404 SubstNonTypeTemplateParmPackExpr *E) {
1405 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1406 // We aren't expanding the parameter pack, so just return ourselves.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001407 return E;
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001408 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001409
1410 TemplateArgument Arg = E->getArgumentPack();
1411 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall7c454bb2011-07-15 05:09:51 +00001412 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1413 E->getParameterPackLocation(),
1414 Arg);
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001415}
John McCall13481c52010-02-06 08:42:39 +00001416
Richard Smithb2997f52019-05-21 20:10:50 +00001417ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
1418 SourceLocation Loc) {
Richard Smithb15fe3a2012-09-12 00:56:43 +00001419 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1420 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1421}
1422
1423ExprResult
1424TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1425 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1426 // We can expand this parameter pack now.
Richard Smithb2997f52019-05-21 20:10:50 +00001427 VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1428 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
Richard Smithb15fe3a2012-09-12 00:56:43 +00001429 if (!VD)
1430 return ExprError();
Richard Smithb2997f52019-05-21 20:10:50 +00001431 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
Richard Smithb15fe3a2012-09-12 00:56:43 +00001432 }
1433
1434 QualType T = TransformType(E->getType());
1435 if (T.isNull())
1436 return ExprError();
1437
1438 // Transform each of the parameter expansions into the corresponding
1439 // parameters in the instantiation of the function decl.
Richard Smithb2997f52019-05-21 20:10:50 +00001440 SmallVector<VarDecl *, 8> Vars;
1441 Vars.reserve(E->getNumExpansions());
Richard Smithb15fe3a2012-09-12 00:56:43 +00001442 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1443 I != End; ++I) {
Richard Smithb2997f52019-05-21 20:10:50 +00001444 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
Richard Smithb15fe3a2012-09-12 00:56:43 +00001445 if (!D)
1446 return ExprError();
Richard Smithb2997f52019-05-21 20:10:50 +00001447 Vars.push_back(D);
Richard Smithb15fe3a2012-09-12 00:56:43 +00001448 }
1449
Richard Smith7bf8f6f2019-06-04 17:17:20 +00001450 auto *PackExpr =
1451 FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
1452 E->getParameterPackLocation(), Vars);
1453 getSema().MarkFunctionParmPackReferenced(PackExpr);
1454 return PackExpr;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001455}
1456
1457ExprResult
1458TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
Richard Smithb2997f52019-05-21 20:10:50 +00001459 VarDecl *PD) {
Richard Smithb15fe3a2012-09-12 00:56:43 +00001460 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1461 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1462 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1463 assert(Found && "no instantiation for parameter pack");
1464
1465 Decl *TransformedDecl;
1466 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
Nico Weberc153d242014-07-28 00:02:09 +00001467 // If this is a reference to a function parameter pack which we can
1468 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
Richard Smithb15fe3a2012-09-12 00:56:43 +00001469 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1470 QualType T = TransformType(E->getType());
1471 if (T.isNull())
1472 return ExprError();
Richard Smith7bf8f6f2019-06-04 17:17:20 +00001473 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
1474 E->getExprLoc(), *Pack);
1475 getSema().MarkFunctionParmPackReferenced(PackExpr);
1476 return PackExpr;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001477 }
1478
1479 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1480 } else {
1481 TransformedDecl = Found->get<Decl*>();
1482 }
1483
1484 // We have either an unexpanded pack or a specific expansion.
Richard Smithb2997f52019-05-21 20:10:50 +00001485 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
Richard Smithb15fe3a2012-09-12 00:56:43 +00001486}
1487
1488ExprResult
John McCall13481c52010-02-06 08:42:39 +00001489TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1490 NamedDecl *D = E->getDecl();
Richard Smithb15fe3a2012-09-12 00:56:43 +00001491
1492 // Handle references to non-type template parameters and non-type template
1493 // parameter packs.
John McCall13481c52010-02-06 08:42:39 +00001494 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1495 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1496 return TransformTemplateParmRefExpr(E, NTTP);
Fangrui Song6907ce22018-07-30 19:24:48 +00001497
Douglas Gregor954de172009-10-31 17:21:17 +00001498 // We have a non-type template parameter that isn't fully substituted;
1499 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001500 }
Mike Stump11289f42009-09-09 15:08:12 +00001501
Richard Smithb15fe3a2012-09-12 00:56:43 +00001502 // Handle references to function parameter packs.
Richard Smithb2997f52019-05-21 20:10:50 +00001503 if (VarDecl *PD = dyn_cast<VarDecl>(D))
Richard Smithb15fe3a2012-09-12 00:56:43 +00001504 if (PD->isParameterPack())
1505 return TransformFunctionParmPackRefExpr(E, PD);
1506
John McCall47f29ea2009-12-08 09:21:05 +00001507 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001508}
1509
John McCalldadc5752010-08-24 06:29:42 +00001510ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001511 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001512 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1513 getDescribedFunctionTemplate() &&
1514 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001515 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
Fangrui Song6907ce22018-07-30 19:24:48 +00001516 cast<FunctionDecl>(E->getParam()->getDeclContext()),
Douglas Gregor033f6752009-12-23 23:03:06 +00001517 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001518}
1519
Richard Smith2e321552014-11-12 02:00:47 +00001520template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +00001521QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1522 FunctionProtoTypeLoc TL,
1523 CXXRecordDecl *ThisContext,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001524 Qualifiers ThisTypeQuals,
Richard Smith2e321552014-11-12 02:00:47 +00001525 Fn TransformExceptionSpec) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001526 // We need a local instantiation scope for this function prototype.
1527 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
Richard Smith2e321552014-11-12 02:00:47 +00001528 return inherited::TransformFunctionProtoType(
1529 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +00001530}
1531
John McCall58f10c32010-03-11 09:03:00 +00001532ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001533TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001534 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001535 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001536 bool ExpectParameterPack) {
Anastasia Stulovaa29aa472019-11-27 11:03:11 +00001537 auto NewParm =
1538 SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1539 NumExpansions, ExpectParameterPack);
1540 if (NewParm && SemaRef.getLangOpts().OpenCL)
1541 SemaRef.deduceOpenCLAddressSpace(NewParm);
1542 return NewParm;
John McCall58f10c32010-03-11 09:03:00 +00001543}
1544
Mike Stump11289f42009-09-09 15:08:12 +00001545QualType
John McCall550e0c22009-10-21 00:40:46 +00001546TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001547 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001548 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001549 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001550 // Replace the template type parameter with its corresponding
1551 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001552
1553 // If the corresponding template argument is NULL or doesn't exist, it's
1554 // because we are performing instantiation from explicitly-specified
1555 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001556 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001557 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1558 TemplateTypeParmTypeLoc NewTL
1559 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1560 NewTL.setNameLoc(TL.getNameLoc());
1561 return TL.getType();
1562 }
Mike Stump11289f42009-09-09 15:08:12 +00001563
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001564 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
Fangrui Song6907ce22018-07-30 19:24:48 +00001565
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001566 if (T->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001567 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001568 "Missing argument pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001569
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001570 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001571 // We have the template argument pack, but we're not expanding the
1572 // enclosing pack expansion yet. Just save the template argument
1573 // pack for later substitution.
1574 QualType Result
1575 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1576 SubstTemplateTypeParmPackTypeLoc NewTL
1577 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1578 NewTL.setNameLoc(TL.getNameLoc());
1579 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001580 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001581
Eli Friedman8917ad52013-07-19 19:40:38 +00001582 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001583 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001584
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001585 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001586 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001587
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001588 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001589
1590 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001591 QualType Result
1592 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1593 SubstTemplateTypeParmTypeLoc NewTL
1594 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1595 NewTL.setNameLoc(TL.getNameLoc());
1596 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001597 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001598
1599 // The template type parameter comes from an inner template (e.g.,
1600 // the template parameter list of a member template inside the
1601 // template we are instantiating). Create a new template type
1602 // parameter with the template "level" reduced by one.
Craig Topperc3ec1492014-05-26 06:22:03 +00001603 TemplateTypeParmDecl *NewTTPDecl = nullptr;
Chandler Carruth08836322011-05-01 00:51:33 +00001604 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1605 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1606 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1607
Richard Smithb4f96252017-02-21 06:30:38 +00001608 QualType Result = getSema().Context.getTemplateTypeParmType(
1609 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1610 T->isParameterPack(), NewTTPDecl);
John McCall550e0c22009-10-21 00:40:46 +00001611 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1612 NewTL.setNameLoc(TL.getNameLoc());
1613 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001614}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001615
Fangrui Song6907ce22018-07-30 19:24:48 +00001616QualType
Douglas Gregorada4b792011-01-14 02:55:32 +00001617TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1618 TypeLocBuilder &TLB,
1619 SubstTemplateTypeParmPackTypeLoc TL) {
1620 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1621 // We aren't expanding the parameter pack, so just return ourselves.
1622 SubstTemplateTypeParmPackTypeLoc NewTL
1623 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1624 NewTL.setNameLoc(TL.getNameLoc());
1625 return TL.getType();
1626 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001627
1628 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1629 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1630 QualType Result = Arg.getAsType();
1631
Douglas Gregorada4b792011-01-14 02:55:32 +00001632 Result = getSema().Context.getSubstTemplateTypeParmType(
1633 TL.getTypePtr()->getReplacedParameter(),
1634 Result);
1635 SubstTemplateTypeParmTypeLoc NewTL
1636 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1637 NewTL.setNameLoc(TL.getNameLoc());
1638 return Result;
1639}
1640
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001641/// Perform substitution on the type T with a given set of template
John McCall76d824f2009-08-25 22:02:44 +00001642/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001643///
1644/// This routine substitutes the given template arguments into the
1645/// type T and produces the instantiated type.
1646///
1647/// \param T the type into which the template arguments will be
1648/// substituted. If this type is not dependent, it will be returned
1649/// immediately.
1650///
James Dennett634962f2012-06-14 21:40:34 +00001651/// \param Args the template arguments that will be
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001652/// substituted for the top-level template parameters within T.
1653///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001654/// \param Loc the location in the source code where this substitution
1655/// is being performed. It will typically be the location of the
1656/// declarator (if we're instantiating the type of some declaration)
1657/// or the location of the type in the source code (if, e.g., we're
1658/// instantiating the type of a cast expression).
1659///
1660/// \param Entity the name of the entity associated with a declaration
1661/// being instantiated (if any). May be empty to indicate that there
1662/// is no such entity (if, e.g., this is a type that occurs as part of
1663/// a cast expression) or that the entity has no name (e.g., an
1664/// unnamed function parameter).
1665///
Richard Smithee579842017-01-30 20:39:26 +00001666/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1667/// acceptable as the top level type of the result.
1668///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001669/// \returns If the instantiation succeeds, the instantiated
1670/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001671TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001672 const MultiLevelTemplateArgumentList &Args,
1673 SourceLocation Loc,
Richard Smithee579842017-01-30 20:39:26 +00001674 DeclarationName Entity,
1675 bool AllowDeducedTST) {
Richard Smith696e3122017-02-23 01:43:54 +00001676 assert(!CodeSynthesisContexts.empty() &&
John McCall609459e2009-10-21 00:58:09 +00001677 "Cannot perform an instantiation without some context on the "
1678 "instantiation stack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001679
1680 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001681 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001682 return T;
1683
1684 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
Richard Smithee579842017-01-30 20:39:26 +00001685 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
1686 : Instantiator.TransformType(T);
John McCall609459e2009-10-21 00:58:09 +00001687}
1688
Douglas Gregor5499af42011-01-05 23:12:31 +00001689TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1690 const MultiLevelTemplateArgumentList &Args,
1691 SourceLocation Loc,
1692 DeclarationName Entity) {
Richard Smith696e3122017-02-23 01:43:54 +00001693 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001694 "Cannot perform an instantiation without some context on the "
1695 "instantiation stack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001696
Douglas Gregor5499af42011-01-05 23:12:31 +00001697 if (TL.getType().isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001698 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001699
Fangrui Song6907ce22018-07-30 19:24:48 +00001700 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001701 !TL.getType()->isVariablyModifiedType()) {
1702 // FIXME: Make a copy of the TypeLoc data here, so that we can
1703 // return a new TypeSourceInfo. Inefficient!
1704 TypeLocBuilder TLB;
1705 TLB.pushFullCopy(TL);
1706 return TLB.getTypeSourceInfo(Context, TL.getType());
1707 }
1708
1709 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1710 TypeLocBuilder TLB;
1711 TLB.reserve(TL.getFullDataSize());
1712 QualType Result = Instantiator.TransformType(TLB, TL);
1713 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001714 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001715
1716 return TLB.getTypeSourceInfo(Context, Result);
1717}
1718
John McCall609459e2009-10-21 00:58:09 +00001719/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001720QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001721 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001722 SourceLocation Loc, DeclarationName Entity) {
Richard Smith696e3122017-02-23 01:43:54 +00001723 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregor79cf6032009-03-10 20:44:00 +00001724 "Cannot perform an instantiation without some context on the "
1725 "instantiation stack");
1726
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001727 // If T is not a dependent type or a variably-modified type, there
1728 // is nothing to do.
Douglas Gregor678d76c2011-07-01 01:22:09 +00001729 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001730 return T;
1731
Douglas Gregord6ff3322009-08-04 16:50:30 +00001732 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1733 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001734}
Douglas Gregor463421d2009-03-03 04:44:36 +00001735
John McCallb29f78f2010-04-09 17:38:44 +00001736static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Nico Weberc0973372016-02-01 22:31:51 +00001737 if (T->getType()->isInstantiationDependentType() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00001738 T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001739 return true;
1740
Abramo Bagnara6d810632010-12-14 22:11:44 +00001741 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00001742 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCallb29f78f2010-04-09 17:38:44 +00001743 return false;
1744
David Blaikie6adc78e2013-02-18 22:06:02 +00001745 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Nico Weberc0973372016-02-01 22:31:51 +00001746 for (ParmVarDecl *P : FP.getParams()) {
Reid Klecknera09e44c2013-07-31 21:00:18 +00001747 // This must be synthesized from a typedef.
1748 if (!P) continue;
1749
Nico Weberc0973372016-02-01 22:31:51 +00001750 // If there are any parameters, a new TypeSourceInfo that refers to the
1751 // instantiated parameters must be built.
1752 return true;
John McCallb29f78f2010-04-09 17:38:44 +00001753 }
1754
1755 return false;
1756}
1757
1758/// A form of SubstType intended specifically for instantiating the
1759/// type of a FunctionDecl. Its purpose is solely to force the
Richard Smith2e321552014-11-12 02:00:47 +00001760/// instantiation of default-argument expressions and to avoid
1761/// instantiating an exception-specification.
John McCallb29f78f2010-04-09 17:38:44 +00001762TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1763 const MultiLevelTemplateArgumentList &Args,
1764 SourceLocation Loc,
Douglas Gregor3024f072012-04-16 07:05:22 +00001765 DeclarationName Entity,
1766 CXXRecordDecl *ThisContext,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001767 Qualifiers ThisTypeQuals) {
Richard Smith696e3122017-02-23 01:43:54 +00001768 assert(!CodeSynthesisContexts.empty() &&
John McCallb29f78f2010-04-09 17:38:44 +00001769 "Cannot perform an instantiation without some context on the "
1770 "instantiation stack");
Nico Weberc0973372016-02-01 22:31:51 +00001771
John McCallb29f78f2010-04-09 17:38:44 +00001772 if (!NeedsInstantiationAsFunctionType(T))
1773 return T;
1774
1775 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1776
1777 TypeLocBuilder TLB;
1778
1779 TypeLoc TL = T->getTypeLoc();
1780 TLB.reserve(TL.getFullDataSize());
1781
Douglas Gregor3024f072012-04-16 07:05:22 +00001782 QualType Result;
David Blaikie6adc78e2013-02-18 22:06:02 +00001783
Richard Smith2e321552014-11-12 02:00:47 +00001784 if (FunctionProtoTypeLoc Proto =
1785 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1786 // Instantiate the type, other than its exception specification. The
1787 // exception specification is instantiated in InitFunctionInstantiation
1788 // once we've built the FunctionDecl.
1789 // FIXME: Set the exception specification to EST_Uninstantiated here,
1790 // instead of rebuilding the function type again later.
1791 Result = Instantiator.TransformFunctionProtoType(
1792 TLB, Proto, ThisContext, ThisTypeQuals,
1793 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1794 bool &Changed) { return false; });
Douglas Gregor3024f072012-04-16 07:05:22 +00001795 } else {
1796 Result = Instantiator.TransformType(TLB, TL);
1797 }
John McCallb29f78f2010-04-09 17:38:44 +00001798 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001799 return nullptr;
John McCallb29f78f2010-04-09 17:38:44 +00001800
1801 return TLB.getTypeSourceInfo(Context, Result);
1802}
1803
Richard Smithcd198152017-06-07 21:46:22 +00001804bool Sema::SubstExceptionSpec(SourceLocation Loc,
1805 FunctionProtoType::ExceptionSpecInfo &ESI,
1806 SmallVectorImpl<QualType> &ExceptionStorage,
1807 const MultiLevelTemplateArgumentList &Args) {
1808 assert(ESI.Type != EST_Uninstantiated);
1809
1810 bool Changed = false;
1811 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
1812 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
1813 Changed);
1814}
1815
Richard Smith2e321552014-11-12 02:00:47 +00001816void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1817 const MultiLevelTemplateArgumentList &Args) {
1818 FunctionProtoType::ExceptionSpecInfo ESI =
1819 Proto->getExtProtoInfo().ExceptionSpec;
Richard Smith2e321552014-11-12 02:00:47 +00001820
1821 SmallVector<QualType, 4> ExceptionStorage;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001822 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
Richard Smithcd198152017-06-07 21:46:22 +00001823 ESI, ExceptionStorage, Args))
Richard Smith2e321552014-11-12 02:00:47 +00001824 // On error, recover by dropping the exception specification.
1825 ESI.Type = EST_None;
1826
1827 UpdateExceptionSpec(New, ESI);
1828}
1829
Fangrui Song6907ce22018-07-30 19:24:48 +00001830ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001831 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall8fb0d9d2011-05-01 22:35:37 +00001832 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001833 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001834 bool ExpectParameterPack) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001835 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Craig Topperc3ec1492014-05-26 06:22:03 +00001836 TypeSourceInfo *NewDI = nullptr;
1837
Douglas Gregor5499af42011-01-05 23:12:31 +00001838 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00001839 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1840
Fangrui Song6907ce22018-07-30 19:24:48 +00001841 // We have a function parameter pack. Substitute into the pattern of the
Douglas Gregor5499af42011-01-05 23:12:31 +00001842 // expansion.
Fangrui Song6907ce22018-07-30 19:24:48 +00001843 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
Douglas Gregor5499af42011-01-05 23:12:31 +00001844 OldParm->getLocation(), OldParm->getDeclName());
1845 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001846 return nullptr;
1847
Douglas Gregor5499af42011-01-05 23:12:31 +00001848 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1849 // We still have unexpanded parameter packs, which means that
1850 // our function parameter is still a function parameter pack.
1851 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001852 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001853 NumExpansions);
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001854 } else if (ExpectParameterPack) {
1855 // We expected to get a parameter pack but didn't (because the type
1856 // itself is not a pack expansion type), so complain. This can occur when
1857 // the substitution goes through an alias template that "loses" the
1858 // pack expansion.
Fangrui Song6907ce22018-07-30 19:24:48 +00001859 Diag(OldParm->getLocation(),
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001860 diag::err_function_parameter_pack_without_parameter_packs)
1861 << NewDI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001862 return nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +00001863 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001864 } else {
Fangrui Song6907ce22018-07-30 19:24:48 +00001865 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
Douglas Gregor5499af42011-01-05 23:12:31 +00001866 OldParm->getDeclName());
1867 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001868
Douglas Gregor940bca72010-04-12 07:48:19 +00001869 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001870 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001871
1872 if (NewDI->getType()->isVoidType()) {
1873 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
Craig Topperc3ec1492014-05-26 06:22:03 +00001874 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001875 }
1876
1877 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001878 OldParm->getInnerLocStart(),
Douglas Gregor940bca72010-04-12 07:48:19 +00001879 OldParm->getLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001880 OldParm->getIdentifier(),
1881 NewDI->getType(), NewDI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001882 OldParm->getStorageClass());
Douglas Gregor940bca72010-04-12 07:48:19 +00001883 if (!NewParm)
Craig Topperc3ec1492014-05-26 06:22:03 +00001884 return nullptr;
1885
Douglas Gregor940bca72010-04-12 07:48:19 +00001886 // Mark the (new) default argument as uninstantiated (if any).
1887 if (OldParm->hasUninstantiatedDefaultArg()) {
1888 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1889 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001890 } else if (OldParm->hasUnparsedDefaultArg()) {
1891 NewParm->setUnparsedDefaultArg();
1892 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001893 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1894 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
Serge Pavlov73c6a242015-08-23 10:22:28 +00001895 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1896 // Instantiate default arguments for methods of local classes (DR1484)
1897 // and non-defining declarations.
1898 Sema::ContextRAII SavedContext(*this, OwningFunc);
Akira Hatanakad644e022016-12-16 03:19:41 +00001899 LocalInstantiationScope Local(*this, true);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001900 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
John McCalldc40b612015-12-11 01:56:36 +00001901 if (NewArg.isUsable()) {
1902 // It would be nice if we still had this.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001903 SourceLocation EqualLoc = NewArg.get()->getBeginLoc();
John McCalldc40b612015-12-11 01:56:36 +00001904 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1905 }
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001906 } else {
1907 // FIXME: if we non-lazily instantiated non-dependent default args for
1908 // non-dependent parameter types we could remove a bunch of duplicate
1909 // conversion warnings for such arguments.
1910 NewParm->setUninstantiatedDefaultArg(Arg);
1911 }
1912 }
Douglas Gregor940bca72010-04-12 07:48:19 +00001913
1914 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Fangrui Song6907ce22018-07-30 19:24:48 +00001915
Douglas Gregorf3010112011-01-07 16:43:16 +00001916 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smith928be492012-01-25 02:14:59 +00001917 // Add the new parameter to the instantiated parameter pack.
Douglas Gregorf3010112011-01-07 16:43:16 +00001918 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1919 } else {
1920 // Introduce an Old -> New mapping
Fangrui Song6907ce22018-07-30 19:24:48 +00001921 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001922 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001923
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001924 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1925 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001926 NewParm->setDeclContext(CurContext);
John McCall8fb0d9d2011-05-01 22:35:37 +00001927
1928 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1929 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rosea0a86be2013-03-08 22:25:36 +00001930
1931 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1932
Fangrui Song6907ce22018-07-30 19:24:48 +00001933 return NewParm;
Douglas Gregor940bca72010-04-12 07:48:19 +00001934}
1935
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001936/// Substitute the given template arguments into the given set of
Douglas Gregordd472162011-01-07 00:20:55 +00001937/// parameters, producing the set of parameter types that would be generated
1938/// from such a substitution.
David Majnemer59f77922016-06-24 04:05:48 +00001939bool Sema::SubstParmTypes(
1940 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1941 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1942 const MultiLevelTemplateArgumentList &TemplateArgs,
1943 SmallVectorImpl<QualType> &ParamTypes,
1944 SmallVectorImpl<ParmVarDecl *> *OutParams,
1945 ExtParameterInfoBuilder &ParamInfos) {
Richard Smith696e3122017-02-23 01:43:54 +00001946 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregordd472162011-01-07 00:20:55 +00001947 "Cannot perform an instantiation without some context on the "
1948 "instantiation stack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001949
1950 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
Douglas Gregordd472162011-01-07 00:20:55 +00001951 DeclarationName());
David Majnemer59f77922016-06-24 04:05:48 +00001952 return Instantiator.TransformFunctionTypeParams(
1953 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
Douglas Gregordd472162011-01-07 00:20:55 +00001954}
1955
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001956/// Perform substitution on the base class specifiers of the
John McCall76d824f2009-08-25 22:02:44 +00001957/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001958///
1959/// Produces a diagnostic and returns true on error, returns false and
1960/// attaches the instantiated base classes to the class template
1961/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001962bool
John McCall76d824f2009-08-25 22:02:44 +00001963Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1964 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001965 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001966 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001967 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Richard Trieub5841332015-04-15 01:21:42 +00001968 for (const auto &Base : Pattern->bases()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001969 if (!Base.getType()->isDependentType()) {
1970 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay76d0b462013-06-21 18:58:32 +00001971 if (RD->isInvalidDecl())
1972 Instantiation->setInvalidDecl();
1973 }
Aaron Ballman574705e2014-03-13 15:41:46 +00001974 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001975 continue;
1976 }
1977
Douglas Gregor752a5952011-01-03 22:36:02 +00001978 SourceLocation EllipsisLoc;
Douglas Gregorc52264e2011-03-02 02:04:06 +00001979 TypeSourceInfo *BaseTypeLoc;
Aaron Ballman574705e2014-03-13 15:41:46 +00001980 if (Base.isPackExpansion()) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001981 // This is a pack expansion. See whether we should expand it now, or
1982 // wait until later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001983 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Aaron Ballman574705e2014-03-13 15:41:46 +00001984 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001985 Unexpanded);
1986 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001987 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001988 Optional<unsigned> NumExpansions;
Fangrui Song6907ce22018-07-30 19:24:48 +00001989 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
Aaron Ballman574705e2014-03-13 15:41:46 +00001990 Base.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001991 Unexpanded,
Fangrui Song6907ce22018-07-30 19:24:48 +00001992 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001993 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001994 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001995 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001996 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001997 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001998
Douglas Gregor752a5952011-01-03 22:36:02 +00001999 // If we should expand this pack expansion now, do so.
2000 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002001 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00002002 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
Fangrui Song6907ce22018-07-30 19:24:48 +00002003
Aaron Ballman574705e2014-03-13 15:41:46 +00002004 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor752a5952011-01-03 22:36:02 +00002005 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00002006 Base.getSourceRange().getBegin(),
Douglas Gregor752a5952011-01-03 22:36:02 +00002007 DeclarationName());
2008 if (!BaseTypeLoc) {
2009 Invalid = true;
2010 continue;
2011 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002012
Douglas Gregor752a5952011-01-03 22:36:02 +00002013 if (CXXBaseSpecifier *InstantiatedBase
2014 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00002015 Base.getSourceRange(),
2016 Base.isVirtual(),
2017 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00002018 BaseTypeLoc,
2019 SourceLocation()))
2020 InstantiatedBases.push_back(InstantiatedBase);
2021 else
2022 Invalid = true;
2023 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002024
Douglas Gregor752a5952011-01-03 22:36:02 +00002025 continue;
2026 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002027
Douglas Gregor752a5952011-01-03 22:36:02 +00002028 // The resulting base specifier will (still) be a pack expansion.
Aaron Ballman574705e2014-03-13 15:41:46 +00002029 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregorc52264e2011-03-02 02:04:06 +00002030 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Aaron Ballman574705e2014-03-13 15:41:46 +00002031 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00002032 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00002033 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00002034 DeclarationName());
2035 } else {
Aaron Ballman574705e2014-03-13 15:41:46 +00002036 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00002037 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00002038 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00002039 DeclarationName());
Douglas Gregor752a5952011-01-03 22:36:02 +00002040 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002041
Nick Lewycky19b9f952010-07-26 16:56:01 +00002042 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00002043 Invalid = true;
2044 continue;
2045 }
2046
2047 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002048 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00002049 Base.getSourceRange(),
2050 Base.isVirtual(),
2051 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00002052 BaseTypeLoc,
2053 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00002054 InstantiatedBases.push_back(InstantiatedBase);
2055 else
2056 Invalid = true;
2057 }
2058
Craig Topperaa700cb2015-12-27 21:55:19 +00002059 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
Douglas Gregor463421d2009-03-03 04:44:36 +00002060 Invalid = true;
2061
2062 return Invalid;
2063}
2064
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002065// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00002066namespace clang {
2067 namespace sema {
2068 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
2069 const MultiLevelTemplateArgumentList &TemplateArgs);
Erich Keanea32910d2017-03-23 18:51:54 +00002070 Attr *instantiateTemplateAttributeForDecl(
2071 const Attr *At, ASTContext &C, Sema &S,
2072 const MultiLevelTemplateArgumentList &TemplateArgs);
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00002073 }
2074}
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002075
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002076/// Instantiate the definition of a class from a given pattern.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002077///
2078/// \param PointOfInstantiation The point of instantiation within the
2079/// source code.
2080///
2081/// \param Instantiation is the declaration whose definition is being
2082/// instantiated. This will be either a class template specialization
2083/// or a member class of a class template specialization.
2084///
2085/// \param Pattern is the pattern from which the instantiation
2086/// occurs. This will be either the declaration of a class template or
2087/// the declaration of a member class of a class template.
2088///
2089/// \param TemplateArgs The template arguments to be substituted into
2090/// the pattern.
2091///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002092/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002093///
2094/// \param Complain whether to complain if the class cannot be instantiated due
2095/// to the lack of a definition.
2096///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002097/// \returns true if an error occurred, false otherwise.
2098bool
2099Sema::InstantiateClass(SourceLocation PointOfInstantiation,
2100 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002101 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002102 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002103 bool Complain) {
Mike Stump11289f42009-09-09 15:08:12 +00002104 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002105 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Vassil Vassilevb21ee082016-08-18 22:01:25 +00002106 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00002107 Instantiation->getInstantiatedFromMemberClass(),
2108 Pattern, PatternDef, TSK, Complain))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002109 return true;
Anton Afanasyevd880de22019-03-30 08:42:48 +00002110
2111 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
Lubos Lunakab8cde42019-05-12 10:39:21 +00002112 std::string Name;
2113 llvm::raw_string_ostream OS(Name);
2114 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
2115 /*Qualified=*/true);
2116 return Name;
Anton Afanasyevd880de22019-03-30 08:42:48 +00002117 });
2118
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002119 Pattern = PatternDef;
2120
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002121 // Record the point of instantiation.
Fangrui Song6907ce22018-07-30 19:24:48 +00002122 if (MemberSpecializationInfo *MSInfo
Douglas Gregord6ba93d2009-10-15 15:54:05 +00002123 = Instantiation->getMemberSpecializationInfo()) {
2124 MSInfo->setTemplateSpecializationKind(TSK);
2125 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Fangrui Song6907ce22018-07-30 19:24:48 +00002126 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weber3ffc4c92011-12-20 20:32:49 +00002127 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregoref6ab412009-10-27 06:26:26 +00002128 Spec->setTemplateSpecializationKind(TSK);
2129 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00002130 }
Richard Smitha1087602014-03-10 00:04:29 +00002131
Douglas Gregorf3430ae2009-03-25 21:23:52 +00002132 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002133 if (Inst.isInvalid())
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002134 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002135 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
Jordan Rose1e879d82018-03-23 00:07:18 +00002136 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00002137 "instantiating class definition");
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002138
2139 // Enter the scope of this instantiation. We don't use
2140 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00002141 ContextRAII SavedContext(*this, Instantiation);
Faisal Valid143a0c2017-04-01 21:30:49 +00002142 EnterExpressionEvaluationContext EvalContext(
2143 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002144
Douglas Gregor51121572010-03-24 01:33:17 +00002145 // If this is an instantiation of a local class, merge this local
2146 // instantiation scope with the enclosing scope. Otherwise, every
2147 // instantiation of a class has its own local instantiation scope.
2148 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00002149 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00002150
Volodymyr Sapsai4fbaa622017-09-21 19:54:12 +00002151 // Some class state isn't processed immediately but delayed till class
2152 // instantiation completes. We may not be ready to handle any delayed state
2153 // already on the stack as it might correspond to a different class, so save
2154 // it now and put it back later.
2155 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
Reid Kleckner5b640342016-02-26 19:51:02 +00002156
John McCall6602bb12010-08-01 02:01:53 +00002157 // Pull attributes from the pattern onto the instantiation.
2158 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2159
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002160 // Start the definition of this instantiation.
2161 Instantiation->startDefinition();
Richard Smitha1087602014-03-10 00:04:29 +00002162
2163 // The instantiation is visible here, even if it was first declared in an
2164 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00002165 Instantiation->setVisibleDespiteOwningModule();
Richard Smitha1087602014-03-10 00:04:29 +00002166
2167 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregore9029562010-05-06 00:28:52 +00002168 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002169
John McCall76d824f2009-08-25 22:02:44 +00002170 // Do substitution on the base class specifiers.
2171 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002172 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002173
Douglas Gregor869853e2010-11-10 19:44:59 +00002174 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002175 SmallVector<Decl*, 4> Fields;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002176 // Delay instantiation of late parsed attributes.
2177 LateInstantiatedAttrVec LateAttrs;
2178 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2179
Richard Smith921f1322019-05-13 23:35:21 +00002180 bool MightHaveConstexprVirtualFunctions = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002181 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002182 // Don't instantiate members not belonging in this semantic context.
2183 // e.g. for:
2184 // @code
2185 // template <int i> class A {
2186 // class B *g;
2187 // };
2188 // @endcode
2189 // 'class B' has the template as lexical context but semantically it is
2190 // introduced in namespace scope.
Aaron Ballman629afae2014-03-07 19:56:05 +00002191 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002192 continue;
2193
Erik Pilkingtona3a462e2018-07-23 22:47:37 +00002194 // BlockDecls can appear in a default-member-initializer. They must be the
2195 // child of a BlockExpr, so we only know how to instantiate them from there.
2196 if (isa<BlockDecl>(Member))
2197 continue;
2198
Aaron Ballman629afae2014-03-07 19:56:05 +00002199 if (Member->isInvalidDecl()) {
Richard Smithded9c2e2012-07-11 22:37:56 +00002200 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002201 continue;
2202 }
2203
Aaron Ballman629afae2014-03-07 19:56:05 +00002204 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002205 if (NewMember) {
Richard Smith938f40b2011-06-11 17:19:42 +00002206 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCall48871652010-08-21 09:40:31 +00002207 Fields.push_back(Field);
Richard Smith7d137e32012-03-23 03:33:32 +00002208 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2209 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2210 // specialization causes the implicit instantiation of the definitions
2211 // of unscoped member enumerations.
2212 // Record a point of instantiation for this implicit instantiation.
Richard Smithb66d7772012-03-23 23:09:08 +00002213 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2214 Enum->isCompleteDefinition()) {
Richard Smith7d137e32012-03-23 03:33:32 +00002215 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2216 assert(MSInfo && "no spec info for member enum specialization");
2217 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2218 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2219 }
Richard Smithded9c2e2012-07-11 22:37:56 +00002220 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2221 if (SA->isFailed()) {
2222 // A static_assert failed. Bail out; instantiating this
2223 // class is probably not meaningful.
2224 Instantiation->setInvalidDecl();
2225 break;
2226 }
Richard Smith921f1322019-05-13 23:35:21 +00002227 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
2228 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
2229 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
2230 MightHaveConstexprVirtualFunctions = true;
Richard Smith7d137e32012-03-23 03:33:32 +00002231 }
2232
2233 if (NewMember->isInvalidDecl())
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002234 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002235 } else {
2236 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002237 // instantiations was a semantic disaster, and we'll want to mark the
2238 // declaration invalid.
2239 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002240 }
2241 }
2242
2243 // Finish checking fields.
Craig Topperc3ec1492014-05-26 06:22:03 +00002244 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
Erich Keanec480f302018-07-12 21:09:05 +00002245 SourceLocation(), SourceLocation(), ParsedAttributesView());
Richard Smith848934c2019-12-05 13:37:35 -08002246 CheckCompletedCXXClass(nullptr, Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002247
Reid Kleckner93f661a2015-03-17 21:51:43 +00002248 // Default arguments are parsed, if not instantiated. We can go instantiate
Hans Wennborg92ce2af2019-12-02 16:25:23 +01002249 // default arg exprs for default constructors if necessary now. Unless we're
2250 // parsing a class, in which case wait until that's finished.
2251 if (ParsingClassDepth == 0)
2252 ActOnFinishCXXNonNestedClass();
Reid Kleckner93f661a2015-03-17 21:51:43 +00002253
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002254 // Instantiate late parsed attributes, and attach them to their decls.
2255 // See Sema::InstantiateAttrs
2256 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2257 E = LateAttrs.end(); I != E; ++I) {
2258 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2259 CurrentInstantiationScope = I->Scope;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002260
2261 // Allow 'this' within late-parsed attributes.
2262 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2263 CXXRecordDecl *ThisContext =
2264 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002265 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002266 ND && ND->isCXXInstanceMember());
2267
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002268 Attr *NewAttr =
2269 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2270 I->NewDecl->addAttr(NewAttr);
2271 LocalInstantiationScope::deleteScopes(I->Scope,
2272 Instantiator.getStartingScope());
2273 }
2274 Instantiator.disableLateAttributeInstantiation();
2275 LateAttrs.clear();
2276
Richard Smithd3b5c9082012-07-27 04:22:15 +00002277 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002278
Richard Smitha1087602014-03-10 00:04:29 +00002279 // FIXME: We should do something similar for explicit instantiations so they
2280 // end up in the right module.
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002281 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidise3789482012-02-11 01:59:57 +00002282 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002283 Instantiation->setLocStart(Pattern->getInnerLocStart());
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00002284 Instantiation->setBraceRange(Pattern->getBraceRange());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002285 }
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002286
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002287 if (!Instantiation->isInvalidDecl()) {
John McCalla0a96892012-08-10 03:15:35 +00002288 // Perform any dependent diagnostics from the pattern.
2289 PerformDependentDiagnostics(Pattern, TemplateArgs);
2290
Douglas Gregor869853e2010-11-10 19:44:59 +00002291 // Instantiate any out-of-line class template partial
2292 // specializations now.
Richard Smith10b55fc2013-09-26 03:49:48 +00002293 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregor869853e2010-11-10 19:44:59 +00002294 P = Instantiator.delayed_partial_spec_begin(),
2295 PEnd = Instantiator.delayed_partial_spec_end();
2296 P != PEnd; ++P) {
2297 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smith10b55fc2013-09-26 03:49:48 +00002298 P->first, P->second)) {
2299 Instantiation->setInvalidDecl();
2300 break;
2301 }
2302 }
2303
2304 // Instantiate any out-of-line variable template partial
2305 // specializations now.
2306 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2307 P = Instantiator.delayed_var_partial_spec_begin(),
2308 PEnd = Instantiator.delayed_var_partial_spec_end();
2309 P != PEnd; ++P) {
2310 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2311 P->first, P->second)) {
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002312 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002313 break;
2314 }
2315 }
2316 }
2317
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002318 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00002319 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002320
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002321 if (!Instantiation->isInvalidDecl()) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00002322 Consumer.HandleTagDeclDefinition(Instantiation);
2323
Douglas Gregor88d292c2010-05-13 16:44:06 +00002324 // Always emit the vtable for an explicit instantiation definition
Richard Smith921f1322019-05-13 23:35:21 +00002325 // of a polymorphic class template specialization. Otherwise, eagerly
2326 // instantiate only constexpr virtual functions in preparation for their use
2327 // in constant evaluation.
Douglas Gregor88d292c2010-05-13 16:44:06 +00002328 if (TSK == TSK_ExplicitInstantiationDefinition)
2329 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
Richard Smith921f1322019-05-13 23:35:21 +00002330 else if (MightHaveConstexprVirtualFunctions)
2331 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
2332 /*ConstexprOnly*/ true);
Douglas Gregor88d292c2010-05-13 16:44:06 +00002333 }
2334
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002335 return Instantiation->isInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002336}
2337
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002338/// Instantiate the definition of an enum from a given pattern.
Richard Smith4b38ded2012-03-14 23:13:10 +00002339///
2340/// \param PointOfInstantiation The point of instantiation within the
2341/// source code.
2342/// \param Instantiation is the declaration whose definition is being
2343/// instantiated. This will be a member enumeration of a class
2344/// temploid specialization, or a local enumeration within a
2345/// function temploid specialization.
2346/// \param Pattern The templated declaration from which the instantiation
2347/// occurs.
2348/// \param TemplateArgs The template arguments to be substituted into
2349/// the pattern.
2350/// \param TSK The kind of implicit or explicit instantiation to perform.
2351///
2352/// \return \c true if an error occurred, \c false otherwise.
2353bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2354 EnumDecl *Instantiation, EnumDecl *Pattern,
2355 const MultiLevelTemplateArgumentList &TemplateArgs,
2356 TemplateSpecializationKind TSK) {
2357 EnumDecl *PatternDef = Pattern->getDefinition();
Vassil Vassilevb21ee082016-08-18 22:01:25 +00002358 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00002359 Instantiation->getInstantiatedFromMemberEnum(),
2360 Pattern, PatternDef, TSK,/*Complain*/true))
2361 return true;
2362 Pattern = PatternDef;
2363
2364 // Record the point of instantiation.
2365 if (MemberSpecializationInfo *MSInfo
2366 = Instantiation->getMemberSpecializationInfo()) {
2367 MSInfo->setTemplateSpecializationKind(TSK);
2368 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2369 }
2370
2371 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002372 if (Inst.isInvalid())
Richard Smith4b38ded2012-03-14 23:13:10 +00002373 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002374 if (Inst.isAlreadyInstantiating())
2375 return false;
Jordan Rose1e879d82018-03-23 00:07:18 +00002376 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00002377 "instantiating enum definition");
Richard Smith4b38ded2012-03-14 23:13:10 +00002378
Richard Smitha1087602014-03-10 00:04:29 +00002379 // The instantiation is visible here, even if it was first declared in an
2380 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00002381 Instantiation->setVisibleDespiteOwningModule();
Richard Smitha1087602014-03-10 00:04:29 +00002382
Richard Smith4b38ded2012-03-14 23:13:10 +00002383 // Enter the scope of this instantiation. We don't use
2384 // PushDeclContext because we don't have a scope.
2385 ContextRAII SavedContext(*this, Instantiation);
Faisal Valid143a0c2017-04-01 21:30:49 +00002386 EnterExpressionEvaluationContext EvalContext(
2387 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith4b38ded2012-03-14 23:13:10 +00002388
2389 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2390
2391 // Pull attributes from the pattern onto the instantiation.
2392 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2393
2394 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2395 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2396
2397 // Exit the scope of this instantiation.
2398 SavedContext.pop();
2399
2400 return Instantiation->isInvalidDecl();
2401}
2402
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002403
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002404/// Instantiate the definition of a field from the given pattern.
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002405///
2406/// \param PointOfInstantiation The point of instantiation within the
2407/// source code.
2408/// \param Instantiation is the declaration whose definition is being
2409/// instantiated. This will be a class of a class temploid
2410/// specialization, or a local enumeration within a function temploid
2411/// specialization.
2412/// \param Pattern The templated declaration from which the instantiation
2413/// occurs.
2414/// \param TemplateArgs The template arguments to be substituted into
2415/// the pattern.
2416///
2417/// \return \c true if an error occurred, \c false otherwise.
2418bool Sema::InstantiateInClassInitializer(
2419 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2420 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2421 // If there is no initializer, we don't need to do anything.
2422 if (!Pattern->hasInClassInitializer())
2423 return false;
2424
2425 assert(Instantiation->getInClassInitStyle() ==
2426 Pattern->getInClassInitStyle() &&
2427 "pattern and instantiation disagree about init style");
2428
2429 // Error out if we haven't parsed the initializer of the pattern yet because
2430 // we are waiting for the closing brace of the outer class.
2431 Expr *OldInit = Pattern->getInClassInitializer();
2432 if (!OldInit) {
2433 RecordDecl *PatternRD = Pattern->getParent();
2434 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
Richard Smith8dbc6b22016-11-22 22:55:12 +00002435 Diag(PointOfInstantiation,
2436 diag::err_in_class_initializer_not_yet_parsed)
2437 << OutermostClass << Pattern;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002438 Diag(Pattern->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002439 Instantiation->setInvalidDecl();
2440 return true;
2441 }
2442
2443 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2444 if (Inst.isInvalid())
2445 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002446 if (Inst.isAlreadyInstantiating()) {
2447 // Error out if we hit an instantiation cycle for this initializer.
2448 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2449 << Instantiation;
2450 return true;
2451 }
Jordan Rose1e879d82018-03-23 00:07:18 +00002452 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00002453 "instantiating default member init");
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002454
2455 // Enter the scope of this instantiation. We don't use PushDeclContext because
2456 // we don't have a scope.
2457 ContextRAII SavedContext(*this, Instantiation->getParent());
Faisal Valid143a0c2017-04-01 21:30:49 +00002458 EnterExpressionEvaluationContext EvalContext(
2459 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002460
Serge Pavlov907233f2015-04-28 17:58:47 +00002461 LocalInstantiationScope Scope(*this, true);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002462
2463 // Instantiate the initializer.
2464 ActOnStartCXXInClassMemberInitializer();
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002465 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002466
2467 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2468 /*CXXDirectInit=*/false);
2469 Expr *Init = NewInit.get();
2470 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2471 ActOnFinishCXXInClassMemberInitializer(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002472 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002473
Richard Smith4b054b22016-08-24 21:25:37 +00002474 if (auto *L = getASTMutationListener())
2475 L->DefaultMemberInitializerInstantiated(Instantiation);
2476
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002477 // Return true if the in-class initializer is still missing.
2478 return !Instantiation->getInClassInitializer();
2479}
2480
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002481namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002482 /// A partial specialization whose template arguments have matched
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002483 /// a given template-id.
2484 struct PartialSpecMatchResult {
2485 ClassTemplatePartialSpecializationDecl *Partial;
2486 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002487 };
2488}
2489
Richard Smithe6d4b772017-06-07 02:42:27 +00002490bool Sema::usesPartialOrExplicitSpecialization(
2491 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
2492 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
2493 TSK_ExplicitSpecialization)
2494 return true;
2495
2496 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2497 ClassTemplateSpec->getSpecializedTemplate()
2498 ->getPartialSpecializations(PartialSpecs);
2499 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2500 TemplateDeductionInfo Info(Loc);
2501 if (!DeduceTemplateArguments(PartialSpecs[I],
2502 ClassTemplateSpec->getTemplateArgs(), Info))
2503 return true;
2504 }
2505
2506 return false;
2507}
2508
Richard Smith32b43762017-01-08 22:45:21 +00002509/// Get the instantiation pattern to use to instantiate the definition of a
2510/// given ClassTemplateSpecializationDecl (either the pattern of the primary
2511/// template or of a partial specialization).
2512static CXXRecordDecl *
2513getPatternForClassTemplateSpecialization(
2514 Sema &S, SourceLocation PointOfInstantiation,
Larisse Voufo72caf2b2013-08-22 00:59:14 +00002515 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2516 TemplateSpecializationKind TSK, bool Complain) {
Richard Smith32b43762017-01-08 22:45:21 +00002517 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2518 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
2519 return nullptr;
2520
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002521 llvm::PointerUnion<ClassTemplateDecl *,
2522 ClassTemplatePartialSpecializationDecl *>
2523 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2524 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
2525 // Find best matching specialization.
2526 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregor2373c592009-05-31 09:31:02 +00002527
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002528 // C++ [temp.class.spec.match]p1:
2529 // When a class template is used in a context that requires an
2530 // instantiation of the class, it is necessary to determine
2531 // whether the instantiation is to be generated using the primary
2532 // template or one of the partial specializations. This is done by
2533 // matching the template arguments of the class template
2534 // specialization with the template argument lists of the partial
2535 // specializations.
2536 typedef PartialSpecMatchResult MatchResult;
2537 SmallVector<MatchResult, 4> Matched;
2538 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2539 Template->getPartialSpecializations(PartialSpecs);
2540 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2541 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2542 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2543 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2544 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
2545 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
2546 // Store the failed-deduction information for use in diagnostics, later.
2547 // TODO: Actually use the failed-deduction info?
2548 FailedCandidates.addCandidate().set(
2549 DeclAccessPair::make(Template, AS_public), Partial,
2550 MakeDeductionFailureInfo(S.Context, Result, Info));
2551 (void)Result;
2552 } else {
2553 Matched.push_back(PartialSpecMatchResult());
2554 Matched.back().Partial = Partial;
2555 Matched.back().Args = Info.take();
2556 }
2557 }
2558
2559 // If we're dealing with a member template where the template parameters
2560 // have been instantiated, this provides the original template parameters
2561 // from which the member template's parameters were instantiated.
2562
2563 if (Matched.size() >= 1) {
2564 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
2565 if (Matched.size() == 1) {
2566 // -- If exactly one matching specialization is found, the
2567 // instantiation is generated from that specialization.
2568 // We don't need to do anything for this.
2569 } else {
2570 // -- If more than one matching specialization is found, the
2571 // partial order rules (14.5.4.2) are used to determine
2572 // whether one of the specializations is more specialized
2573 // than the others. If none of the specializations is more
2574 // specialized than all of the other matching
2575 // specializations, then the use of the class template is
2576 // ambiguous and the program is ill-formed.
2577 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2578 PEnd = Matched.end();
2579 P != PEnd; ++P) {
2580 if (S.getMoreSpecializedPartialSpecialization(
2581 P->Partial, Best->Partial, PointOfInstantiation) ==
2582 P->Partial)
2583 Best = P;
2584 }
2585
2586 // Determine if the best partial specialization is more specialized than
2587 // the others.
2588 bool Ambiguous = false;
2589 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2590 PEnd = Matched.end();
2591 P != PEnd; ++P) {
2592 if (P != Best && S.getMoreSpecializedPartialSpecialization(
2593 P->Partial, Best->Partial,
2594 PointOfInstantiation) != Best->Partial) {
2595 Ambiguous = true;
2596 break;
2597 }
2598 }
2599
2600 if (Ambiguous) {
2601 // Partial ordering did not produce a clear winner. Complain.
2602 Inst.Clear();
2603 ClassTemplateSpec->setInvalidDecl();
2604 S.Diag(PointOfInstantiation,
2605 diag::err_partial_spec_ordering_ambiguous)
2606 << ClassTemplateSpec;
2607
2608 // Print the matching partial specializations.
2609 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2610 PEnd = Matched.end();
2611 P != PEnd; ++P)
2612 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2613 << S.getTemplateArgumentBindingsText(
2614 P->Partial->getTemplateParameters(), *P->Args);
2615
2616 return nullptr;
2617 }
2618 }
2619
2620 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002621 } else {
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002622 // -- If no matches are found, the instantiation is generated
2623 // from the primary template.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002624 }
Douglas Gregor2373c592009-05-31 09:31:02 +00002625 }
2626
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002627 CXXRecordDecl *Pattern = nullptr;
2628 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2629 if (auto *PartialSpec =
2630 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
Douglas Gregorbe999392009-09-15 16:23:51 +00002631 // Instantiate using the best class template partial specialization.
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002632 while (PartialSpec->getInstantiatedFromMember()) {
Douglas Gregor21610382009-10-29 00:04:11 +00002633 // If we've found an explicit specialization of this class template,
2634 // stop here and use that as the pattern.
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002635 if (PartialSpec->isMemberSpecialization())
Douglas Gregor21610382009-10-29 00:04:11 +00002636 break;
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002637
2638 PartialSpec = PartialSpec->getInstantiatedFromMember();
Douglas Gregor21610382009-10-29 00:04:11 +00002639 }
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002640 Pattern = PartialSpec;
Douglas Gregor170bc422009-06-12 22:31:52 +00002641 } else {
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002642 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2643 while (Template->getInstantiatedFromMemberTemplate()) {
Douglas Gregorcf915552009-10-13 16:30:37 +00002644 // If we've found an explicit specialization of this class template,
2645 // stop here and use that as the pattern.
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002646 if (Template->isMemberSpecialization())
Douglas Gregorcf915552009-10-13 16:30:37 +00002647 break;
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002648
2649 Template = Template->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00002650 }
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002651 Pattern = Template->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00002652 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002653
Richard Smith32b43762017-01-08 22:45:21 +00002654 return Pattern;
2655}
Mike Stump11289f42009-09-09 15:08:12 +00002656
Richard Smith32b43762017-01-08 22:45:21 +00002657bool Sema::InstantiateClassTemplateSpecialization(
2658 SourceLocation PointOfInstantiation,
2659 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2660 TemplateSpecializationKind TSK, bool Complain) {
2661 // Perform the actual instantiation on the canonical declaration.
2662 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2663 ClassTemplateSpec->getCanonicalDecl());
2664 if (ClassTemplateSpec->isInvalidDecl())
2665 return true;
2666
2667 CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization(
2668 *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
2669 if (!Pattern)
2670 return true;
2671
2672 return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
2673 getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
2674 Complain);
Douglas Gregor463421d2009-03-03 04:44:36 +00002675}
Douglas Gregor90a1a652009-03-19 17:26:29 +00002676
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002677/// Instantiates the definitions of all of the member
John McCall76d824f2009-08-25 22:02:44 +00002678/// of the given class, which is an instantiation of a class template
2679/// or a member class of a template.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002680void
2681Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002682 CXXRecordDecl *Instantiation,
2683 const MultiLevelTemplateArgumentList &TemplateArgs,
2684 TemplateSpecializationKind TSK) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00002685 // FIXME: We need to notify the ASTMutationListener that we did all of these
2686 // things, in case we have an explicit instantiation definition in a PCM, a
2687 // module, or preamble, and the declaration is in an imported AST.
David Majnemer192d1792013-11-27 08:20:38 +00002688 assert(
2689 (TSK == TSK_ExplicitInstantiationDefinition ||
2690 TSK == TSK_ExplicitInstantiationDeclaration ||
2691 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2692 "Unexpected template specialization kind!");
Aaron Ballman629afae2014-03-07 19:56:05 +00002693 for (auto *D : Instantiation->decls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002694 bool SuppressNew = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002695 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Louis Dionned2695792018-10-04 15:49:42 +00002696 if (FunctionDecl *Pattern =
2697 Function->getInstantiatedFromMemberFunction()) {
2698
2699 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2700 continue;
2701
2702 MemberSpecializationInfo *MSInfo =
2703 Function->getMemberSpecializationInfo();
Douglas Gregor1d957a32009-10-27 18:42:08 +00002704 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002705 if (MSInfo->getTemplateSpecializationKind()
2706 == TSK_ExplicitSpecialization)
2707 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002708
2709 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2710 Function,
Douglas Gregor1d957a32009-10-27 18:42:08 +00002711 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002712 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002713 SuppressNew) ||
2714 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002715 continue;
Richard Smitheb36ddf2014-04-24 22:45:46 +00002716
2717 // C++11 [temp.explicit]p8:
2718 // An explicit instantiation definition that names a class template
2719 // specialization explicitly instantiates the class template
2720 // specialization and is only an explicit instantiation definition
2721 // of members whose definition is visible at the point of
2722 // instantiation.
2723 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002724 continue;
2725
Richard Smitheb36ddf2014-04-24 22:45:46 +00002726 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2727
2728 if (Function->isDefined()) {
2729 // Let the ASTConsumer know that this function has been explicitly
2730 // instantiated now, and its linkage might have changed.
2731 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2732 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002733 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Richard Smitheb36ddf2014-04-24 22:45:46 +00002734 } else if (TSK == TSK_ImplicitInstantiation) {
2735 PendingLocalImplicitInstantiations.push_back(
2736 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor1d957a32009-10-27 18:42:08 +00002737 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002738 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002739 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002740 if (isa<VarTemplateSpecializationDecl>(Var))
2741 continue;
2742
Douglas Gregor86d142a2009-10-08 07:24:58 +00002743 if (Var->isStaticDataMember()) {
Louis Dionned2695792018-10-04 15:49:42 +00002744 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2745 continue;
2746
Douglas Gregor1d957a32009-10-27 18:42:08 +00002747 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2748 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002749 if (MSInfo->getTemplateSpecializationKind()
2750 == TSK_ExplicitSpecialization)
2751 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002752
2753 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2754 Var,
Douglas Gregor1d957a32009-10-27 18:42:08 +00002755 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002756 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002757 SuppressNew) ||
2758 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002759 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002760
Douglas Gregor1d957a32009-10-27 18:42:08 +00002761 if (TSK == TSK_ExplicitInstantiationDefinition) {
2762 // C++0x [temp.explicit]p8:
2763 // An explicit instantiation definition that names a class template
Fangrui Song6907ce22018-07-30 19:24:48 +00002764 // specialization explicitly instantiates the class template
2765 // specialization and is only an explicit instantiation definition
2766 // of members whose definition is visible at the point of
Douglas Gregor1d957a32009-10-27 18:42:08 +00002767 // instantiation.
Richard Smith62f19e72016-06-25 00:15:56 +00002768 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002769 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002770
Douglas Gregor1d957a32009-10-27 18:42:08 +00002771 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00002772 InstantiateVariableDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00002773 } else {
2774 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2775 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002776 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002777 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Louis Dionned2695792018-10-04 15:49:42 +00002778 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2779 continue;
2780
Douglas Gregor1da22252010-04-18 18:11:38 +00002781 // Always skip the injected-class-name, along with any
2782 // redeclarations of nested classes, since both would cause us
2783 // to try to instantiate the members of a class twice.
Richard Smith069ecf62014-11-20 22:56:34 +00002784 // Skip closure types; they'll get instantiated when we instantiate
2785 // the corresponding lambda-expression.
2786 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2787 Record->isLambda())
Douglas Gregord801b062009-10-07 23:56:10 +00002788 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002789
Douglas Gregor1d957a32009-10-27 18:42:08 +00002790 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2791 assert(MSInfo && "No member specialization information?");
Fangrui Song6907ce22018-07-30 19:24:48 +00002792
Douglas Gregor06aa50412010-04-09 21:02:29 +00002793 if (MSInfo->getTemplateSpecializationKind()
2794 == TSK_ExplicitSpecialization)
2795 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00002796
Reid Kleckner5f789ba2019-04-29 21:32:05 +00002797 if (Context.getTargetInfo().getTriple().isOSWindows() &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00002798 TSK == TSK_ExplicitInstantiationDeclaration) {
Reid Kleckner5f789ba2019-04-29 21:32:05 +00002799 // On Windows, explicit instantiation decl of the outer class doesn't
2800 // affect the inner class. Typically extern template declarations are
2801 // used in combination with dll import/export annotations, but those
2802 // are not propagated from the outer class templates to inner classes.
2803 // Therefore, do not instantiate inner classes on this platform, so
2804 // that users don't end up with undefined symbols during linking.
Hans Wennborga86a83b2016-05-26 19:42:56 +00002805 continue;
2806 }
2807
Fangrui Song6907ce22018-07-30 19:24:48 +00002808 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2809 Record,
Douglas Gregor1d957a32009-10-27 18:42:08 +00002810 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002811 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002812 SuppressNew) ||
2813 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002814 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002815
Douglas Gregor1d957a32009-10-27 18:42:08 +00002816 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2817 assert(Pattern && "Missing instantiated-from-template information");
Fangrui Song6907ce22018-07-30 19:24:48 +00002818
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002819 if (!Record->getDefinition()) {
2820 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002821 // C++0x [temp.explicit]p8:
2822 // An explicit instantiation definition that names a class template
Fangrui Song6907ce22018-07-30 19:24:48 +00002823 // specialization explicitly instantiates the class template
2824 // specialization and is only an explicit instantiation definition
2825 // of members whose definition is visible at the point of
Douglas Gregor1d957a32009-10-27 18:42:08 +00002826 // instantiation.
2827 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2828 MSInfo->setTemplateSpecializationKind(TSK);
2829 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2830 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002831
Douglas Gregor1d957a32009-10-27 18:42:08 +00002832 continue;
2833 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002834
Douglas Gregor1d957a32009-10-27 18:42:08 +00002835 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002836 TemplateArgs,
2837 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002838 } else {
2839 if (TSK == TSK_ExplicitInstantiationDefinition &&
2840 Record->getTemplateSpecializationKind() ==
2841 TSK_ExplicitInstantiationDeclaration) {
2842 Record->setTemplateSpecializationKind(TSK);
2843 MarkVTableUsed(PointOfInstantiation, Record, true);
2844 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002845 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002846
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002847 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002848 if (Pattern)
Fangrui Song6907ce22018-07-30 19:24:48 +00002849 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
Douglas Gregor1d957a32009-10-27 18:42:08 +00002850 TSK);
Aaron Ballman629afae2014-03-07 19:56:05 +00002851 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smith4b38ded2012-03-14 23:13:10 +00002852 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2853 assert(MSInfo && "No member specialization information?");
2854
2855 if (MSInfo->getTemplateSpecializationKind()
2856 == TSK_ExplicitSpecialization)
2857 continue;
2858
2859 if (CheckSpecializationInstantiationRedecl(
2860 PointOfInstantiation, TSK, Enum,
2861 MSInfo->getTemplateSpecializationKind(),
2862 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2863 SuppressNew)
2864 continue;
2865
2866 if (Enum->getDefinition())
2867 continue;
2868
Richard Smith6739a102016-05-05 00:56:12 +00002869 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
Richard Smith4b38ded2012-03-14 23:13:10 +00002870 assert(Pattern && "Missing instantiated-from-template information");
2871
2872 if (TSK == TSK_ExplicitInstantiationDefinition) {
2873 if (!Pattern->getDefinition())
2874 continue;
2875
2876 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2877 } else {
2878 MSInfo->setTemplateSpecializationKind(TSK);
2879 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2880 }
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002881 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2882 // No need to instantiate in-class initializers during explicit
2883 // instantiation.
2884 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2885 CXXRecordDecl *ClassPattern =
2886 Instantiation->getTemplateInstantiationPattern();
2887 DeclContext::lookup_result Lookup =
2888 ClassPattern->lookup(Field->getDeclName());
David Majnemer76a25622016-06-09 05:26:56 +00002889 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002890 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2891 TemplateArgs);
2892 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002893 }
2894 }
2895}
2896
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002897/// Instantiate the definitions of all of the members of the
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002898/// given class template specialization, which was named as part of an
2899/// explicit instantiation.
Mike Stump11289f42009-09-09 15:08:12 +00002900void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002901Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002902 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002903 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2904 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002905 // C++0x [temp.explicit]p7:
2906 // An explicit instantiation that names a class template
2907 // specialization is an explicit instantion of the same kind
2908 // (declaration or definition) of each of its members (not
2909 // including members inherited from base classes) that has not
2910 // been previously explicitly specialized in the translation unit
2911 // containing the explicit instantiation, except as described
2912 // below.
2913 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002914 getTemplateInstantiationArgs(ClassTemplateSpec),
2915 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002916}
2917
John McCalldadc5752010-08-24 06:29:42 +00002918StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002919Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002920 if (!S)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002921 return S;
Douglas Gregorebe10102009-08-20 07:17:43 +00002922
2923 TemplateInstantiator Instantiator(*this, TemplateArgs,
2924 SourceLocation(),
2925 DeclarationName());
2926 return Instantiator.TransformStmt(S);
2927}
2928
John McCalldadc5752010-08-24 06:29:42 +00002929ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002930Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002931 if (!E)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002932 return E;
Mike Stump11289f42009-09-09 15:08:12 +00002933
Douglas Gregora16548e2009-08-11 05:31:07 +00002934 TemplateInstantiator Instantiator(*this, TemplateArgs,
2935 SourceLocation(),
2936 DeclarationName());
2937 return Instantiator.TransformExpr(E);
2938}
2939
Richard Smithd59b8322012-12-19 01:39:02 +00002940ExprResult Sema::SubstInitializer(Expr *Init,
2941 const MultiLevelTemplateArgumentList &TemplateArgs,
2942 bool CXXDirectInit) {
2943 TemplateInstantiator Instantiator(*this, TemplateArgs,
2944 SourceLocation(),
2945 DeclarationName());
2946 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2947}
2948
Craig Topper99d23532015-12-24 23:58:29 +00002949bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002950 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002951 SmallVectorImpl<Expr *> &Outputs) {
Craig Topper99d23532015-12-24 23:58:29 +00002952 if (Exprs.empty())
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002953 return false;
Richard Smithd59b8322012-12-19 01:39:02 +00002954
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002955 TemplateInstantiator Instantiator(*this, TemplateArgs,
2956 SourceLocation(),
2957 DeclarationName());
Craig Topper99d23532015-12-24 23:58:29 +00002958 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2959 IsCall, Outputs);
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002960}
2961
Douglas Gregor14454802011-02-25 02:25:35 +00002962NestedNameSpecifierLoc
2963Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
Fangrui Song6907ce22018-07-30 19:24:48 +00002964 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor14454802011-02-25 02:25:35 +00002965 if (!NNS)
2966 return NestedNameSpecifierLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002967
Douglas Gregor14454802011-02-25 02:25:35 +00002968 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2969 DeclarationName());
2970 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2971}
2972
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002973/// Do template substitution on declaration name info.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002974DeclarationNameInfo
2975Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2976 const MultiLevelTemplateArgumentList &TemplateArgs) {
2977 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2978 NameInfo.getName());
2979 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2980}
2981
Douglas Gregoraa594892009-03-31 18:38:02 +00002982TemplateName
Douglas Gregordf846d12011-03-02 18:46:51 +00002983Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2984 TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002985 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002986 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2987 DeclarationName());
Douglas Gregordf846d12011-03-02 18:46:51 +00002988 CXXScopeSpec SS;
2989 SS.Adopt(QualifierLoc);
2990 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregoraa594892009-03-31 18:38:02 +00002991}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002992
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002993bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2994 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002995 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002996 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2997 DeclarationName());
Fangrui Song6907ce22018-07-30 19:24:48 +00002998
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002999 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00003000}
Douglas Gregor14cf7522010-04-30 18:55:50 +00003001
Richard Smith70b13042015-01-09 01:19:56 +00003002static const Decl *getCanonicalParmVarDecl(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00003003 // When storing ParmVarDecls in the local instantiation scope, we always
3004 // want to use the ParmVarDecl from the canonical function declaration,
3005 // since the map is then valid for any redeclaration or definition of that
3006 // function.
3007 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
3008 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
3009 unsigned i = PV->getFunctionScopeIndex();
Richard Smith70b13042015-01-09 01:19:56 +00003010 // This parameter might be from a freestanding function type within the
3011 // function and isn't necessarily referring to one of FD's parameters.
Dmitri Gribenko66b6bb12019-04-10 20:25:07 +00003012 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
Richard Smith70b13042015-01-09 01:19:56 +00003013 return FD->getCanonicalDecl()->getParamDecl(i);
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00003014 }
3015 }
3016 return D;
3017}
3018
3019
Douglas Gregorf3010112011-01-07 16:43:16 +00003020llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
3021LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00003022 D = getCanonicalParmVarDecl(D);
Chris Lattnercab02a62011-02-17 20:34:02 +00003023 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor14cf7522010-04-30 18:55:50 +00003024 Current = Current->Outer) {
Chris Lattnercab02a62011-02-17 20:34:02 +00003025
Douglas Gregor14cf7522010-04-30 18:55:50 +00003026 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00003027 const Decl *CheckD = D;
3028 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00003029 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00003030 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00003031 return &Found->second;
Fangrui Song6907ce22018-07-30 19:24:48 +00003032
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00003033 // If this is a tag declaration, it's possible that we need to look for
3034 // a previous declaration.
3035 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregorec9fd132012-01-14 16:38:05 +00003036 CheckD = Tag->getPreviousDecl();
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00003037 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003038 CheckD = nullptr;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00003039 } while (CheckD);
Fangrui Song6907ce22018-07-30 19:24:48 +00003040
3041 // If we aren't combined with our outer scope, we're done.
Douglas Gregor14cf7522010-04-30 18:55:50 +00003042 if (!Current->CombineWithOuterScope)
3043 break;
3044 }
Chris Lattnercab02a62011-02-17 20:34:02 +00003045
Serge Pavlov7cd8f602013-07-15 06:14:07 +00003046 // If we're performing a partial substitution during template argument
3047 // deduction, we may not have values for template parameters yet.
3048 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
3049 isa<TemplateTemplateParmDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00003050 return nullptr;
Serge Pavlov7cd8f602013-07-15 06:14:07 +00003051
Serge Pavlove7ad8312015-05-15 10:10:28 +00003052 // Local types referenced prior to definition may require instantiation.
3053 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
3054 if (RD->isLocalClass())
3055 return nullptr;
3056
3057 // Enumeration types referenced prior to definition may appear as a result of
3058 // error recovery.
3059 if (isa<EnumDecl>(D))
Serge Pavlov4c511742015-05-04 16:44:39 +00003060 return nullptr;
3061
Chris Lattnercab02a62011-02-17 20:34:02 +00003062 // If we didn't find the decl, then we either have a sema bug, or we have a
3063 // forward reference to a label declaration. Return null to indicate that
3064 // we have an uninstantiated label.
3065 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Craig Topperc3ec1492014-05-26 06:22:03 +00003066 return nullptr;
Douglas Gregor14cf7522010-04-30 18:55:50 +00003067}
3068
John McCall19c1bfd2010-08-25 05:32:35 +00003069void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00003070 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00003071 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Richard Smith70b13042015-01-09 01:19:56 +00003072 if (Stored.isNull()) {
3073#ifndef NDEBUG
3074 // It should not be present in any surrounding scope either.
3075 LocalInstantiationScope *Current = this;
3076 while (Current->CombineWithOuterScope && Current->Outer) {
3077 Current = Current->Outer;
3078 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3079 "Instantiated local in inner and outer scopes");
3080 }
3081#endif
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003082 Stored = Inst;
Richard Smith70b13042015-01-09 01:19:56 +00003083 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
Richard Smithb2997f52019-05-21 20:10:50 +00003084 Pack->push_back(cast<VarDecl>(Inst));
Richard Smith70b13042015-01-09 01:19:56 +00003085 } else {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003086 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Richard Smith70b13042015-01-09 01:19:56 +00003087 }
Douglas Gregor14cf7522010-04-30 18:55:50 +00003088}
Douglas Gregorf3010112011-01-07 16:43:16 +00003089
James Y Knight48fefa32015-09-30 14:04:23 +00003090void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
Richard Smithb2997f52019-05-21 20:10:50 +00003091 VarDecl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00003092 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00003093 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
3094 Pack->push_back(Inst);
3095}
3096
3097void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
Richard Smith70b13042015-01-09 01:19:56 +00003098#ifndef NDEBUG
3099 // This should be the first time we've been told about this decl.
3100 for (LocalInstantiationScope *Current = this;
3101 Current && Current->CombineWithOuterScope; Current = Current->Outer)
3102 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3103 "Creating local pack after instantiation of local");
3104#endif
3105
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00003106 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00003107 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregorf3010112011-01-07 16:43:16 +00003108 DeclArgumentPack *Pack = new DeclArgumentPack;
3109 Stored = Pack;
3110 ArgumentPacks.push_back(Pack);
3111}
3112
Fangrui Song6907ce22018-07-30 19:24:48 +00003113void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003114 const TemplateArgument *ExplicitArgs,
3115 unsigned NumExplicitArgs) {
3116 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
3117 "Already have a partially-substituted pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00003118 assert((!PartiallySubstitutedPack
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003119 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
3120 "Wrong number of arguments in partially-substituted pack");
3121 PartiallySubstitutedPack = Pack;
3122 ArgsInPartiallySubstitutedPack = ExplicitArgs;
3123 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
3124}
3125
3126NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
3127 const TemplateArgument **ExplicitArgs,
3128 unsigned *NumExplicitArgs) const {
3129 if (ExplicitArgs)
Craig Topperc3ec1492014-05-26 06:22:03 +00003130 *ExplicitArgs = nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003131 if (NumExplicitArgs)
3132 *NumExplicitArgs = 0;
Fangrui Song6907ce22018-07-30 19:24:48 +00003133
3134 for (const LocalInstantiationScope *Current = this; Current;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003135 Current = Current->Outer) {
3136 if (Current->PartiallySubstitutedPack) {
3137 if (ExplicitArgs)
3138 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
3139 if (NumExplicitArgs)
3140 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
Fangrui Song6907ce22018-07-30 19:24:48 +00003141
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003142 return Current->PartiallySubstitutedPack;
3143 }
3144
3145 if (!Current->CombineWithOuterScope)
3146 break;
3147 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003148
3149 return nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003150}