blob: 1451fe4bb4d109d860ab16ea6da6d8438a15e808 [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 Smith883dbc42017-05-25 22:47:05 +0000206 case DefiningSynthesizedFunction:
Richard Smith5159bbad2018-09-05 22:30:37 +0000207 case ExceptionSpecEvaluation:
Saar Raz5d98ba62019-10-15 15:24:26 +0000208 case ConstraintSubstitution:
Richard Smith974c8b72019-10-19 00:04:43 +0000209 case RewritingOperatorAsSpaceship:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000210 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000211
Gabor Horvath207e7b12018-02-10 14:04:45 +0000212 // This function should never be called when Kind's value is Memoization.
213 case Memoization:
214 break;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000215 }
David Blaikie8a40f702012-01-17 06:56:22 +0000216
Richard Smith696e3122017-02-23 01:43:54 +0000217 llvm_unreachable("Invalid SynthesisKind!");
Douglas Gregor84d49a22009-11-11 21:54:23 +0000218}
219
Benjamin Kramer7761a042015-03-06 16:36:50 +0000220Sema::InstantiatingTemplate::InstantiatingTemplate(
Richard Smith696e3122017-02-23 01:43:54 +0000221 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000222 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
223 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000224 sema::TemplateDeductionInfo *DeductionInfo)
Richard Smith13381222017-02-23 21:43:43 +0000225 : SemaRef(SemaRef) {
Akira Hatanaka43556c12016-11-03 15:04:58 +0000226 // Don't allow further instantiation if a fatal error and an uncompilable
Akira Hatanaka40c15ab2016-11-03 17:11:28 +0000227 // error have occurred. Any diagnostics we might have raised will not be
Akira Hatanaka43556c12016-11-03 15:04:58 +0000228 // visible, and we do not need to construct a correct AST.
229 if (SemaRef.Diags.hasFatalErrorOccurred() &&
230 SemaRef.Diags.hasUncompilableErrorOccurred()) {
David Majnemer8c969ea2015-01-30 05:01:23 +0000231 Invalid = true;
232 return;
233 }
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000234 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
235 if (!Invalid) {
Richard Smith696e3122017-02-23 01:43:54 +0000236 CodeSynthesisContext Inst;
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000237 Inst.Kind = Kind;
238 Inst.PointOfInstantiation = PointOfInstantiation;
239 Inst.Entity = Entity;
240 Inst.Template = Template;
241 Inst.TemplateArgs = TemplateArgs.data();
242 Inst.NumTemplateArgs = TemplateArgs.size();
243 Inst.DeductionInfo = DeductionInfo;
244 Inst.InstantiationRange = InstantiationRange;
Richard Smith13381222017-02-23 21:43:43 +0000245 SemaRef.pushCodeSynthesisContext(Inst);
246
Richard Smith54f18e82016-08-31 02:15:21 +0000247 AlreadyInstantiating =
248 !SemaRef.InstantiatingSpecializations
249 .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
250 .second;
Gabor Horvath207e7b12018-02-10 14:04:45 +0000251 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000252 }
253}
254
Benjamin Kramer7761a042015-03-06 16:36:50 +0000255Sema::InstantiatingTemplate::InstantiatingTemplate(
256 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
257 SourceRange InstantiationRange)
258 : InstantiatingTemplate(SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000259 CodeSynthesisContext::TemplateInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000260 PointOfInstantiation, InstantiationRange, Entity) {}
Douglas Gregor79cf6032009-03-10 20:44:00 +0000261
Benjamin Kramer7761a042015-03-06 16:36:50 +0000262Sema::InstantiatingTemplate::InstantiatingTemplate(
263 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
264 ExceptionSpecification, SourceRange InstantiationRange)
265 : InstantiatingTemplate(
Richard Smith696e3122017-02-23 01:43:54 +0000266 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000267 PointOfInstantiation, InstantiationRange, Entity) {}
Richard Smithf623c962012-04-17 00:58:00 +0000268
Benjamin Kramer7761a042015-03-06 16:36:50 +0000269Sema::InstantiatingTemplate::InstantiatingTemplate(
Richard Smith54f18e82016-08-31 02:15:21 +0000270 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
271 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
272 SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000273 : InstantiatingTemplate(
274 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000275 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
Richard Smith54f18e82016-08-31 02:15:21 +0000276 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
277 Template, TemplateArgs) {}
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000278
Benjamin Kramer7761a042015-03-06 16:36:50 +0000279Sema::InstantiatingTemplate::InstantiatingTemplate(
280 Sema &SemaRef, SourceLocation PointOfInstantiation,
281 FunctionTemplateDecl *FunctionTemplate,
282 ArrayRef<TemplateArgument> TemplateArgs,
Richard Smith696e3122017-02-23 01:43:54 +0000283 CodeSynthesisContext::SynthesisKind Kind,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000284 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
285 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
286 InstantiationRange, FunctionTemplate, nullptr,
Richard Smith54f18e82016-08-31 02:15:21 +0000287 TemplateArgs, &DeductionInfo) {
288 assert(
Richard Smith696e3122017-02-23 01:43:54 +0000289 Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
290 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution);
Richard Smith54f18e82016-08-31 02:15:21 +0000291}
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000292
Benjamin Kramer7761a042015-03-06 16:36:50 +0000293Sema::InstantiatingTemplate::InstantiatingTemplate(
294 Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith0e617ec2016-12-27 07:56:27 +0000295 TemplateDecl *Template,
296 ArrayRef<TemplateArgument> TemplateArgs,
297 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
298 : InstantiatingTemplate(
299 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000300 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
Richard Smith0e617ec2016-12-27 07:56:27 +0000301 PointOfInstantiation, InstantiationRange, Template, nullptr,
302 TemplateArgs, &DeductionInfo) {}
303
304Sema::InstantiatingTemplate::InstantiatingTemplate(
305 Sema &SemaRef, SourceLocation PointOfInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000306 ClassTemplatePartialSpecializationDecl *PartialSpec,
307 ArrayRef<TemplateArgument> TemplateArgs,
308 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
309 : InstantiatingTemplate(
310 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000311 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000312 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
313 TemplateArgs, &DeductionInfo) {}
Douglas Gregor637d9982009-06-10 23:47:09 +0000314
Larisse Voufo39a1e502013-08-06 01:03:05 +0000315Sema::InstantiatingTemplate::InstantiatingTemplate(
316 Sema &SemaRef, SourceLocation PointOfInstantiation,
317 VarTemplatePartialSpecializationDecl *PartialSpec,
318 ArrayRef<TemplateArgument> TemplateArgs,
319 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000320 : InstantiatingTemplate(
321 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000322 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000323 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
324 TemplateArgs, &DeductionInfo) {}
Larisse Voufo39a1e502013-08-06 01:03:05 +0000325
Benjamin Kramer7761a042015-03-06 16:36:50 +0000326Sema::InstantiatingTemplate::InstantiatingTemplate(
327 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
328 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
329 : InstantiatingTemplate(
330 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000331 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000332 PointOfInstantiation, InstantiationRange, Param, nullptr,
333 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000334
Benjamin Kramer7761a042015-03-06 16:36:50 +0000335Sema::InstantiatingTemplate::InstantiatingTemplate(
336 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
337 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
338 SourceRange InstantiationRange)
339 : InstantiatingTemplate(
340 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000341 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000342 PointOfInstantiation, InstantiationRange, Param, Template,
343 TemplateArgs) {}
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000344
Benjamin Kramer7761a042015-03-06 16:36:50 +0000345Sema::InstantiatingTemplate::InstantiatingTemplate(
346 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
347 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
348 SourceRange InstantiationRange)
349 : InstantiatingTemplate(
350 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000351 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000352 PointOfInstantiation, InstantiationRange, Param, Template,
353 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000354
Benjamin Kramer7761a042015-03-06 16:36:50 +0000355Sema::InstantiatingTemplate::InstantiatingTemplate(
356 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
357 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
358 SourceRange InstantiationRange)
359 : InstantiatingTemplate(
Richard Smith696e3122017-02-23 01:43:54 +0000360 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000361 PointOfInstantiation, InstantiationRange, Param, Template,
362 TemplateArgs) {}
Anders Carlsson657bad42009-09-05 05:14:19 +0000363
Saar Raz5d98ba62019-10-15 15:24:26 +0000364Sema::InstantiatingTemplate::InstantiatingTemplate(
365 Sema &SemaRef, SourceLocation PointOfInstantiation,
Saar Razfdf80e82019-12-06 01:30:21 +0200366 ConstraintsCheck, NamedDecl *Template,
Saar Raz5d98ba62019-10-15 15:24:26 +0000367 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
368 : InstantiatingTemplate(
369 SemaRef, CodeSynthesisContext::ConstraintsCheck,
370 PointOfInstantiation, InstantiationRange, Template, nullptr,
371 TemplateArgs) {}
372
373Sema::InstantiatingTemplate::InstantiatingTemplate(
374 Sema &SemaRef, SourceLocation PointOfInstantiation,
Saar Razfdf80e82019-12-06 01:30:21 +0200375 ConstraintSubstitution, NamedDecl *Template,
Saar Raz5d98ba62019-10-15 15:24:26 +0000376 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
377 : InstantiatingTemplate(
378 SemaRef, CodeSynthesisContext::ConstraintSubstitution,
379 PointOfInstantiation, InstantiationRange, Template, nullptr,
380 {}, &DeductionInfo) {}
381
Richard Smith13381222017-02-23 21:43:43 +0000382void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
383 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
384 InNonInstantiationSFINAEContext = false;
385
386 CodeSynthesisContexts.push_back(Ctx);
387
388 if (!Ctx.isInstantiationRecord())
389 ++NonInstantiationEntries;
Richard Smith26a92d52019-08-26 18:18:07 +0000390
391 // Check to see if we're low on stack space. We can't do anything about this
392 // from here, but we can at least warn the user.
393 if (isStackNearlyExhausted())
394 warnStackExhausted(Ctx.PointOfInstantiation);
Richard Smith13381222017-02-23 21:43:43 +0000395}
396
397void Sema::popCodeSynthesisContext() {
398 auto &Active = CodeSynthesisContexts.back();
399 if (!Active.isInstantiationRecord()) {
400 assert(NonInstantiationEntries > 0);
401 --NonInstantiationEntries;
402 }
403
404 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
405
406 // Name lookup no longer looks in this template's defining module.
407 assert(CodeSynthesisContexts.size() >=
408 CodeSynthesisContextLookupModules.size() &&
409 "forgot to remove a lookup module for a template instantiation");
410 if (CodeSynthesisContexts.size() ==
411 CodeSynthesisContextLookupModules.size()) {
412 if (Module *M = CodeSynthesisContextLookupModules.back())
413 LookupModulesCache.erase(M);
414 CodeSynthesisContextLookupModules.pop_back();
415 }
416
417 // If we've left the code synthesis context for the current context stack,
418 // stop remembering that we've emitted that stack.
419 if (CodeSynthesisContexts.size() ==
420 LastEmittedCodeSynthesisContextDepth)
421 LastEmittedCodeSynthesisContextDepth = 0;
422
423 CodeSynthesisContexts.pop_back();
424}
425
Douglas Gregor85673582009-05-18 17:01:57 +0000426void Sema::InstantiatingTemplate::Clear() {
427 if (!Invalid) {
Richard Smith13381222017-02-23 21:43:43 +0000428 if (!AlreadyInstantiating) {
429 auto &Active = SemaRef.CodeSynthesisContexts.back();
Richard Smith54f18e82016-08-31 02:15:21 +0000430 SemaRef.InstantiatingSpecializations.erase(
431 std::make_pair(Active.Entity, Active.Kind));
Richard Smith13381222017-02-23 21:43:43 +0000432 }
Richard Smith54f18e82016-08-31 02:15:21 +0000433
Gabor Horvath207e7b12018-02-10 14:04:45 +0000434 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
435 SemaRef.CodeSynthesisContexts.back());
Richard Smith13381222017-02-23 21:43:43 +0000436
Gabor Horvath207e7b12018-02-10 14:04:45 +0000437 SemaRef.popCodeSynthesisContext();
Douglas Gregor85673582009-05-18 17:01:57 +0000438 Invalid = true;
439 }
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000440}
441
Douglas Gregor79cf6032009-03-10 20:44:00 +0000442bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
443 SourceLocation PointOfInstantiation,
444 SourceRange InstantiationRange) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000445 assert(SemaRef.NonInstantiationEntries <=
Richard Smith696e3122017-02-23 01:43:54 +0000446 SemaRef.CodeSynthesisContexts.size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000447 if ((SemaRef.CodeSynthesisContexts.size() -
Douglas Gregor84d49a22009-11-11 21:54:23 +0000448 SemaRef.NonInstantiationEntries)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000449 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregor79cf6032009-03-10 20:44:00 +0000450 return false;
451
Mike Stump11289f42009-09-09 15:08:12 +0000452 SemaRef.Diag(PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000453 diag::err_template_recursion_depth_exceeded)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000454 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregor79cf6032009-03-10 20:44:00 +0000455 << InstantiationRange;
456 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000457 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000458 return true;
459}
460
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000461/// Prints the current instantiation stack through a series of
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000462/// notes.
463void Sema::PrintInstantiationStack() {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000464 // Determine which template instantiations to skip, if any.
Richard Smith696e3122017-02-23 01:43:54 +0000465 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000466 unsigned Limit = Diags.getTemplateBacktraceLimit();
Richard Smith696e3122017-02-23 01:43:54 +0000467 if (Limit && Limit < CodeSynthesisContexts.size()) {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000468 SkipStart = Limit / 2 + Limit % 2;
Richard Smith696e3122017-02-23 01:43:54 +0000469 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000470 }
471
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000472 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000473 unsigned InstantiationIdx = 0;
Richard Smith696e3122017-02-23 01:43:54 +0000474 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
475 Active = CodeSynthesisContexts.rbegin(),
476 ActiveEnd = CodeSynthesisContexts.rend();
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000477 Active != ActiveEnd;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000478 ++Active, ++InstantiationIdx) {
479 // Skip this instantiation?
480 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
481 if (InstantiationIdx == SkipStart) {
482 // Note that we're skipping instantiations.
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000483 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000484 diag::note_instantiation_contexts_suppressed)
Richard Smith696e3122017-02-23 01:43:54 +0000485 << unsigned(CodeSynthesisContexts.size() - Limit);
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000486 }
487 continue;
488 }
489
Douglas Gregor79cf6032009-03-10 20:44:00 +0000490 switch (Active->Kind) {
Richard Smith696e3122017-02-23 01:43:54 +0000491 case CodeSynthesisContext::TemplateInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000492 Decl *D = Active->Entity;
Douglas Gregor85673582009-05-18 17:01:57 +0000493 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
494 unsigned DiagID = diag::note_template_member_class_here;
495 if (isa<ClassTemplateSpecializationDecl>(Record))
496 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000497 Diags.Report(Active->PointOfInstantiation, DiagID)
Richard Smith792c22d2016-12-24 04:09:05 +0000498 << Record << Active->InstantiationRange;
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000499 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +0000500 unsigned DiagID;
501 if (Function->getPrimaryTemplate())
502 DiagID = diag::note_function_template_spec_here;
503 else
504 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000505 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000506 << Function
507 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000508 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000509 Diags.Report(Active->PointOfInstantiation,
Larisse Voufodbd65772013-08-14 20:15:02 +0000510 VD->isStaticDataMember()?
511 diag::note_template_static_data_member_def_here
512 : diag::note_template_variable_def_here)
Richard Smith3f1b5d02011-05-05 21:57:07 +0000513 << VD
514 << Active->InstantiationRange;
Richard Smith4b38ded2012-03-14 23:13:10 +0000515 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
516 Diags.Report(Active->PointOfInstantiation,
517 diag::note_template_enum_def_here)
518 << ED
519 << Active->InstantiationRange;
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000520 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
521 Diags.Report(Active->PointOfInstantiation,
522 diag::note_template_nsdmi_here)
523 << FD << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000524 } else {
525 Diags.Report(Active->PointOfInstantiation,
526 diag::note_template_type_alias_instantiation_here)
527 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000528 << Active->InstantiationRange;
Douglas Gregor85673582009-05-18 17:01:57 +0000529 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000530 break;
531 }
532
Richard Smith696e3122017-02-23 01:43:54 +0000533 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
Richard Smith54f18e82016-08-31 02:15:21 +0000534 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000535 SmallVector<char, 128> TemplateArgsStr;
536 llvm::raw_svector_ostream OS(TemplateArgsStr);
537 Template->printName(OS);
Serge Pavlov03e672c2017-11-28 16:14:14 +0000538 printTemplateArgumentList(OS, Active->template_arguments(),
539 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000540 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000541 diag::note_default_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000542 << OS.str()
Douglas Gregor79cf6032009-03-10 20:44:00 +0000543 << Active->InstantiationRange;
544 break;
545 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000546
Richard Smith696e3122017-02-23 01:43:54 +0000547 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000548 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000549 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000550 diag::note_explicit_template_arg_substitution_here)
Fangrui Song6907ce22018-07-30 19:24:48 +0000551 << FnTmpl
552 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
553 Active->TemplateArgs,
Douglas Gregor607f1412010-03-30 20:35:20 +0000554 Active->NumTemplateArgs)
555 << Active->InstantiationRange;
Douglas Gregor637d9982009-06-10 23:47:09 +0000556 break;
557 }
Mike Stump11289f42009-09-09 15:08:12 +0000558
Richard Smith696e3122017-02-23 01:43:54 +0000559 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
Richard Smithe68a38f2016-12-24 04:20:31 +0000560 if (FunctionTemplateDecl *FnTmpl =
561 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000562 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000563 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000564 << FnTmpl
Fangrui Song6907ce22018-07-30 19:24:48 +0000565 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
566 Active->TemplateArgs,
Douglas Gregor607f1412010-03-30 20:35:20 +0000567 Active->NumTemplateArgs)
568 << Active->InstantiationRange;
Richard Smithe68a38f2016-12-24 04:20:31 +0000569 } else {
570 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
571 isa<VarTemplateSpecializationDecl>(Active->Entity);
Richard Smith0e617ec2016-12-27 07:56:27 +0000572 bool IsTemplate = false;
Richard Smithe68a38f2016-12-24 04:20:31 +0000573 TemplateParameterList *Params;
Richard Smith0e617ec2016-12-27 07:56:27 +0000574 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
575 IsTemplate = true;
576 Params = D->getTemplateParameters();
577 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
Richard Smithe68a38f2016-12-24 04:20:31 +0000578 Active->Entity)) {
579 Params = D->getTemplateParameters();
580 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
581 Active->Entity)) {
582 Params = D->getTemplateParameters();
583 } else {
584 llvm_unreachable("unexpected template kind");
585 }
586
Richard Smithe68a38f2016-12-24 04:20:31 +0000587 Diags.Report(Active->PointOfInstantiation,
588 diag::note_deduced_template_arg_substitution_here)
Richard Smith0e617ec2016-12-27 07:56:27 +0000589 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
Fangrui Song6907ce22018-07-30 19:24:48 +0000590 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
Richard Smithe68a38f2016-12-24 04:20:31 +0000591 Active->NumTemplateArgs)
592 << Active->InstantiationRange;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000593 }
594 break;
Richard Smithe68a38f2016-12-24 04:20:31 +0000595 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000596
Richard Smith696e3122017-02-23 01:43:54 +0000597 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000598 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson657bad42009-09-05 05:14:19 +0000599 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +0000600
Benjamin Kramer9170e912013-02-22 15:46:01 +0000601 SmallVector<char, 128> TemplateArgsStr;
602 llvm::raw_svector_ostream OS(TemplateArgsStr);
603 FD->printName(OS);
Serge Pavlov03e672c2017-11-28 16:14:14 +0000604 printTemplateArgumentList(OS, Active->template_arguments(),
605 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000606 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000607 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000608 << OS.str()
Anders Carlsson657bad42009-09-05 05:14:19 +0000609 << Active->InstantiationRange;
610 break;
611 }
Mike Stump11289f42009-09-09 15:08:12 +0000612
Richard Smith696e3122017-02-23 01:43:54 +0000613 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000614 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000615 std::string Name;
616 if (!Parm->getName().empty())
617 Name = std::string(" '") + Parm->getName().str() + "'";
Craig Topperc3ec1492014-05-26 06:22:03 +0000618
619 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000620 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
621 TemplateParams = Template->getTemplateParameters();
622 else
623 TemplateParams =
624 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
625 ->getTemplateParameters();
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000626 Diags.Report(Active->PointOfInstantiation,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000627 diag::note_prior_template_arg_substitution)
628 << isa<TemplateTemplateParmDecl>(Parm)
629 << Name
Fangrui Song6907ce22018-07-30 19:24:48 +0000630 << getTemplateArgumentBindingsText(TemplateParams,
631 Active->TemplateArgs,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000632 Active->NumTemplateArgs)
633 << Active->InstantiationRange;
634 break;
635 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000636
Richard Smith696e3122017-02-23 01:43:54 +0000637 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
Craig Topperc3ec1492014-05-26 06:22:03 +0000638 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000639 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
640 TemplateParams = Template->getTemplateParameters();
641 else
642 TemplateParams =
643 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
644 ->getTemplateParameters();
645
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000646 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000647 diag::note_template_default_arg_checking)
Fangrui Song6907ce22018-07-30 19:24:48 +0000648 << getTemplateArgumentBindingsText(TemplateParams,
649 Active->TemplateArgs,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000650 Active->NumTemplateArgs)
651 << Active->InstantiationRange;
652 break;
653 }
Richard Smithf623c962012-04-17 00:58:00 +0000654
Richard Smith5159bbad2018-09-05 22:30:37 +0000655 case CodeSynthesisContext::ExceptionSpecEvaluation:
656 Diags.Report(Active->PointOfInstantiation,
657 diag::note_evaluating_exception_spec_here)
658 << cast<FunctionDecl>(Active->Entity);
659 break;
660
Richard Smith696e3122017-02-23 01:43:54 +0000661 case CodeSynthesisContext::ExceptionSpecInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000662 Diags.Report(Active->PointOfInstantiation,
663 diag::note_template_exception_spec_instantiation_here)
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000664 << cast<FunctionDecl>(Active->Entity)
Richard Smithf623c962012-04-17 00:58:00 +0000665 << Active->InstantiationRange;
666 break;
Richard Smith13381222017-02-23 21:43:43 +0000667
668 case CodeSynthesisContext::DeclaringSpecialMember:
669 Diags.Report(Active->PointOfInstantiation,
670 diag::note_in_declaration_of_implicit_special_member)
671 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
672 break;
Richard Smith883dbc42017-05-25 22:47:05 +0000673
Gabor Horvath207e7b12018-02-10 14:04:45 +0000674 case CodeSynthesisContext::DefiningSynthesizedFunction: {
Richard Smithcafc7412019-12-04 15:25:27 -0800675 // FIXME: For synthesized functions that are not defaulted,
676 // produce a note.
677 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
678 DefaultedFunctionKind DFK =
679 FD ? getDefaultedFunctionKind(FD) : DefaultedFunctionKind();
680 if (DFK.isSpecialMember()) {
681 auto *MD = cast<CXXMethodDecl>(FD);
Richard Smith883dbc42017-05-25 22:47:05 +0000682 Diags.Report(Active->PointOfInstantiation,
683 diag::note_member_synthesized_at)
Richard Smithcafc7412019-12-04 15:25:27 -0800684 << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
685 << Context.getTagDeclType(MD->getParent());
686 } else if (DFK.isComparison()) {
687 Diags.Report(Active->PointOfInstantiation,
688 diag::note_comparison_synthesized_at)
689 << (int)DFK.asComparison()
690 << Context.getTagDeclType(
691 cast<CXXRecordDecl>(FD->getLexicalDeclContext()));
Richard Smith883dbc42017-05-25 22:47:05 +0000692 }
693 break;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000694 }
Gabor Horvath207e7b12018-02-10 14:04:45 +0000695
Richard Smith974c8b72019-10-19 00:04:43 +0000696 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
697 Diags.Report(Active->Entity->getLocation(),
698 diag::note_rewriting_operator_as_spaceship);
699 break;
700
Gabor Horvath207e7b12018-02-10 14:04:45 +0000701 case CodeSynthesisContext::Memoization:
702 break;
Saar Raz5d98ba62019-10-15 15:24:26 +0000703
Saar Razfdf80e82019-12-06 01:30:21 +0200704 case CodeSynthesisContext::ConstraintsCheck: {
705 unsigned DiagID = 0;
706 if (isa<ConceptDecl>(Active->Entity))
707 DiagID = diag::note_concept_specialization_here;
708 else if (isa<TemplateDecl>(Active->Entity))
709 DiagID = diag::note_checking_constraints_for_template_id_here;
710 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
711 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
712 else {
713 assert(isa<ClassTemplatePartialSpecializationDecl>(Active->Entity));
714 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
Saar Raz5d98ba62019-10-15 15:24:26 +0000715 }
Saar Razfdf80e82019-12-06 01:30:21 +0200716 SmallVector<char, 128> TemplateArgsStr;
717 llvm::raw_svector_ostream OS(TemplateArgsStr);
718 cast<NamedDecl>(Active->Entity)->printName(OS);
719 printTemplateArgumentList(OS, Active->template_arguments(),
720 getPrintingPolicy());
721 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
722 << Active->InstantiationRange;
Saar Raz5d98ba62019-10-15 15:24:26 +0000723 break;
Saar Razfdf80e82019-12-06 01:30:21 +0200724 }
Saar Raz5d98ba62019-10-15 15:24:26 +0000725 case CodeSynthesisContext::ConstraintSubstitution:
726 Diags.Report(Active->PointOfInstantiation,
727 diag::note_constraint_substitution_here)
728 << Active->InstantiationRange;
729 break;
Gabor Horvath207e7b12018-02-10 14:04:45 +0000730 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000731 }
732}
733
David Blaikie05785d12013-02-20 22:23:23 +0000734Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregoredb76852011-01-27 22:31:44 +0000735 if (InNonInstantiationSFINAEContext)
Craig Topperc3ec1492014-05-26 06:22:03 +0000736 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregoredb76852011-01-27 22:31:44 +0000737
Richard Smith696e3122017-02-23 01:43:54 +0000738 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
739 Active = CodeSynthesisContexts.rbegin(),
740 ActiveEnd = CodeSynthesisContexts.rend();
Douglas Gregor33834512009-06-14 07:33:30 +0000741 Active != ActiveEnd;
Fangrui Song6907ce22018-07-30 19:24:48 +0000742 ++Active)
Douglas Gregor84d49a22009-11-11 21:54:23 +0000743 {
Richard Smith13381222017-02-23 21:43:43 +0000744 switch (Active->Kind) {
Richard Smith696e3122017-02-23 01:43:54 +0000745 case CodeSynthesisContext::TemplateInstantiation:
Richard Smith72249ba2012-04-26 07:24:08 +0000746 // An instantiation of an alias template may or may not be a SFINAE
747 // context, depending on what else is on the stack.
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000748 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smith72249ba2012-04-26 07:24:08 +0000749 break;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +0000750 LLVM_FALLTHROUGH;
Richard Smith696e3122017-02-23 01:43:54 +0000751 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
752 case CodeSynthesisContext::ExceptionSpecInstantiation:
Saar Raz5d98ba62019-10-15 15:24:26 +0000753 case CodeSynthesisContext::ConstraintsCheck:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000754 // This is a template instantiation, so there is no SFINAE.
David Blaikie7a30dc52013-02-21 01:47:18 +0000755 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000756
Richard Smith696e3122017-02-23 01:43:54 +0000757 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
758 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
759 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000760 // A default template argument instantiation and substitution into
Fangrui Song6907ce22018-07-30 19:24:48 +0000761 // template parameters with arguments for prior parameters may or may
Douglas Gregore62e6a02009-11-11 19:13:48 +0000762 // not be a SFINAE context; look further up the stack.
Douglas Gregor33834512009-06-14 07:33:30 +0000763 break;
Mike Stump11289f42009-09-09 15:08:12 +0000764
Richard Smith696e3122017-02-23 01:43:54 +0000765 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
766 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
Saar Raz5d98ba62019-10-15 15:24:26 +0000767 case CodeSynthesisContext::ConstraintSubstitution:
768 // We're either substituting explicitly-specified template arguments
769 // or deduced template arguments or a constraint expression, so SFINAE
770 // applies.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000771 assert(Active->DeductionInfo && "Missing deduction info pointer");
772 return Active->DeductionInfo;
Richard Smith13381222017-02-23 21:43:43 +0000773
774 case CodeSynthesisContext::DeclaringSpecialMember:
Richard Smith883dbc42017-05-25 22:47:05 +0000775 case CodeSynthesisContext::DefiningSynthesizedFunction:
Richard Smith974c8b72019-10-19 00:04:43 +0000776 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
Richard Smith13381222017-02-23 21:43:43 +0000777 // This happens in a context unrelated to template instantiation, so
778 // there is no SFINAE.
779 return None;
Gabor Horvath207e7b12018-02-10 14:04:45 +0000780
Richard Smith5159bbad2018-09-05 22:30:37 +0000781 case CodeSynthesisContext::ExceptionSpecEvaluation:
782 // FIXME: This should not be treated as a SFINAE context, because
783 // we will cache an incorrect exception specification. However, clang
784 // bootstrap relies this! See PR31692.
785 break;
786
Gabor Horvath207e7b12018-02-10 14:04:45 +0000787 case CodeSynthesisContext::Memoization:
788 break;
Douglas Gregor33834512009-06-14 07:33:30 +0000789 }
Richard Smith13381222017-02-23 21:43:43 +0000790
791 // The inner context was transparent for SFINAE. If it occurred within a
792 // non-instantiation SFINAE context, then SFINAE applies.
793 if (Active->SavedInNonInstantiationSFINAEContext)
794 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregor33834512009-06-14 07:33:30 +0000795 }
796
David Blaikie7a30dc52013-02-21 01:47:18 +0000797 return None;
Douglas Gregor33834512009-06-14 07:33:30 +0000798}
799
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000800//===----------------------------------------------------------------------===/
801// Template Instantiation for Types
802//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000803namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000804 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000805 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000806 SourceLocation Loc;
807 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000808
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000809 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000810 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000811
812 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000813 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000814 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000815 DeclarationName Entity)
816 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000817 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000818
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000819 /// Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-08-04 16:50:30 +0000820 /// transformed.
821 ///
822 /// For the purposes of template instantiation, a type has already been
823 /// transformed if it is NULL or if it is not dependent.
Douglas Gregor5597ab42010-05-07 23:12:07 +0000824 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000825
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000826 /// Returns the location of the entity being instantiated, if known.
Douglas Gregord6ff3322009-08-04 16:50:30 +0000827 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000828
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000829 /// Returns the name of the entity being instantiated, if any.
Douglas Gregord6ff3322009-08-04 16:50:30 +0000830 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000831
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000832 /// Sets the "base" location and entity when that
Douglas Gregoref6ab412009-10-27 06:26:26 +0000833 /// information is known based on another transformation.
834 void setBase(SourceLocation Loc, DeclarationName Entity) {
835 this->Loc = Loc;
836 this->Entity = Entity;
837 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000838
839 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
840 SourceRange PatternRange,
Robert Wilhelm16e94b92013-08-09 18:02:13 +0000841 ArrayRef<UnexpandedParameterPack> Unexpanded,
842 bool &ShouldExpand, bool &RetainExpansion,
David Blaikie05785d12013-02-20 22:23:23 +0000843 Optional<unsigned> &NumExpansions) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000844 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000845 PatternRange, Unexpanded,
Fangrui Song6907ce22018-07-30 19:24:48 +0000846 TemplateArgs,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000847 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000848 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000849 NumExpansions);
850 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000851
Fangrui Song6907ce22018-07-30 19:24:48 +0000852 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
Douglas Gregorf3010112011-01-07 16:43:16 +0000853 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
854 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000855
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000856 TemplateArgument ForgetPartiallySubstitutedPack() {
857 TemplateArgument Result;
858 if (NamedDecl *PartialPack
859 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
860 MultiLevelTemplateArgumentList &TemplateArgs
861 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
862 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000863 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000864 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
865 Result = TemplateArgs(Depth, Index);
866 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
867 }
868 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000869
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000870 return Result;
871 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000872
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000873 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
874 if (Arg.isNull())
875 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000876
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000877 if (NamedDecl *PartialPack
878 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
879 MultiLevelTemplateArgumentList &TemplateArgs
880 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
881 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000882 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000883 TemplateArgs.setArgument(Depth, Index, Arg);
884 }
885 }
886
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000887 /// Transform the given declaration by instantiating a reference to
Douglas Gregord6ff3322009-08-04 16:50:30 +0000888 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000889 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000890
Fangrui Song6907ce22018-07-30 19:24:48 +0000891 void transformAttrs(Decl *Old, Decl *New) {
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000892 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
893 }
894
Richard Smithb2997f52019-05-21 20:10:50 +0000895 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
896 if (Old->isParameterPack()) {
897 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);
898 for (auto *New : NewDecls)
899 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
900 Old, cast<VarDecl>(New));
901 return;
902 }
903
904 assert(NewDecls.size() == 1 &&
905 "should only have multiple expansions for a pack");
906 Decl *New = NewDecls.front();
907
Richard Smithc38498f2015-04-27 21:27:54 +0000908 // If we've instantiated the call operator of a lambda or the call
909 // operator template of a generic lambda, update the "instantiation of"
910 // information.
911 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
912 if (NewMD && isLambdaCallOperator(NewMD)) {
913 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
914 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
915 NewTD->setInstantiatedFromMemberTemplate(
916 OldMD->getDescribedFunctionTemplate());
917 else
918 NewMD->setInstantiationOfMemberFunction(OldMD,
919 TSK_ImplicitInstantiation);
920 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000921
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000922 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
Richard Smithc7649dc2016-03-23 20:07:07 +0000923
924 // We recreated a local declaration, but not by instantiating it. There
925 // may be pending dependent diagnostics to produce.
926 if (auto *DC = dyn_cast<DeclContext>(Old))
927 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000928 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000929
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000930 /// Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000931 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000932 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000933
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000934 /// Transform the first qualifier within a scope by instantiating the
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000935 /// declaration.
936 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
Fangrui Song6907ce22018-07-30 19:24:48 +0000937
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000938 /// Rebuild the exception declaration and register the declaration
Douglas Gregorebe10102009-08-20 07:17:43 +0000939 /// as an instantiated local.
Fangrui Song6907ce22018-07-30 19:24:48 +0000940 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000941 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000942 SourceLocation StartLoc,
943 SourceLocation NameLoc,
944 IdentifierInfo *Name);
Mike Stump11289f42009-09-09 15:08:12 +0000945
Fangrui Song6907ce22018-07-30 19:24:48 +0000946 /// Rebuild the Objective-C exception declaration and register the
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000947 /// declaration as an instantiated local.
Fangrui Song6907ce22018-07-30 19:24:48 +0000948 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000949 TypeSourceInfo *TSInfo, QualType T);
Fangrui Song6907ce22018-07-30 19:24:48 +0000950
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000951 /// Check for tag mismatches when instantiating an
John McCall7f41d982009-09-11 04:59:25 +0000952 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000953 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
954 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000955 NestedNameSpecifierLoc QualifierLoc,
956 QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000957
Craig Topperc3ec1492014-05-26 06:22:03 +0000958 TemplateName
959 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
960 SourceLocation NameLoc,
961 QualType ObjectType = QualType(),
Richard Smithfd3dae02017-01-20 00:20:39 +0000962 NamedDecl *FirstQualifierInScope = nullptr,
963 bool AllowInjectedClassName = false);
Douglas Gregor9db53502011-03-02 18:07:45 +0000964
Tyler Nowickic724a83e2014-10-12 20:46:07 +0000965 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
966
John McCalldadc5752010-08-24 06:29:42 +0000967 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
968 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
969 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000970
John McCalldadc5752010-08-24 06:29:42 +0000971 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000972 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000973 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
974 SubstNonTypeTemplateParmPackExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000975
Richard Smithb2997f52019-05-21 20:10:50 +0000976 /// Rebuild a DeclRefExpr for a VarDecl reference.
977 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000978
Richard Smithb2997f52019-05-21 20:10:50 +0000979 /// Transform a reference to a function or init-capture parameter pack.
980 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000981
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000982 /// Transform a FunctionParmPackExpr which was built when we couldn't
Richard Smithb15fe3a2012-09-12 00:56:43 +0000983 /// expand a function parameter pack reference which refers to an expanded
984 /// pack.
985 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
986
Hans Wennborge113c202014-09-18 16:01:32 +0000987 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
Richard Smith2e321552014-11-12 02:00:47 +0000988 FunctionProtoTypeLoc TL) {
989 // Call the base version; it will forward to our overridden version below.
990 return inherited::TransformFunctionProtoType(TLB, TL);
991 }
992
993 template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +0000994 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
995 FunctionProtoTypeLoc TL,
996 CXXRecordDecl *ThisContext,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +0000997 Qualifiers ThisTypeQuals,
Richard Smith2e321552014-11-12 02:00:47 +0000998 Fn TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +0000999
Douglas Gregor715e4612011-01-14 22:40:04 +00001000 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001001 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001002 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001003 bool ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +00001004
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001005 /// Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +00001006 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +00001007 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001008 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001009
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001010 /// Transforms an already-substituted template type parameter pack
Douglas Gregorada4b792011-01-14 02:55:32 +00001011 /// into either itself (if we aren't substituting into its pack expansion)
1012 /// or the appropriate substituted argument.
1013 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1014 SubstTemplateTypeParmPackTypeLoc TL);
1015
Richard Smith2589b9802012-07-25 03:56:55 +00001016 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1017 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1018 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
1019 }
1020
David Majnemerb1004102014-03-02 18:46:05 +00001021 TemplateParameterList *TransformTemplateParameterList(
Faisal Vali2cba1332013-10-23 06:44:28 +00001022 TemplateParameterList *OrigTPL) {
1023 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
Fangrui Song6907ce22018-07-30 19:24:48 +00001024
Faisal Vali2cba1332013-10-23 06:44:28 +00001025 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
Fangrui Song6907ce22018-07-30 19:24:48 +00001026 TemplateDeclInstantiator DeclInstantiator(getSema(),
Faisal Vali2cba1332013-10-23 06:44:28 +00001027 /* DeclContext *Owner */ Owner, TemplateArgs);
Fangrui Song6907ce22018-07-30 19:24:48 +00001028 return DeclInstantiator.SubstTemplateParams(OrigTPL);
Faisal Vali2cba1332013-10-23 06:44:28 +00001029 }
John McCall7c454bb2011-07-15 05:09:51 +00001030 private:
1031 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
1032 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001033 TemplateArgument arg);
Douglas Gregord6ff3322009-08-04 16:50:30 +00001034 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001035}
Douglas Gregor04318252009-07-06 15:59:29 +00001036
Douglas Gregor5597ab42010-05-07 23:12:07 +00001037bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1038 if (T.isNull())
1039 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00001040
Douglas Gregor678d76c2011-07-01 01:22:09 +00001041 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +00001042 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001043
Douglas Gregor5597ab42010-05-07 23:12:07 +00001044 getSema().MarkDeclarationsReferencedInType(Loc, T);
1045 return true;
1046}
1047
Eli Friedman8917ad52013-07-19 19:40:38 +00001048static TemplateArgument
1049getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001050 assert(S.ArgumentPackSubstitutionIndex >= 0);
Eli Friedman8917ad52013-07-19 19:40:38 +00001051 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1052 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
1053 if (Arg.isPackExpansion())
1054 Arg = Arg.getPackExpansionPattern();
1055 return Arg;
1056}
1057
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001058Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +00001059 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +00001060 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001061
Douglas Gregor2b6ca462009-09-03 21:38:09 +00001062 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +00001063 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +00001064 // If the corresponding template argument is NULL or non-existent, it's
1065 // because we are performing instantiation from explicitly-specified
1066 // template arguments in a function template, but there were some
1067 // arguments left unspecified.
1068 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1069 TTP->getPosition()))
1070 return D;
1071
Douglas Gregorf5500772011-01-05 15:48:55 +00001072 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
Fangrui Song6907ce22018-07-30 19:24:48 +00001073
Douglas Gregorf5500772011-01-05 15:48:55 +00001074 if (TTP->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001075 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregorf5500772011-01-05 15:48:55 +00001076 "Missing argument pack");
Eli Friedman8917ad52013-07-19 19:40:38 +00001077 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorf5500772011-01-05 15:48:55 +00001078 }
1079
Richard Smith1abacfc2017-08-29 22:14:43 +00001080 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001081 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +00001082 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001083 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001084 }
Mike Stump11289f42009-09-09 15:08:12 +00001085
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001086 // Fall through to find the instantiated declaration for this template
1087 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +00001088 }
Mike Stump11289f42009-09-09 15:08:12 +00001089
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001090 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +00001091}
1092
Douglas Gregor25289362010-03-01 17:25:41 +00001093Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +00001094 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +00001095 if (!Inst)
Craig Topperc3ec1492014-05-26 06:22:03 +00001096 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001097
Douglas Gregorebe10102009-08-20 07:17:43 +00001098 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1099 return Inst;
1100}
1101
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001102NamedDecl *
Fangrui Song6907ce22018-07-30 19:24:48 +00001103TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001104 SourceLocation Loc) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001105 // If the first part of the nested-name-specifier was a template type
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001106 // parameter, instantiate that type parameter down to a tag type.
1107 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001108 const TemplateTypeParmType *TTP
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001109 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Fangrui Song6907ce22018-07-30 19:24:48 +00001110
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001111 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001112 // FIXME: This needs testing w/ member access expressions.
1113 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
Fangrui Song6907ce22018-07-30 19:24:48 +00001114
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001115 if (TTP->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001116 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001117 "Missing argument pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001118
Douglas Gregore1d60df2011-01-14 23:41:42 +00001119 if (getSema().ArgumentPackSubstitutionIndex == -1)
Craig Topperc3ec1492014-05-26 06:22:03 +00001120 return nullptr;
1121
Eli Friedman8917ad52013-07-19 19:40:38 +00001122 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001123 }
1124
1125 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001126 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001127 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Fangrui Song6907ce22018-07-30 19:24:48 +00001128
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001129 if (const TagType *Tag = T->getAs<TagType>())
1130 return Tag->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001131
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001132 // The resulting type is not a tag; complain.
1133 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
Craig Topperc3ec1492014-05-26 06:22:03 +00001134 return nullptr;
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001135 }
1136 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001137
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001138 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001139}
1140
Douglas Gregorebe10102009-08-20 07:17:43 +00001141VarDecl *
1142TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +00001143 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001144 SourceLocation StartLoc,
1145 SourceLocation NameLoc,
1146 IdentifierInfo *Name) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00001147 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001148 StartLoc, NameLoc, Name);
Douglas Gregorf4e837f2010-04-26 17:57:08 +00001149 if (Var)
1150 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1151 return Var;
1152}
1153
Fangrui Song6907ce22018-07-30 19:24:48 +00001154VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1155 TypeSourceInfo *TSInfo,
Douglas Gregorf4e837f2010-04-26 17:57:08 +00001156 QualType T) {
1157 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1158 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +00001159 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1160 return Var;
1161}
1162
John McCall7f41d982009-09-11 04:59:25 +00001163QualType
John McCall954b5de2010-11-04 19:04:38 +00001164TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1165 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001166 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara6150c882010-05-11 21:36:43 +00001167 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +00001168 if (const TagType *TT = T->getAs<TagType>()) {
1169 TagDecl* TD = TT->getDecl();
1170
John McCall954b5de2010-11-04 19:04:38 +00001171 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +00001172
John McCall7f41d982009-09-11 04:59:25 +00001173 IdentifierInfo *Id = TD->getIdentifier();
1174
1175 // TODO: should we even warn on struct/class mismatches for this? Seems
1176 // like it's likely to produce a lot of spurious errors.
Richard Smith80b3c5a2012-08-17 00:12:27 +00001177 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001178 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieucaa33d32011-06-10 03:11:26 +00001179 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001180 TagLocation, Id)) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001181 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1182 << Id
1183 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1184 TD->getKindName());
1185 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1186 }
John McCall7f41d982009-09-11 04:59:25 +00001187 }
1188 }
1189
John McCall954b5de2010-11-04 19:04:38 +00001190 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1191 Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001192 QualifierLoc,
1193 T);
John McCall7f41d982009-09-11 04:59:25 +00001194}
1195
Richard Smithfd3dae02017-01-20 00:20:39 +00001196TemplateName TemplateInstantiator::TransformTemplateName(
1197 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1198 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1199 bool AllowInjectedClassName) {
Douglas Gregor9db53502011-03-02 18:07:45 +00001200 if (TemplateTemplateParmDecl *TTP
1201 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1202 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1203 // If the corresponding template argument is NULL or non-existent, it's
1204 // because we are performing instantiation from explicitly-specified
1205 // template arguments in a function template, but there were some
1206 // arguments left unspecified.
1207 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1208 TTP->getPosition()))
1209 return Name;
Fangrui Song6907ce22018-07-30 19:24:48 +00001210
Douglas Gregor9db53502011-03-02 18:07:45 +00001211 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
Fangrui Song6907ce22018-07-30 19:24:48 +00001212
Douglas Gregor9db53502011-03-02 18:07:45 +00001213 if (TTP->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001214 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregor9db53502011-03-02 18:07:45 +00001215 "Missing argument pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001216
Douglas Gregor9db53502011-03-02 18:07:45 +00001217 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1218 // We have the template argument pack to substitute, but we're not
1219 // actually expanding the enclosing pack expansion yet. So, just
1220 // keep the entire argument pack.
1221 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1222 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001223
1224 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor9db53502011-03-02 18:07:45 +00001225 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001226
Richard Smith1abacfc2017-08-29 22:14:43 +00001227 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001228 assert(!Template.isNull() && "Null template template argument");
Richard Smith1abacfc2017-08-29 22:14:43 +00001229 assert(!Template.getAsQualifiedTemplateName() &&
1230 "template decl to substitute is qualified?");
John McCalld9dfe3a2011-06-30 08:33:18 +00001231
1232 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregor9db53502011-03-02 18:07:45 +00001233 return Template;
1234 }
1235 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001236
Douglas Gregor9db53502011-03-02 18:07:45 +00001237 if (SubstTemplateTemplateParmPackStorage *SubstPack
1238 = Name.getAsSubstTemplateTemplateParmPack()) {
1239 if (getSema().ArgumentPackSubstitutionIndex == -1)
1240 return Name;
Fangrui Song6907ce22018-07-30 19:24:48 +00001241
Eli Friedman8917ad52013-07-19 19:40:38 +00001242 TemplateArgument Arg = SubstPack->getArgumentPack();
1243 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Richard Smith1abacfc2017-08-29 22:14:43 +00001244 return Arg.getAsTemplate().getNameToSubstitute();
Douglas Gregor9db53502011-03-02 18:07:45 +00001245 }
Richard Smithfd3dae02017-01-20 00:20:39 +00001246
1247 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1248 FirstQualifierInScope,
1249 AllowInjectedClassName);
Douglas Gregor9db53502011-03-02 18:07:45 +00001250}
1251
Fangrui Song6907ce22018-07-30 19:24:48 +00001252ExprResult
John McCall47f29ea2009-12-08 09:21:05 +00001253TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +00001254 if (!E->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001255 return E;
Anders Carlsson0b209a82009-09-11 01:22:35 +00001256
Bruno Ricci17ff0262018-10-27 19:21:19 +00001257 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
Anders Carlsson0b209a82009-09-11 01:22:35 +00001258}
1259
John McCalldadc5752010-08-24 06:29:42 +00001260ExprResult
John McCall13481c52010-02-06 08:42:39 +00001261TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001262 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +00001263 // If the corresponding template argument is NULL or non-existent, it's
1264 // because we are performing instantiation from explicitly-specified
1265 // template arguments in a function template, but there were some
1266 // arguments left unspecified.
1267 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1268 NTTP->getPosition()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001269 return E;
Mike Stump11289f42009-09-09 15:08:12 +00001270
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001271 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
Richard Smithb4f96252017-02-21 06:30:38 +00001272
1273 if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1274 // We're performing a partial substitution, so the substituted argument
1275 // could be dependent. As a result we can't create a SubstNonType*Expr
1276 // node now, since that represents a fully-substituted argument.
1277 // FIXME: We should have some AST representation for this.
1278 if (Arg.getKind() == TemplateArgument::Pack) {
1279 // FIXME: This won't work for alias templates.
1280 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1281 "unexpected pack arguments in partial substitution");
1282 Arg = Arg.pack_begin()->getPackExpansionPattern();
1283 }
1284 assert(Arg.getKind() == TemplateArgument::Expression &&
1285 "unexpected nontype template argument kind in partial substitution");
1286 return Arg.getAsExpr();
1287 }
1288
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001289 if (NTTP->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001290 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001291 "Missing argument pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001292
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001293 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001294 // We have an argument pack, but we can't select a particular argument
1295 // out of it yet. Therefore, we'll build an expression to hold on to that
1296 // argument pack.
1297 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
Fangrui Song6907ce22018-07-30 19:24:48 +00001298 E->getLocation(),
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001299 NTTP->getDeclName());
1300 if (TargetType.isNull())
1301 return ExprError();
Richard Smithf1f20e62018-02-14 02:07:53 +00001302
1303 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1304 TargetType.getNonLValueExprType(SemaRef.Context),
1305 TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP,
1306 E->getLocation(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001307 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001308
Eli Friedman8917ad52013-07-19 19:40:38 +00001309 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001310 }
Mike Stump11289f42009-09-09 15:08:12 +00001311
John McCall7c454bb2011-07-15 05:09:51 +00001312 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1313}
1314
Tyler Nowickic724a83e2014-10-12 20:46:07 +00001315const LoopHintAttr *
1316TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1317 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1318
1319 if (TransformedExpr == LH->getValue())
1320 return LH;
1321
1322 // Generate error if there is a problem with the value.
1323 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1324 return LH;
1325
1326 // Create new LoopHintValueAttr with integral expression in place of the
1327 // non-type template parameter.
Erich Keane6a24e802019-09-13 17:39:31 +00001328 return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
1329 LH->getState(), TransformedExpr, *LH);
Tyler Nowickic724a83e2014-10-12 20:46:07 +00001330}
1331
John McCall7c454bb2011-07-15 05:09:51 +00001332ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1333 NonTypeTemplateParmDecl *parm,
1334 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001335 TemplateArgument arg) {
John McCall7c454bb2011-07-15 05:09:51 +00001336 ExprResult result;
1337 QualType type;
1338
John McCall13481c52010-02-06 08:42:39 +00001339 // The template argument itself might be an expression, in which
1340 // case we just return that expression.
John McCall7c454bb2011-07-15 05:09:51 +00001341 if (arg.getKind() == TemplateArgument::Expression) {
1342 Expr *argExpr = arg.getAsExpr();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001343 result = argExpr;
John McCall7c454bb2011-07-15 05:09:51 +00001344 type = argExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001345
Eli Friedmanb826a002012-09-26 02:36:12 +00001346 } else if (arg.getKind() == TemplateArgument::Declaration ||
1347 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001348 ValueDecl *VD;
Eli Friedmanb826a002012-09-26 02:36:12 +00001349 if (arg.getKind() == TemplateArgument::Declaration) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00001350 VD = arg.getAsDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001351
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001352 // Find the instantiation of the template argument. This is
1353 // required for nested templates.
1354 VD = cast_or_null<ValueDecl>(
1355 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1356 if (!VD)
1357 return ExprError();
1358 } else {
1359 // Propagate NULL template argument.
Craig Topperc3ec1492014-05-26 06:22:03 +00001360 VD = nullptr;
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001361 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001362
John McCall15dda372010-02-06 10:23:53 +00001363 // Derive the type we want the substituted decl to have. This had
1364 // better be non-dependent, or these checks will have serious problems.
John McCall7c454bb2011-07-15 05:09:51 +00001365 if (parm->isExpandedParameterPack()) {
1366 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
Fangrui Song6907ce22018-07-30 19:24:48 +00001367 } else if (parm->isParameterPack() &&
John McCall7c454bb2011-07-15 05:09:51 +00001368 isa<PackExpansionType>(parm->getType())) {
1369 type = SemaRef.SubstType(
1370 cast<PackExpansionType>(parm->getType())->getPattern(),
1371 TemplateArgs, loc, parm->getDeclName());
1372 } else {
Richard Smith5f274382016-09-28 23:55:27 +00001373 type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1374 TemplateArgs, loc, parm->getDeclName());
John McCall7c454bb2011-07-15 05:09:51 +00001375 }
1376 assert(!type.isNull() && "type substitution failed for param type");
1377 assert(!type->isDependentType() && "param type still dependent");
1378 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCall13481c52010-02-06 08:42:39 +00001379
John McCall7c454bb2011-07-15 05:09:51 +00001380 if (!result.isInvalid()) type = result.get()->getType();
1381 } else {
1382 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1383
1384 // Note that this type can be different from the type of 'result',
1385 // e.g. if it's an enum type.
1386 type = arg.getIntegralType();
1387 }
1388 if (result.isInvalid()) return ExprError();
1389
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001390 Expr *resultExpr = result.get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001391 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1392 type, resultExpr->getValueKind(), loc, parm, resultExpr);
John McCall13481c52010-02-06 08:42:39 +00001393}
Fangrui Song6907ce22018-07-30 19:24:48 +00001394
1395ExprResult
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001396TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1397 SubstNonTypeTemplateParmPackExpr *E) {
1398 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1399 // We aren't expanding the parameter pack, so just return ourselves.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001400 return E;
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001401 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001402
1403 TemplateArgument Arg = E->getArgumentPack();
1404 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall7c454bb2011-07-15 05:09:51 +00001405 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1406 E->getParameterPackLocation(),
1407 Arg);
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001408}
John McCall13481c52010-02-06 08:42:39 +00001409
Richard Smithb2997f52019-05-21 20:10:50 +00001410ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
1411 SourceLocation Loc) {
Richard Smithb15fe3a2012-09-12 00:56:43 +00001412 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1413 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1414}
1415
1416ExprResult
1417TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1418 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1419 // We can expand this parameter pack now.
Richard Smithb2997f52019-05-21 20:10:50 +00001420 VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1421 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
Richard Smithb15fe3a2012-09-12 00:56:43 +00001422 if (!VD)
1423 return ExprError();
Richard Smithb2997f52019-05-21 20:10:50 +00001424 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
Richard Smithb15fe3a2012-09-12 00:56:43 +00001425 }
1426
1427 QualType T = TransformType(E->getType());
1428 if (T.isNull())
1429 return ExprError();
1430
1431 // Transform each of the parameter expansions into the corresponding
1432 // parameters in the instantiation of the function decl.
Richard Smithb2997f52019-05-21 20:10:50 +00001433 SmallVector<VarDecl *, 8> Vars;
1434 Vars.reserve(E->getNumExpansions());
Richard Smithb15fe3a2012-09-12 00:56:43 +00001435 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1436 I != End; ++I) {
Richard Smithb2997f52019-05-21 20:10:50 +00001437 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
Richard Smithb15fe3a2012-09-12 00:56:43 +00001438 if (!D)
1439 return ExprError();
Richard Smithb2997f52019-05-21 20:10:50 +00001440 Vars.push_back(D);
Richard Smithb15fe3a2012-09-12 00:56:43 +00001441 }
1442
Richard Smith7bf8f6f2019-06-04 17:17:20 +00001443 auto *PackExpr =
1444 FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
1445 E->getParameterPackLocation(), Vars);
1446 getSema().MarkFunctionParmPackReferenced(PackExpr);
1447 return PackExpr;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001448}
1449
1450ExprResult
1451TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
Richard Smithb2997f52019-05-21 20:10:50 +00001452 VarDecl *PD) {
Richard Smithb15fe3a2012-09-12 00:56:43 +00001453 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1454 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1455 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1456 assert(Found && "no instantiation for parameter pack");
1457
1458 Decl *TransformedDecl;
1459 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
Nico Weberc153d242014-07-28 00:02:09 +00001460 // If this is a reference to a function parameter pack which we can
1461 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
Richard Smithb15fe3a2012-09-12 00:56:43 +00001462 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1463 QualType T = TransformType(E->getType());
1464 if (T.isNull())
1465 return ExprError();
Richard Smith7bf8f6f2019-06-04 17:17:20 +00001466 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
1467 E->getExprLoc(), *Pack);
1468 getSema().MarkFunctionParmPackReferenced(PackExpr);
1469 return PackExpr;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001470 }
1471
1472 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1473 } else {
1474 TransformedDecl = Found->get<Decl*>();
1475 }
1476
1477 // We have either an unexpanded pack or a specific expansion.
Richard Smithb2997f52019-05-21 20:10:50 +00001478 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
Richard Smithb15fe3a2012-09-12 00:56:43 +00001479}
1480
1481ExprResult
John McCall13481c52010-02-06 08:42:39 +00001482TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1483 NamedDecl *D = E->getDecl();
Richard Smithb15fe3a2012-09-12 00:56:43 +00001484
1485 // Handle references to non-type template parameters and non-type template
1486 // parameter packs.
John McCall13481c52010-02-06 08:42:39 +00001487 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1488 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1489 return TransformTemplateParmRefExpr(E, NTTP);
Fangrui Song6907ce22018-07-30 19:24:48 +00001490
Douglas Gregor954de172009-10-31 17:21:17 +00001491 // We have a non-type template parameter that isn't fully substituted;
1492 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001493 }
Mike Stump11289f42009-09-09 15:08:12 +00001494
Richard Smithb15fe3a2012-09-12 00:56:43 +00001495 // Handle references to function parameter packs.
Richard Smithb2997f52019-05-21 20:10:50 +00001496 if (VarDecl *PD = dyn_cast<VarDecl>(D))
Richard Smithb15fe3a2012-09-12 00:56:43 +00001497 if (PD->isParameterPack())
1498 return TransformFunctionParmPackRefExpr(E, PD);
1499
John McCall47f29ea2009-12-08 09:21:05 +00001500 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001501}
1502
John McCalldadc5752010-08-24 06:29:42 +00001503ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001504 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001505 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1506 getDescribedFunctionTemplate() &&
1507 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001508 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
Fangrui Song6907ce22018-07-30 19:24:48 +00001509 cast<FunctionDecl>(E->getParam()->getDeclContext()),
Douglas Gregor033f6752009-12-23 23:03:06 +00001510 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001511}
1512
Richard Smith2e321552014-11-12 02:00:47 +00001513template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +00001514QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1515 FunctionProtoTypeLoc TL,
1516 CXXRecordDecl *ThisContext,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001517 Qualifiers ThisTypeQuals,
Richard Smith2e321552014-11-12 02:00:47 +00001518 Fn TransformExceptionSpec) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001519 // We need a local instantiation scope for this function prototype.
1520 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
Richard Smith2e321552014-11-12 02:00:47 +00001521 return inherited::TransformFunctionProtoType(
1522 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +00001523}
1524
John McCall58f10c32010-03-11 09:03:00 +00001525ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001526TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001527 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001528 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001529 bool ExpectParameterPack) {
Anastasia Stulovaa29aa472019-11-27 11:03:11 +00001530 auto NewParm =
1531 SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1532 NumExpansions, ExpectParameterPack);
1533 if (NewParm && SemaRef.getLangOpts().OpenCL)
1534 SemaRef.deduceOpenCLAddressSpace(NewParm);
1535 return NewParm;
John McCall58f10c32010-03-11 09:03:00 +00001536}
1537
Mike Stump11289f42009-09-09 15:08:12 +00001538QualType
John McCall550e0c22009-10-21 00:40:46 +00001539TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001540 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001541 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001542 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001543 // Replace the template type parameter with its corresponding
1544 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001545
1546 // If the corresponding template argument is NULL or doesn't exist, it's
1547 // because we are performing instantiation from explicitly-specified
1548 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001549 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001550 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1551 TemplateTypeParmTypeLoc NewTL
1552 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1553 NewTL.setNameLoc(TL.getNameLoc());
1554 return TL.getType();
1555 }
Mike Stump11289f42009-09-09 15:08:12 +00001556
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001557 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
Fangrui Song6907ce22018-07-30 19:24:48 +00001558
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001559 if (T->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001560 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001561 "Missing argument pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001562
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001563 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001564 // We have the template argument pack, but we're not expanding the
1565 // enclosing pack expansion yet. Just save the template argument
1566 // pack for later substitution.
1567 QualType Result
1568 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1569 SubstTemplateTypeParmPackTypeLoc NewTL
1570 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1571 NewTL.setNameLoc(TL.getNameLoc());
1572 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001573 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001574
Eli Friedman8917ad52013-07-19 19:40:38 +00001575 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001576 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001577
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001578 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001579 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001580
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001581 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001582
1583 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001584 QualType Result
1585 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1586 SubstTemplateTypeParmTypeLoc NewTL
1587 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1588 NewTL.setNameLoc(TL.getNameLoc());
1589 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001590 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001591
1592 // The template type parameter comes from an inner template (e.g.,
1593 // the template parameter list of a member template inside the
1594 // template we are instantiating). Create a new template type
1595 // parameter with the template "level" reduced by one.
Craig Topperc3ec1492014-05-26 06:22:03 +00001596 TemplateTypeParmDecl *NewTTPDecl = nullptr;
Chandler Carruth08836322011-05-01 00:51:33 +00001597 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1598 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1599 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1600
Richard Smithb4f96252017-02-21 06:30:38 +00001601 QualType Result = getSema().Context.getTemplateTypeParmType(
1602 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1603 T->isParameterPack(), NewTTPDecl);
John McCall550e0c22009-10-21 00:40:46 +00001604 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1605 NewTL.setNameLoc(TL.getNameLoc());
1606 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001607}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001608
Fangrui Song6907ce22018-07-30 19:24:48 +00001609QualType
Douglas Gregorada4b792011-01-14 02:55:32 +00001610TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1611 TypeLocBuilder &TLB,
1612 SubstTemplateTypeParmPackTypeLoc TL) {
1613 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1614 // We aren't expanding the parameter pack, so just return ourselves.
1615 SubstTemplateTypeParmPackTypeLoc NewTL
1616 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1617 NewTL.setNameLoc(TL.getNameLoc());
1618 return TL.getType();
1619 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001620
1621 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1622 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1623 QualType Result = Arg.getAsType();
1624
Douglas Gregorada4b792011-01-14 02:55:32 +00001625 Result = getSema().Context.getSubstTemplateTypeParmType(
1626 TL.getTypePtr()->getReplacedParameter(),
1627 Result);
1628 SubstTemplateTypeParmTypeLoc NewTL
1629 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1630 NewTL.setNameLoc(TL.getNameLoc());
1631 return Result;
1632}
1633
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001634/// Perform substitution on the type T with a given set of template
John McCall76d824f2009-08-25 22:02:44 +00001635/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001636///
1637/// This routine substitutes the given template arguments into the
1638/// type T and produces the instantiated type.
1639///
1640/// \param T the type into which the template arguments will be
1641/// substituted. If this type is not dependent, it will be returned
1642/// immediately.
1643///
James Dennett634962f2012-06-14 21:40:34 +00001644/// \param Args the template arguments that will be
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001645/// substituted for the top-level template parameters within T.
1646///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001647/// \param Loc the location in the source code where this substitution
1648/// is being performed. It will typically be the location of the
1649/// declarator (if we're instantiating the type of some declaration)
1650/// or the location of the type in the source code (if, e.g., we're
1651/// instantiating the type of a cast expression).
1652///
1653/// \param Entity the name of the entity associated with a declaration
1654/// being instantiated (if any). May be empty to indicate that there
1655/// is no such entity (if, e.g., this is a type that occurs as part of
1656/// a cast expression) or that the entity has no name (e.g., an
1657/// unnamed function parameter).
1658///
Richard Smithee579842017-01-30 20:39:26 +00001659/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1660/// acceptable as the top level type of the result.
1661///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001662/// \returns If the instantiation succeeds, the instantiated
1663/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001664TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001665 const MultiLevelTemplateArgumentList &Args,
1666 SourceLocation Loc,
Richard Smithee579842017-01-30 20:39:26 +00001667 DeclarationName Entity,
1668 bool AllowDeducedTST) {
Richard Smith696e3122017-02-23 01:43:54 +00001669 assert(!CodeSynthesisContexts.empty() &&
John McCall609459e2009-10-21 00:58:09 +00001670 "Cannot perform an instantiation without some context on the "
1671 "instantiation stack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001672
1673 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001674 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001675 return T;
1676
1677 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
Richard Smithee579842017-01-30 20:39:26 +00001678 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
1679 : Instantiator.TransformType(T);
John McCall609459e2009-10-21 00:58:09 +00001680}
1681
Douglas Gregor5499af42011-01-05 23:12:31 +00001682TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1683 const MultiLevelTemplateArgumentList &Args,
1684 SourceLocation Loc,
1685 DeclarationName Entity) {
Richard Smith696e3122017-02-23 01:43:54 +00001686 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001687 "Cannot perform an instantiation without some context on the "
1688 "instantiation stack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001689
Douglas Gregor5499af42011-01-05 23:12:31 +00001690 if (TL.getType().isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001691 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001692
Fangrui Song6907ce22018-07-30 19:24:48 +00001693 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001694 !TL.getType()->isVariablyModifiedType()) {
1695 // FIXME: Make a copy of the TypeLoc data here, so that we can
1696 // return a new TypeSourceInfo. Inefficient!
1697 TypeLocBuilder TLB;
1698 TLB.pushFullCopy(TL);
1699 return TLB.getTypeSourceInfo(Context, TL.getType());
1700 }
1701
1702 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1703 TypeLocBuilder TLB;
1704 TLB.reserve(TL.getFullDataSize());
1705 QualType Result = Instantiator.TransformType(TLB, TL);
1706 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001707 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001708
1709 return TLB.getTypeSourceInfo(Context, Result);
1710}
1711
John McCall609459e2009-10-21 00:58:09 +00001712/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001713QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001714 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001715 SourceLocation Loc, DeclarationName Entity) {
Richard Smith696e3122017-02-23 01:43:54 +00001716 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregor79cf6032009-03-10 20:44:00 +00001717 "Cannot perform an instantiation without some context on the "
1718 "instantiation stack");
1719
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001720 // If T is not a dependent type or a variably-modified type, there
1721 // is nothing to do.
Douglas Gregor678d76c2011-07-01 01:22:09 +00001722 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001723 return T;
1724
Douglas Gregord6ff3322009-08-04 16:50:30 +00001725 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1726 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001727}
Douglas Gregor463421d2009-03-03 04:44:36 +00001728
John McCallb29f78f2010-04-09 17:38:44 +00001729static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Nico Weberc0973372016-02-01 22:31:51 +00001730 if (T->getType()->isInstantiationDependentType() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00001731 T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001732 return true;
1733
Abramo Bagnara6d810632010-12-14 22:11:44 +00001734 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00001735 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCallb29f78f2010-04-09 17:38:44 +00001736 return false;
1737
David Blaikie6adc78e2013-02-18 22:06:02 +00001738 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Nico Weberc0973372016-02-01 22:31:51 +00001739 for (ParmVarDecl *P : FP.getParams()) {
Reid Klecknera09e44c2013-07-31 21:00:18 +00001740 // This must be synthesized from a typedef.
1741 if (!P) continue;
1742
Nico Weberc0973372016-02-01 22:31:51 +00001743 // If there are any parameters, a new TypeSourceInfo that refers to the
1744 // instantiated parameters must be built.
1745 return true;
John McCallb29f78f2010-04-09 17:38:44 +00001746 }
1747
1748 return false;
1749}
1750
1751/// A form of SubstType intended specifically for instantiating the
1752/// type of a FunctionDecl. Its purpose is solely to force the
Richard Smith2e321552014-11-12 02:00:47 +00001753/// instantiation of default-argument expressions and to avoid
1754/// instantiating an exception-specification.
John McCallb29f78f2010-04-09 17:38:44 +00001755TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1756 const MultiLevelTemplateArgumentList &Args,
1757 SourceLocation Loc,
Douglas Gregor3024f072012-04-16 07:05:22 +00001758 DeclarationName Entity,
1759 CXXRecordDecl *ThisContext,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001760 Qualifiers ThisTypeQuals) {
Richard Smith696e3122017-02-23 01:43:54 +00001761 assert(!CodeSynthesisContexts.empty() &&
John McCallb29f78f2010-04-09 17:38:44 +00001762 "Cannot perform an instantiation without some context on the "
1763 "instantiation stack");
Nico Weberc0973372016-02-01 22:31:51 +00001764
John McCallb29f78f2010-04-09 17:38:44 +00001765 if (!NeedsInstantiationAsFunctionType(T))
1766 return T;
1767
1768 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1769
1770 TypeLocBuilder TLB;
1771
1772 TypeLoc TL = T->getTypeLoc();
1773 TLB.reserve(TL.getFullDataSize());
1774
Douglas Gregor3024f072012-04-16 07:05:22 +00001775 QualType Result;
David Blaikie6adc78e2013-02-18 22:06:02 +00001776
Richard Smith2e321552014-11-12 02:00:47 +00001777 if (FunctionProtoTypeLoc Proto =
1778 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1779 // Instantiate the type, other than its exception specification. The
1780 // exception specification is instantiated in InitFunctionInstantiation
1781 // once we've built the FunctionDecl.
1782 // FIXME: Set the exception specification to EST_Uninstantiated here,
1783 // instead of rebuilding the function type again later.
1784 Result = Instantiator.TransformFunctionProtoType(
1785 TLB, Proto, ThisContext, ThisTypeQuals,
1786 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1787 bool &Changed) { return false; });
Douglas Gregor3024f072012-04-16 07:05:22 +00001788 } else {
1789 Result = Instantiator.TransformType(TLB, TL);
1790 }
John McCallb29f78f2010-04-09 17:38:44 +00001791 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001792 return nullptr;
John McCallb29f78f2010-04-09 17:38:44 +00001793
1794 return TLB.getTypeSourceInfo(Context, Result);
1795}
1796
Richard Smithcd198152017-06-07 21:46:22 +00001797bool Sema::SubstExceptionSpec(SourceLocation Loc,
1798 FunctionProtoType::ExceptionSpecInfo &ESI,
1799 SmallVectorImpl<QualType> &ExceptionStorage,
1800 const MultiLevelTemplateArgumentList &Args) {
1801 assert(ESI.Type != EST_Uninstantiated);
1802
1803 bool Changed = false;
1804 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
1805 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
1806 Changed);
1807}
1808
Richard Smith2e321552014-11-12 02:00:47 +00001809void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1810 const MultiLevelTemplateArgumentList &Args) {
1811 FunctionProtoType::ExceptionSpecInfo ESI =
1812 Proto->getExtProtoInfo().ExceptionSpec;
Richard Smith2e321552014-11-12 02:00:47 +00001813
1814 SmallVector<QualType, 4> ExceptionStorage;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001815 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
Richard Smithcd198152017-06-07 21:46:22 +00001816 ESI, ExceptionStorage, Args))
Richard Smith2e321552014-11-12 02:00:47 +00001817 // On error, recover by dropping the exception specification.
1818 ESI.Type = EST_None;
1819
1820 UpdateExceptionSpec(New, ESI);
1821}
1822
Fangrui Song6907ce22018-07-30 19:24:48 +00001823ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001824 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall8fb0d9d2011-05-01 22:35:37 +00001825 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001826 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001827 bool ExpectParameterPack) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001828 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Craig Topperc3ec1492014-05-26 06:22:03 +00001829 TypeSourceInfo *NewDI = nullptr;
1830
Douglas Gregor5499af42011-01-05 23:12:31 +00001831 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00001832 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1833
Fangrui Song6907ce22018-07-30 19:24:48 +00001834 // We have a function parameter pack. Substitute into the pattern of the
Douglas Gregor5499af42011-01-05 23:12:31 +00001835 // expansion.
Fangrui Song6907ce22018-07-30 19:24:48 +00001836 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
Douglas Gregor5499af42011-01-05 23:12:31 +00001837 OldParm->getLocation(), OldParm->getDeclName());
1838 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001839 return nullptr;
1840
Douglas Gregor5499af42011-01-05 23:12:31 +00001841 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1842 // We still have unexpanded parameter packs, which means that
1843 // our function parameter is still a function parameter pack.
1844 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001845 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001846 NumExpansions);
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001847 } else if (ExpectParameterPack) {
1848 // We expected to get a parameter pack but didn't (because the type
1849 // itself is not a pack expansion type), so complain. This can occur when
1850 // the substitution goes through an alias template that "loses" the
1851 // pack expansion.
Fangrui Song6907ce22018-07-30 19:24:48 +00001852 Diag(OldParm->getLocation(),
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001853 diag::err_function_parameter_pack_without_parameter_packs)
1854 << NewDI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001855 return nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +00001856 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001857 } else {
Fangrui Song6907ce22018-07-30 19:24:48 +00001858 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
Douglas Gregor5499af42011-01-05 23:12:31 +00001859 OldParm->getDeclName());
1860 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001861
Douglas Gregor940bca72010-04-12 07:48:19 +00001862 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001863 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001864
1865 if (NewDI->getType()->isVoidType()) {
1866 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
Craig Topperc3ec1492014-05-26 06:22:03 +00001867 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001868 }
1869
1870 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001871 OldParm->getInnerLocStart(),
Douglas Gregor940bca72010-04-12 07:48:19 +00001872 OldParm->getLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001873 OldParm->getIdentifier(),
1874 NewDI->getType(), NewDI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001875 OldParm->getStorageClass());
Douglas Gregor940bca72010-04-12 07:48:19 +00001876 if (!NewParm)
Craig Topperc3ec1492014-05-26 06:22:03 +00001877 return nullptr;
1878
Douglas Gregor940bca72010-04-12 07:48:19 +00001879 // Mark the (new) default argument as uninstantiated (if any).
1880 if (OldParm->hasUninstantiatedDefaultArg()) {
1881 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1882 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001883 } else if (OldParm->hasUnparsedDefaultArg()) {
1884 NewParm->setUnparsedDefaultArg();
1885 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001886 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1887 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
Serge Pavlov73c6a242015-08-23 10:22:28 +00001888 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1889 // Instantiate default arguments for methods of local classes (DR1484)
1890 // and non-defining declarations.
1891 Sema::ContextRAII SavedContext(*this, OwningFunc);
Akira Hatanakad644e022016-12-16 03:19:41 +00001892 LocalInstantiationScope Local(*this, true);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001893 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
John McCalldc40b612015-12-11 01:56:36 +00001894 if (NewArg.isUsable()) {
1895 // It would be nice if we still had this.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001896 SourceLocation EqualLoc = NewArg.get()->getBeginLoc();
John McCalldc40b612015-12-11 01:56:36 +00001897 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1898 }
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001899 } else {
1900 // FIXME: if we non-lazily instantiated non-dependent default args for
1901 // non-dependent parameter types we could remove a bunch of duplicate
1902 // conversion warnings for such arguments.
1903 NewParm->setUninstantiatedDefaultArg(Arg);
1904 }
1905 }
Douglas Gregor940bca72010-04-12 07:48:19 +00001906
1907 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Fangrui Song6907ce22018-07-30 19:24:48 +00001908
Douglas Gregorf3010112011-01-07 16:43:16 +00001909 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smith928be492012-01-25 02:14:59 +00001910 // Add the new parameter to the instantiated parameter pack.
Douglas Gregorf3010112011-01-07 16:43:16 +00001911 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1912 } else {
1913 // Introduce an Old -> New mapping
Fangrui Song6907ce22018-07-30 19:24:48 +00001914 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001915 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001916
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001917 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1918 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001919 NewParm->setDeclContext(CurContext);
John McCall8fb0d9d2011-05-01 22:35:37 +00001920
1921 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1922 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rosea0a86be2013-03-08 22:25:36 +00001923
1924 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1925
Fangrui Song6907ce22018-07-30 19:24:48 +00001926 return NewParm;
Douglas Gregor940bca72010-04-12 07:48:19 +00001927}
1928
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001929/// Substitute the given template arguments into the given set of
Douglas Gregordd472162011-01-07 00:20:55 +00001930/// parameters, producing the set of parameter types that would be generated
1931/// from such a substitution.
David Majnemer59f77922016-06-24 04:05:48 +00001932bool Sema::SubstParmTypes(
1933 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1934 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1935 const MultiLevelTemplateArgumentList &TemplateArgs,
1936 SmallVectorImpl<QualType> &ParamTypes,
1937 SmallVectorImpl<ParmVarDecl *> *OutParams,
1938 ExtParameterInfoBuilder &ParamInfos) {
Richard Smith696e3122017-02-23 01:43:54 +00001939 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregordd472162011-01-07 00:20:55 +00001940 "Cannot perform an instantiation without some context on the "
1941 "instantiation stack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001942
1943 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
Douglas Gregordd472162011-01-07 00:20:55 +00001944 DeclarationName());
David Majnemer59f77922016-06-24 04:05:48 +00001945 return Instantiator.TransformFunctionTypeParams(
1946 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
Douglas Gregordd472162011-01-07 00:20:55 +00001947}
1948
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001949/// Perform substitution on the base class specifiers of the
John McCall76d824f2009-08-25 22:02:44 +00001950/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001951///
1952/// Produces a diagnostic and returns true on error, returns false and
1953/// attaches the instantiated base classes to the class template
1954/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001955bool
John McCall76d824f2009-08-25 22:02:44 +00001956Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1957 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001958 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001959 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001960 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Richard Trieub5841332015-04-15 01:21:42 +00001961 for (const auto &Base : Pattern->bases()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001962 if (!Base.getType()->isDependentType()) {
1963 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay76d0b462013-06-21 18:58:32 +00001964 if (RD->isInvalidDecl())
1965 Instantiation->setInvalidDecl();
1966 }
Aaron Ballman574705e2014-03-13 15:41:46 +00001967 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001968 continue;
1969 }
1970
Douglas Gregor752a5952011-01-03 22:36:02 +00001971 SourceLocation EllipsisLoc;
Douglas Gregorc52264e2011-03-02 02:04:06 +00001972 TypeSourceInfo *BaseTypeLoc;
Aaron Ballman574705e2014-03-13 15:41:46 +00001973 if (Base.isPackExpansion()) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001974 // This is a pack expansion. See whether we should expand it now, or
1975 // wait until later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001976 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Aaron Ballman574705e2014-03-13 15:41:46 +00001977 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001978 Unexpanded);
1979 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001980 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001981 Optional<unsigned> NumExpansions;
Fangrui Song6907ce22018-07-30 19:24:48 +00001982 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
Aaron Ballman574705e2014-03-13 15:41:46 +00001983 Base.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001984 Unexpanded,
Fangrui Song6907ce22018-07-30 19:24:48 +00001985 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001986 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001987 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001988 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001989 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001990 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001991
Douglas Gregor752a5952011-01-03 22:36:02 +00001992 // If we should expand this pack expansion now, do so.
1993 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001994 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001995 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
Fangrui Song6907ce22018-07-30 19:24:48 +00001996
Aaron Ballman574705e2014-03-13 15:41:46 +00001997 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001998 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001999 Base.getSourceRange().getBegin(),
Douglas Gregor752a5952011-01-03 22:36:02 +00002000 DeclarationName());
2001 if (!BaseTypeLoc) {
2002 Invalid = true;
2003 continue;
2004 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002005
Douglas Gregor752a5952011-01-03 22:36:02 +00002006 if (CXXBaseSpecifier *InstantiatedBase
2007 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00002008 Base.getSourceRange(),
2009 Base.isVirtual(),
2010 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00002011 BaseTypeLoc,
2012 SourceLocation()))
2013 InstantiatedBases.push_back(InstantiatedBase);
2014 else
2015 Invalid = true;
2016 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002017
Douglas Gregor752a5952011-01-03 22:36:02 +00002018 continue;
2019 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002020
Douglas Gregor752a5952011-01-03 22:36:02 +00002021 // The resulting base specifier will (still) be a pack expansion.
Aaron Ballman574705e2014-03-13 15:41:46 +00002022 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregorc52264e2011-03-02 02:04:06 +00002023 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Aaron Ballman574705e2014-03-13 15:41:46 +00002024 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00002025 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00002026 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00002027 DeclarationName());
2028 } else {
Aaron Ballman574705e2014-03-13 15:41:46 +00002029 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00002030 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00002031 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00002032 DeclarationName());
Douglas Gregor752a5952011-01-03 22:36:02 +00002033 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002034
Nick Lewycky19b9f952010-07-26 16:56:01 +00002035 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00002036 Invalid = true;
2037 continue;
2038 }
2039
2040 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002041 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00002042 Base.getSourceRange(),
2043 Base.isVirtual(),
2044 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00002045 BaseTypeLoc,
2046 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00002047 InstantiatedBases.push_back(InstantiatedBase);
2048 else
2049 Invalid = true;
2050 }
2051
Craig Topperaa700cb2015-12-27 21:55:19 +00002052 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
Douglas Gregor463421d2009-03-03 04:44:36 +00002053 Invalid = true;
2054
2055 return Invalid;
2056}
2057
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002058// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00002059namespace clang {
2060 namespace sema {
2061 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
2062 const MultiLevelTemplateArgumentList &TemplateArgs);
Erich Keanea32910d2017-03-23 18:51:54 +00002063 Attr *instantiateTemplateAttributeForDecl(
2064 const Attr *At, ASTContext &C, Sema &S,
2065 const MultiLevelTemplateArgumentList &TemplateArgs);
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00002066 }
2067}
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002068
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002069/// Instantiate the definition of a class from a given pattern.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002070///
2071/// \param PointOfInstantiation The point of instantiation within the
2072/// source code.
2073///
2074/// \param Instantiation is the declaration whose definition is being
2075/// instantiated. This will be either a class template specialization
2076/// or a member class of a class template specialization.
2077///
2078/// \param Pattern is the pattern from which the instantiation
2079/// occurs. This will be either the declaration of a class template or
2080/// the declaration of a member class of a class template.
2081///
2082/// \param TemplateArgs The template arguments to be substituted into
2083/// the pattern.
2084///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002085/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002086///
2087/// \param Complain whether to complain if the class cannot be instantiated due
2088/// to the lack of a definition.
2089///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002090/// \returns true if an error occurred, false otherwise.
2091bool
2092Sema::InstantiateClass(SourceLocation PointOfInstantiation,
2093 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002094 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002095 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002096 bool Complain) {
Mike Stump11289f42009-09-09 15:08:12 +00002097 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002098 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Vassil Vassilevb21ee082016-08-18 22:01:25 +00002099 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00002100 Instantiation->getInstantiatedFromMemberClass(),
2101 Pattern, PatternDef, TSK, Complain))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002102 return true;
Anton Afanasyevd880de22019-03-30 08:42:48 +00002103
2104 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
Lubos Lunakab8cde42019-05-12 10:39:21 +00002105 std::string Name;
2106 llvm::raw_string_ostream OS(Name);
2107 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
2108 /*Qualified=*/true);
2109 return Name;
Anton Afanasyevd880de22019-03-30 08:42:48 +00002110 });
2111
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002112 Pattern = PatternDef;
2113
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002114 // Record the point of instantiation.
Fangrui Song6907ce22018-07-30 19:24:48 +00002115 if (MemberSpecializationInfo *MSInfo
Douglas Gregord6ba93d2009-10-15 15:54:05 +00002116 = Instantiation->getMemberSpecializationInfo()) {
2117 MSInfo->setTemplateSpecializationKind(TSK);
2118 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Fangrui Song6907ce22018-07-30 19:24:48 +00002119 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weber3ffc4c92011-12-20 20:32:49 +00002120 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregoref6ab412009-10-27 06:26:26 +00002121 Spec->setTemplateSpecializationKind(TSK);
2122 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00002123 }
Richard Smitha1087602014-03-10 00:04:29 +00002124
Douglas Gregorf3430ae2009-03-25 21:23:52 +00002125 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002126 if (Inst.isInvalid())
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002127 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002128 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
Jordan Rose1e879d82018-03-23 00:07:18 +00002129 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00002130 "instantiating class definition");
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002131
2132 // Enter the scope of this instantiation. We don't use
2133 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00002134 ContextRAII SavedContext(*this, Instantiation);
Faisal Valid143a0c2017-04-01 21:30:49 +00002135 EnterExpressionEvaluationContext EvalContext(
2136 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002137
Douglas Gregor51121572010-03-24 01:33:17 +00002138 // If this is an instantiation of a local class, merge this local
2139 // instantiation scope with the enclosing scope. Otherwise, every
2140 // instantiation of a class has its own local instantiation scope.
2141 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00002142 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00002143
Volodymyr Sapsai4fbaa622017-09-21 19:54:12 +00002144 // Some class state isn't processed immediately but delayed till class
2145 // instantiation completes. We may not be ready to handle any delayed state
2146 // already on the stack as it might correspond to a different class, so save
2147 // it now and put it back later.
2148 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
Reid Kleckner5b640342016-02-26 19:51:02 +00002149
John McCall6602bb12010-08-01 02:01:53 +00002150 // Pull attributes from the pattern onto the instantiation.
2151 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2152
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002153 // Start the definition of this instantiation.
2154 Instantiation->startDefinition();
Richard Smitha1087602014-03-10 00:04:29 +00002155
2156 // The instantiation is visible here, even if it was first declared in an
2157 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00002158 Instantiation->setVisibleDespiteOwningModule();
Richard Smitha1087602014-03-10 00:04:29 +00002159
2160 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregore9029562010-05-06 00:28:52 +00002161 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002162
John McCall76d824f2009-08-25 22:02:44 +00002163 // Do substitution on the base class specifiers.
2164 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002165 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002166
Douglas Gregor869853e2010-11-10 19:44:59 +00002167 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002168 SmallVector<Decl*, 4> Fields;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002169 // Delay instantiation of late parsed attributes.
2170 LateInstantiatedAttrVec LateAttrs;
2171 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2172
Richard Smith921f1322019-05-13 23:35:21 +00002173 bool MightHaveConstexprVirtualFunctions = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002174 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002175 // Don't instantiate members not belonging in this semantic context.
2176 // e.g. for:
2177 // @code
2178 // template <int i> class A {
2179 // class B *g;
2180 // };
2181 // @endcode
2182 // 'class B' has the template as lexical context but semantically it is
2183 // introduced in namespace scope.
Aaron Ballman629afae2014-03-07 19:56:05 +00002184 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002185 continue;
2186
Erik Pilkingtona3a462e2018-07-23 22:47:37 +00002187 // BlockDecls can appear in a default-member-initializer. They must be the
2188 // child of a BlockExpr, so we only know how to instantiate them from there.
2189 if (isa<BlockDecl>(Member))
2190 continue;
2191
Aaron Ballman629afae2014-03-07 19:56:05 +00002192 if (Member->isInvalidDecl()) {
Richard Smithded9c2e2012-07-11 22:37:56 +00002193 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002194 continue;
2195 }
2196
Aaron Ballman629afae2014-03-07 19:56:05 +00002197 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002198 if (NewMember) {
Richard Smith938f40b2011-06-11 17:19:42 +00002199 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCall48871652010-08-21 09:40:31 +00002200 Fields.push_back(Field);
Richard Smith7d137e32012-03-23 03:33:32 +00002201 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2202 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2203 // specialization causes the implicit instantiation of the definitions
2204 // of unscoped member enumerations.
2205 // Record a point of instantiation for this implicit instantiation.
Richard Smithb66d7772012-03-23 23:09:08 +00002206 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2207 Enum->isCompleteDefinition()) {
Richard Smith7d137e32012-03-23 03:33:32 +00002208 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2209 assert(MSInfo && "no spec info for member enum specialization");
2210 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2211 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2212 }
Richard Smithded9c2e2012-07-11 22:37:56 +00002213 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2214 if (SA->isFailed()) {
2215 // A static_assert failed. Bail out; instantiating this
2216 // class is probably not meaningful.
2217 Instantiation->setInvalidDecl();
2218 break;
2219 }
Richard Smith921f1322019-05-13 23:35:21 +00002220 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
2221 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
2222 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
2223 MightHaveConstexprVirtualFunctions = true;
Richard Smith7d137e32012-03-23 03:33:32 +00002224 }
2225
2226 if (NewMember->isInvalidDecl())
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002227 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002228 } else {
2229 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002230 // instantiations was a semantic disaster, and we'll want to mark the
2231 // declaration invalid.
2232 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002233 }
2234 }
2235
2236 // Finish checking fields.
Craig Topperc3ec1492014-05-26 06:22:03 +00002237 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
Erich Keanec480f302018-07-12 21:09:05 +00002238 SourceLocation(), SourceLocation(), ParsedAttributesView());
Richard Smith848934c2019-12-05 13:37:35 -08002239 CheckCompletedCXXClass(nullptr, Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002240
Reid Kleckner93f661a2015-03-17 21:51:43 +00002241 // Default arguments are parsed, if not instantiated. We can go instantiate
Hans Wennborg92ce2af2019-12-02 16:25:23 +01002242 // default arg exprs for default constructors if necessary now. Unless we're
2243 // parsing a class, in which case wait until that's finished.
2244 if (ParsingClassDepth == 0)
2245 ActOnFinishCXXNonNestedClass();
Reid Kleckner93f661a2015-03-17 21:51:43 +00002246
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002247 // Instantiate late parsed attributes, and attach them to their decls.
2248 // See Sema::InstantiateAttrs
2249 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2250 E = LateAttrs.end(); I != E; ++I) {
2251 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2252 CurrentInstantiationScope = I->Scope;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002253
2254 // Allow 'this' within late-parsed attributes.
2255 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2256 CXXRecordDecl *ThisContext =
2257 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002258 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002259 ND && ND->isCXXInstanceMember());
2260
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002261 Attr *NewAttr =
2262 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2263 I->NewDecl->addAttr(NewAttr);
2264 LocalInstantiationScope::deleteScopes(I->Scope,
2265 Instantiator.getStartingScope());
2266 }
2267 Instantiator.disableLateAttributeInstantiation();
2268 LateAttrs.clear();
2269
Richard Smithd3b5c9082012-07-27 04:22:15 +00002270 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002271
Richard Smitha1087602014-03-10 00:04:29 +00002272 // FIXME: We should do something similar for explicit instantiations so they
2273 // end up in the right module.
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002274 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidise3789482012-02-11 01:59:57 +00002275 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002276 Instantiation->setLocStart(Pattern->getInnerLocStart());
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00002277 Instantiation->setBraceRange(Pattern->getBraceRange());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002278 }
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002279
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002280 if (!Instantiation->isInvalidDecl()) {
John McCalla0a96892012-08-10 03:15:35 +00002281 // Perform any dependent diagnostics from the pattern.
2282 PerformDependentDiagnostics(Pattern, TemplateArgs);
2283
Douglas Gregor869853e2010-11-10 19:44:59 +00002284 // Instantiate any out-of-line class template partial
2285 // specializations now.
Richard Smith10b55fc2013-09-26 03:49:48 +00002286 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregor869853e2010-11-10 19:44:59 +00002287 P = Instantiator.delayed_partial_spec_begin(),
2288 PEnd = Instantiator.delayed_partial_spec_end();
2289 P != PEnd; ++P) {
2290 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smith10b55fc2013-09-26 03:49:48 +00002291 P->first, P->second)) {
2292 Instantiation->setInvalidDecl();
2293 break;
2294 }
2295 }
2296
2297 // Instantiate any out-of-line variable template partial
2298 // specializations now.
2299 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2300 P = Instantiator.delayed_var_partial_spec_begin(),
2301 PEnd = Instantiator.delayed_var_partial_spec_end();
2302 P != PEnd; ++P) {
2303 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2304 P->first, P->second)) {
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002305 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002306 break;
2307 }
2308 }
2309 }
2310
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002311 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00002312 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002313
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002314 if (!Instantiation->isInvalidDecl()) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00002315 Consumer.HandleTagDeclDefinition(Instantiation);
2316
Douglas Gregor88d292c2010-05-13 16:44:06 +00002317 // Always emit the vtable for an explicit instantiation definition
Richard Smith921f1322019-05-13 23:35:21 +00002318 // of a polymorphic class template specialization. Otherwise, eagerly
2319 // instantiate only constexpr virtual functions in preparation for their use
2320 // in constant evaluation.
Douglas Gregor88d292c2010-05-13 16:44:06 +00002321 if (TSK == TSK_ExplicitInstantiationDefinition)
2322 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
Richard Smith921f1322019-05-13 23:35:21 +00002323 else if (MightHaveConstexprVirtualFunctions)
2324 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
2325 /*ConstexprOnly*/ true);
Douglas Gregor88d292c2010-05-13 16:44:06 +00002326 }
2327
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002328 return Instantiation->isInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002329}
2330
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002331/// Instantiate the definition of an enum from a given pattern.
Richard Smith4b38ded2012-03-14 23:13:10 +00002332///
2333/// \param PointOfInstantiation The point of instantiation within the
2334/// source code.
2335/// \param Instantiation is the declaration whose definition is being
2336/// instantiated. This will be a member enumeration of a class
2337/// temploid specialization, or a local enumeration within a
2338/// function temploid specialization.
2339/// \param Pattern The templated declaration from which the instantiation
2340/// occurs.
2341/// \param TemplateArgs The template arguments to be substituted into
2342/// the pattern.
2343/// \param TSK The kind of implicit or explicit instantiation to perform.
2344///
2345/// \return \c true if an error occurred, \c false otherwise.
2346bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2347 EnumDecl *Instantiation, EnumDecl *Pattern,
2348 const MultiLevelTemplateArgumentList &TemplateArgs,
2349 TemplateSpecializationKind TSK) {
2350 EnumDecl *PatternDef = Pattern->getDefinition();
Vassil Vassilevb21ee082016-08-18 22:01:25 +00002351 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00002352 Instantiation->getInstantiatedFromMemberEnum(),
2353 Pattern, PatternDef, TSK,/*Complain*/true))
2354 return true;
2355 Pattern = PatternDef;
2356
2357 // Record the point of instantiation.
2358 if (MemberSpecializationInfo *MSInfo
2359 = Instantiation->getMemberSpecializationInfo()) {
2360 MSInfo->setTemplateSpecializationKind(TSK);
2361 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2362 }
2363
2364 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002365 if (Inst.isInvalid())
Richard Smith4b38ded2012-03-14 23:13:10 +00002366 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002367 if (Inst.isAlreadyInstantiating())
2368 return false;
Jordan Rose1e879d82018-03-23 00:07:18 +00002369 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00002370 "instantiating enum definition");
Richard Smith4b38ded2012-03-14 23:13:10 +00002371
Richard Smitha1087602014-03-10 00:04:29 +00002372 // The instantiation is visible here, even if it was first declared in an
2373 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00002374 Instantiation->setVisibleDespiteOwningModule();
Richard Smitha1087602014-03-10 00:04:29 +00002375
Richard Smith4b38ded2012-03-14 23:13:10 +00002376 // Enter the scope of this instantiation. We don't use
2377 // PushDeclContext because we don't have a scope.
2378 ContextRAII SavedContext(*this, Instantiation);
Faisal Valid143a0c2017-04-01 21:30:49 +00002379 EnterExpressionEvaluationContext EvalContext(
2380 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith4b38ded2012-03-14 23:13:10 +00002381
2382 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2383
2384 // Pull attributes from the pattern onto the instantiation.
2385 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2386
2387 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2388 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2389
2390 // Exit the scope of this instantiation.
2391 SavedContext.pop();
2392
2393 return Instantiation->isInvalidDecl();
2394}
2395
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002396
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002397/// Instantiate the definition of a field from the given pattern.
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002398///
2399/// \param PointOfInstantiation The point of instantiation within the
2400/// source code.
2401/// \param Instantiation is the declaration whose definition is being
2402/// instantiated. This will be a class of a class temploid
2403/// specialization, or a local enumeration within a function temploid
2404/// specialization.
2405/// \param Pattern The templated declaration from which the instantiation
2406/// occurs.
2407/// \param TemplateArgs The template arguments to be substituted into
2408/// the pattern.
2409///
2410/// \return \c true if an error occurred, \c false otherwise.
2411bool Sema::InstantiateInClassInitializer(
2412 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2413 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2414 // If there is no initializer, we don't need to do anything.
2415 if (!Pattern->hasInClassInitializer())
2416 return false;
2417
2418 assert(Instantiation->getInClassInitStyle() ==
2419 Pattern->getInClassInitStyle() &&
2420 "pattern and instantiation disagree about init style");
2421
2422 // Error out if we haven't parsed the initializer of the pattern yet because
2423 // we are waiting for the closing brace of the outer class.
2424 Expr *OldInit = Pattern->getInClassInitializer();
2425 if (!OldInit) {
2426 RecordDecl *PatternRD = Pattern->getParent();
2427 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
Richard Smith8dbc6b22016-11-22 22:55:12 +00002428 Diag(PointOfInstantiation,
2429 diag::err_in_class_initializer_not_yet_parsed)
2430 << OutermostClass << Pattern;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002431 Diag(Pattern->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002432 Instantiation->setInvalidDecl();
2433 return true;
2434 }
2435
2436 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2437 if (Inst.isInvalid())
2438 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002439 if (Inst.isAlreadyInstantiating()) {
2440 // Error out if we hit an instantiation cycle for this initializer.
2441 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2442 << Instantiation;
2443 return true;
2444 }
Jordan Rose1e879d82018-03-23 00:07:18 +00002445 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00002446 "instantiating default member init");
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002447
2448 // Enter the scope of this instantiation. We don't use PushDeclContext because
2449 // we don't have a scope.
2450 ContextRAII SavedContext(*this, Instantiation->getParent());
Faisal Valid143a0c2017-04-01 21:30:49 +00002451 EnterExpressionEvaluationContext EvalContext(
2452 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002453
Serge Pavlov907233f2015-04-28 17:58:47 +00002454 LocalInstantiationScope Scope(*this, true);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002455
2456 // Instantiate the initializer.
2457 ActOnStartCXXInClassMemberInitializer();
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002458 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002459
2460 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2461 /*CXXDirectInit=*/false);
2462 Expr *Init = NewInit.get();
2463 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2464 ActOnFinishCXXInClassMemberInitializer(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002465 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002466
Richard Smith4b054b22016-08-24 21:25:37 +00002467 if (auto *L = getASTMutationListener())
2468 L->DefaultMemberInitializerInstantiated(Instantiation);
2469
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002470 // Return true if the in-class initializer is still missing.
2471 return !Instantiation->getInClassInitializer();
2472}
2473
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002474namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002475 /// A partial specialization whose template arguments have matched
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002476 /// a given template-id.
2477 struct PartialSpecMatchResult {
2478 ClassTemplatePartialSpecializationDecl *Partial;
2479 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002480 };
2481}
2482
Richard Smithe6d4b772017-06-07 02:42:27 +00002483bool Sema::usesPartialOrExplicitSpecialization(
2484 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
2485 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
2486 TSK_ExplicitSpecialization)
2487 return true;
2488
2489 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2490 ClassTemplateSpec->getSpecializedTemplate()
2491 ->getPartialSpecializations(PartialSpecs);
2492 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2493 TemplateDeductionInfo Info(Loc);
2494 if (!DeduceTemplateArguments(PartialSpecs[I],
2495 ClassTemplateSpec->getTemplateArgs(), Info))
2496 return true;
2497 }
2498
2499 return false;
2500}
2501
Richard Smith32b43762017-01-08 22:45:21 +00002502/// Get the instantiation pattern to use to instantiate the definition of a
2503/// given ClassTemplateSpecializationDecl (either the pattern of the primary
2504/// template or of a partial specialization).
2505static CXXRecordDecl *
2506getPatternForClassTemplateSpecialization(
2507 Sema &S, SourceLocation PointOfInstantiation,
Larisse Voufo72caf2b2013-08-22 00:59:14 +00002508 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2509 TemplateSpecializationKind TSK, bool Complain) {
Richard Smith32b43762017-01-08 22:45:21 +00002510 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2511 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
2512 return nullptr;
2513
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002514 llvm::PointerUnion<ClassTemplateDecl *,
2515 ClassTemplatePartialSpecializationDecl *>
2516 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2517 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
2518 // Find best matching specialization.
2519 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregor2373c592009-05-31 09:31:02 +00002520
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002521 // C++ [temp.class.spec.match]p1:
2522 // When a class template is used in a context that requires an
2523 // instantiation of the class, it is necessary to determine
2524 // whether the instantiation is to be generated using the primary
2525 // template or one of the partial specializations. This is done by
2526 // matching the template arguments of the class template
2527 // specialization with the template argument lists of the partial
2528 // specializations.
2529 typedef PartialSpecMatchResult MatchResult;
2530 SmallVector<MatchResult, 4> Matched;
2531 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2532 Template->getPartialSpecializations(PartialSpecs);
2533 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2534 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2535 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2536 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2537 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
2538 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
2539 // Store the failed-deduction information for use in diagnostics, later.
2540 // TODO: Actually use the failed-deduction info?
2541 FailedCandidates.addCandidate().set(
2542 DeclAccessPair::make(Template, AS_public), Partial,
2543 MakeDeductionFailureInfo(S.Context, Result, Info));
2544 (void)Result;
2545 } else {
2546 Matched.push_back(PartialSpecMatchResult());
2547 Matched.back().Partial = Partial;
2548 Matched.back().Args = Info.take();
2549 }
2550 }
2551
2552 // If we're dealing with a member template where the template parameters
2553 // have been instantiated, this provides the original template parameters
2554 // from which the member template's parameters were instantiated.
2555
2556 if (Matched.size() >= 1) {
2557 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
2558 if (Matched.size() == 1) {
2559 // -- If exactly one matching specialization is found, the
2560 // instantiation is generated from that specialization.
2561 // We don't need to do anything for this.
2562 } else {
2563 // -- If more than one matching specialization is found, the
2564 // partial order rules (14.5.4.2) are used to determine
2565 // whether one of the specializations is more specialized
2566 // than the others. If none of the specializations is more
2567 // specialized than all of the other matching
2568 // specializations, then the use of the class template is
2569 // ambiguous and the program is ill-formed.
2570 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2571 PEnd = Matched.end();
2572 P != PEnd; ++P) {
2573 if (S.getMoreSpecializedPartialSpecialization(
2574 P->Partial, Best->Partial, PointOfInstantiation) ==
2575 P->Partial)
2576 Best = P;
2577 }
2578
2579 // Determine if the best partial specialization is more specialized than
2580 // the others.
2581 bool Ambiguous = false;
2582 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2583 PEnd = Matched.end();
2584 P != PEnd; ++P) {
2585 if (P != Best && S.getMoreSpecializedPartialSpecialization(
2586 P->Partial, Best->Partial,
2587 PointOfInstantiation) != Best->Partial) {
2588 Ambiguous = true;
2589 break;
2590 }
2591 }
2592
2593 if (Ambiguous) {
2594 // Partial ordering did not produce a clear winner. Complain.
2595 Inst.Clear();
2596 ClassTemplateSpec->setInvalidDecl();
2597 S.Diag(PointOfInstantiation,
2598 diag::err_partial_spec_ordering_ambiguous)
2599 << ClassTemplateSpec;
2600
2601 // Print the matching partial specializations.
2602 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2603 PEnd = Matched.end();
2604 P != PEnd; ++P)
2605 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2606 << S.getTemplateArgumentBindingsText(
2607 P->Partial->getTemplateParameters(), *P->Args);
2608
2609 return nullptr;
2610 }
2611 }
2612
2613 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002614 } else {
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002615 // -- If no matches are found, the instantiation is generated
2616 // from the primary template.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002617 }
Douglas Gregor2373c592009-05-31 09:31:02 +00002618 }
2619
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002620 CXXRecordDecl *Pattern = nullptr;
2621 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2622 if (auto *PartialSpec =
2623 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
Douglas Gregorbe999392009-09-15 16:23:51 +00002624 // Instantiate using the best class template partial specialization.
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002625 while (PartialSpec->getInstantiatedFromMember()) {
Douglas Gregor21610382009-10-29 00:04:11 +00002626 // If we've found an explicit specialization of this class template,
2627 // stop here and use that as the pattern.
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002628 if (PartialSpec->isMemberSpecialization())
Douglas Gregor21610382009-10-29 00:04:11 +00002629 break;
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002630
2631 PartialSpec = PartialSpec->getInstantiatedFromMember();
Douglas Gregor21610382009-10-29 00:04:11 +00002632 }
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002633 Pattern = PartialSpec;
Douglas Gregor170bc422009-06-12 22:31:52 +00002634 } else {
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002635 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2636 while (Template->getInstantiatedFromMemberTemplate()) {
Douglas Gregorcf915552009-10-13 16:30:37 +00002637 // If we've found an explicit specialization of this class template,
2638 // stop here and use that as the pattern.
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002639 if (Template->isMemberSpecialization())
Douglas Gregorcf915552009-10-13 16:30:37 +00002640 break;
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002641
2642 Template = Template->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00002643 }
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002644 Pattern = Template->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00002645 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002646
Richard Smith32b43762017-01-08 22:45:21 +00002647 return Pattern;
2648}
Mike Stump11289f42009-09-09 15:08:12 +00002649
Richard Smith32b43762017-01-08 22:45:21 +00002650bool Sema::InstantiateClassTemplateSpecialization(
2651 SourceLocation PointOfInstantiation,
2652 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2653 TemplateSpecializationKind TSK, bool Complain) {
2654 // Perform the actual instantiation on the canonical declaration.
2655 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2656 ClassTemplateSpec->getCanonicalDecl());
2657 if (ClassTemplateSpec->isInvalidDecl())
2658 return true;
2659
2660 CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization(
2661 *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
2662 if (!Pattern)
2663 return true;
2664
2665 return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
2666 getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
2667 Complain);
Douglas Gregor463421d2009-03-03 04:44:36 +00002668}
Douglas Gregor90a1a652009-03-19 17:26:29 +00002669
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002670/// Instantiates the definitions of all of the member
John McCall76d824f2009-08-25 22:02:44 +00002671/// of the given class, which is an instantiation of a class template
2672/// or a member class of a template.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002673void
2674Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002675 CXXRecordDecl *Instantiation,
2676 const MultiLevelTemplateArgumentList &TemplateArgs,
2677 TemplateSpecializationKind TSK) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00002678 // FIXME: We need to notify the ASTMutationListener that we did all of these
2679 // things, in case we have an explicit instantiation definition in a PCM, a
2680 // module, or preamble, and the declaration is in an imported AST.
David Majnemer192d1792013-11-27 08:20:38 +00002681 assert(
2682 (TSK == TSK_ExplicitInstantiationDefinition ||
2683 TSK == TSK_ExplicitInstantiationDeclaration ||
2684 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2685 "Unexpected template specialization kind!");
Aaron Ballman629afae2014-03-07 19:56:05 +00002686 for (auto *D : Instantiation->decls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002687 bool SuppressNew = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002688 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Louis Dionned2695792018-10-04 15:49:42 +00002689 if (FunctionDecl *Pattern =
2690 Function->getInstantiatedFromMemberFunction()) {
2691
2692 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2693 continue;
2694
2695 MemberSpecializationInfo *MSInfo =
2696 Function->getMemberSpecializationInfo();
Douglas Gregor1d957a32009-10-27 18:42:08 +00002697 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002698 if (MSInfo->getTemplateSpecializationKind()
2699 == TSK_ExplicitSpecialization)
2700 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002701
2702 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2703 Function,
Douglas Gregor1d957a32009-10-27 18:42:08 +00002704 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002705 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002706 SuppressNew) ||
2707 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002708 continue;
Richard Smitheb36ddf2014-04-24 22:45:46 +00002709
2710 // C++11 [temp.explicit]p8:
2711 // An explicit instantiation definition that names a class template
2712 // specialization explicitly instantiates the class template
2713 // specialization and is only an explicit instantiation definition
2714 // of members whose definition is visible at the point of
2715 // instantiation.
2716 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002717 continue;
2718
Richard Smitheb36ddf2014-04-24 22:45:46 +00002719 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2720
2721 if (Function->isDefined()) {
2722 // Let the ASTConsumer know that this function has been explicitly
2723 // instantiated now, and its linkage might have changed.
2724 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2725 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002726 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Richard Smitheb36ddf2014-04-24 22:45:46 +00002727 } else if (TSK == TSK_ImplicitInstantiation) {
2728 PendingLocalImplicitInstantiations.push_back(
2729 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor1d957a32009-10-27 18:42:08 +00002730 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002731 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002732 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002733 if (isa<VarTemplateSpecializationDecl>(Var))
2734 continue;
2735
Douglas Gregor86d142a2009-10-08 07:24:58 +00002736 if (Var->isStaticDataMember()) {
Louis Dionned2695792018-10-04 15:49:42 +00002737 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2738 continue;
2739
Douglas Gregor1d957a32009-10-27 18:42:08 +00002740 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2741 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002742 if (MSInfo->getTemplateSpecializationKind()
2743 == TSK_ExplicitSpecialization)
2744 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002745
2746 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2747 Var,
Douglas Gregor1d957a32009-10-27 18:42:08 +00002748 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002749 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002750 SuppressNew) ||
2751 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002752 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002753
Douglas Gregor1d957a32009-10-27 18:42:08 +00002754 if (TSK == TSK_ExplicitInstantiationDefinition) {
2755 // C++0x [temp.explicit]p8:
2756 // An explicit instantiation definition that names a class template
Fangrui Song6907ce22018-07-30 19:24:48 +00002757 // specialization explicitly instantiates the class template
2758 // specialization and is only an explicit instantiation definition
2759 // of members whose definition is visible at the point of
Douglas Gregor1d957a32009-10-27 18:42:08 +00002760 // instantiation.
Richard Smith62f19e72016-06-25 00:15:56 +00002761 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002762 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002763
Douglas Gregor1d957a32009-10-27 18:42:08 +00002764 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00002765 InstantiateVariableDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00002766 } else {
2767 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2768 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002769 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002770 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Louis Dionned2695792018-10-04 15:49:42 +00002771 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2772 continue;
2773
Douglas Gregor1da22252010-04-18 18:11:38 +00002774 // Always skip the injected-class-name, along with any
2775 // redeclarations of nested classes, since both would cause us
2776 // to try to instantiate the members of a class twice.
Richard Smith069ecf62014-11-20 22:56:34 +00002777 // Skip closure types; they'll get instantiated when we instantiate
2778 // the corresponding lambda-expression.
2779 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2780 Record->isLambda())
Douglas Gregord801b062009-10-07 23:56:10 +00002781 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002782
Douglas Gregor1d957a32009-10-27 18:42:08 +00002783 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2784 assert(MSInfo && "No member specialization information?");
Fangrui Song6907ce22018-07-30 19:24:48 +00002785
Douglas Gregor06aa50412010-04-09 21:02:29 +00002786 if (MSInfo->getTemplateSpecializationKind()
2787 == TSK_ExplicitSpecialization)
2788 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00002789
Reid Kleckner5f789ba2019-04-29 21:32:05 +00002790 if (Context.getTargetInfo().getTriple().isOSWindows() &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00002791 TSK == TSK_ExplicitInstantiationDeclaration) {
Reid Kleckner5f789ba2019-04-29 21:32:05 +00002792 // On Windows, explicit instantiation decl of the outer class doesn't
2793 // affect the inner class. Typically extern template declarations are
2794 // used in combination with dll import/export annotations, but those
2795 // are not propagated from the outer class templates to inner classes.
2796 // Therefore, do not instantiate inner classes on this platform, so
2797 // that users don't end up with undefined symbols during linking.
Hans Wennborga86a83b2016-05-26 19:42:56 +00002798 continue;
2799 }
2800
Fangrui Song6907ce22018-07-30 19:24:48 +00002801 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2802 Record,
Douglas Gregor1d957a32009-10-27 18:42:08 +00002803 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002804 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002805 SuppressNew) ||
2806 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002807 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002808
Douglas Gregor1d957a32009-10-27 18:42:08 +00002809 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2810 assert(Pattern && "Missing instantiated-from-template information");
Fangrui Song6907ce22018-07-30 19:24:48 +00002811
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002812 if (!Record->getDefinition()) {
2813 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002814 // C++0x [temp.explicit]p8:
2815 // An explicit instantiation definition that names a class template
Fangrui Song6907ce22018-07-30 19:24:48 +00002816 // specialization explicitly instantiates the class template
2817 // specialization and is only an explicit instantiation definition
2818 // of members whose definition is visible at the point of
Douglas Gregor1d957a32009-10-27 18:42:08 +00002819 // instantiation.
2820 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2821 MSInfo->setTemplateSpecializationKind(TSK);
2822 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2823 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002824
Douglas Gregor1d957a32009-10-27 18:42:08 +00002825 continue;
2826 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002827
Douglas Gregor1d957a32009-10-27 18:42:08 +00002828 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002829 TemplateArgs,
2830 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002831 } else {
2832 if (TSK == TSK_ExplicitInstantiationDefinition &&
2833 Record->getTemplateSpecializationKind() ==
2834 TSK_ExplicitInstantiationDeclaration) {
2835 Record->setTemplateSpecializationKind(TSK);
2836 MarkVTableUsed(PointOfInstantiation, Record, true);
2837 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002838 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002839
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002840 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002841 if (Pattern)
Fangrui Song6907ce22018-07-30 19:24:48 +00002842 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
Douglas Gregor1d957a32009-10-27 18:42:08 +00002843 TSK);
Aaron Ballman629afae2014-03-07 19:56:05 +00002844 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smith4b38ded2012-03-14 23:13:10 +00002845 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2846 assert(MSInfo && "No member specialization information?");
2847
2848 if (MSInfo->getTemplateSpecializationKind()
2849 == TSK_ExplicitSpecialization)
2850 continue;
2851
2852 if (CheckSpecializationInstantiationRedecl(
2853 PointOfInstantiation, TSK, Enum,
2854 MSInfo->getTemplateSpecializationKind(),
2855 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2856 SuppressNew)
2857 continue;
2858
2859 if (Enum->getDefinition())
2860 continue;
2861
Richard Smith6739a102016-05-05 00:56:12 +00002862 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
Richard Smith4b38ded2012-03-14 23:13:10 +00002863 assert(Pattern && "Missing instantiated-from-template information");
2864
2865 if (TSK == TSK_ExplicitInstantiationDefinition) {
2866 if (!Pattern->getDefinition())
2867 continue;
2868
2869 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2870 } else {
2871 MSInfo->setTemplateSpecializationKind(TSK);
2872 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2873 }
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002874 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2875 // No need to instantiate in-class initializers during explicit
2876 // instantiation.
2877 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2878 CXXRecordDecl *ClassPattern =
2879 Instantiation->getTemplateInstantiationPattern();
2880 DeclContext::lookup_result Lookup =
2881 ClassPattern->lookup(Field->getDeclName());
David Majnemer76a25622016-06-09 05:26:56 +00002882 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002883 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2884 TemplateArgs);
2885 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002886 }
2887 }
2888}
2889
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002890/// Instantiate the definitions of all of the members of the
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002891/// given class template specialization, which was named as part of an
2892/// explicit instantiation.
Mike Stump11289f42009-09-09 15:08:12 +00002893void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002894Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002895 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002896 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2897 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002898 // C++0x [temp.explicit]p7:
2899 // An explicit instantiation that names a class template
2900 // specialization is an explicit instantion of the same kind
2901 // (declaration or definition) of each of its members (not
2902 // including members inherited from base classes) that has not
2903 // been previously explicitly specialized in the translation unit
2904 // containing the explicit instantiation, except as described
2905 // below.
2906 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002907 getTemplateInstantiationArgs(ClassTemplateSpec),
2908 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002909}
2910
John McCalldadc5752010-08-24 06:29:42 +00002911StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002912Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002913 if (!S)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002914 return S;
Douglas Gregorebe10102009-08-20 07:17:43 +00002915
2916 TemplateInstantiator Instantiator(*this, TemplateArgs,
2917 SourceLocation(),
2918 DeclarationName());
2919 return Instantiator.TransformStmt(S);
2920}
2921
John McCalldadc5752010-08-24 06:29:42 +00002922ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002923Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002924 if (!E)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002925 return E;
Mike Stump11289f42009-09-09 15:08:12 +00002926
Douglas Gregora16548e2009-08-11 05:31:07 +00002927 TemplateInstantiator Instantiator(*this, TemplateArgs,
2928 SourceLocation(),
2929 DeclarationName());
2930 return Instantiator.TransformExpr(E);
2931}
2932
Richard Smithd59b8322012-12-19 01:39:02 +00002933ExprResult Sema::SubstInitializer(Expr *Init,
2934 const MultiLevelTemplateArgumentList &TemplateArgs,
2935 bool CXXDirectInit) {
2936 TemplateInstantiator Instantiator(*this, TemplateArgs,
2937 SourceLocation(),
2938 DeclarationName());
2939 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2940}
2941
Craig Topper99d23532015-12-24 23:58:29 +00002942bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002943 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002944 SmallVectorImpl<Expr *> &Outputs) {
Craig Topper99d23532015-12-24 23:58:29 +00002945 if (Exprs.empty())
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002946 return false;
Richard Smithd59b8322012-12-19 01:39:02 +00002947
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002948 TemplateInstantiator Instantiator(*this, TemplateArgs,
2949 SourceLocation(),
2950 DeclarationName());
Craig Topper99d23532015-12-24 23:58:29 +00002951 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2952 IsCall, Outputs);
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002953}
2954
Douglas Gregor14454802011-02-25 02:25:35 +00002955NestedNameSpecifierLoc
2956Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
Fangrui Song6907ce22018-07-30 19:24:48 +00002957 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor14454802011-02-25 02:25:35 +00002958 if (!NNS)
2959 return NestedNameSpecifierLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002960
Douglas Gregor14454802011-02-25 02:25:35 +00002961 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2962 DeclarationName());
2963 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2964}
2965
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002966/// Do template substitution on declaration name info.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002967DeclarationNameInfo
2968Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2969 const MultiLevelTemplateArgumentList &TemplateArgs) {
2970 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2971 NameInfo.getName());
2972 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2973}
2974
Douglas Gregoraa594892009-03-31 18:38:02 +00002975TemplateName
Douglas Gregordf846d12011-03-02 18:46:51 +00002976Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2977 TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002978 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002979 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2980 DeclarationName());
Douglas Gregordf846d12011-03-02 18:46:51 +00002981 CXXScopeSpec SS;
2982 SS.Adopt(QualifierLoc);
2983 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregoraa594892009-03-31 18:38:02 +00002984}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002985
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002986bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2987 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002988 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002989 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2990 DeclarationName());
Fangrui Song6907ce22018-07-30 19:24:48 +00002991
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002992 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00002993}
Douglas Gregor14cf7522010-04-30 18:55:50 +00002994
Richard Smith70b13042015-01-09 01:19:56 +00002995static const Decl *getCanonicalParmVarDecl(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002996 // When storing ParmVarDecls in the local instantiation scope, we always
2997 // want to use the ParmVarDecl from the canonical function declaration,
2998 // since the map is then valid for any redeclaration or definition of that
2999 // function.
3000 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
3001 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
3002 unsigned i = PV->getFunctionScopeIndex();
Richard Smith70b13042015-01-09 01:19:56 +00003003 // This parameter might be from a freestanding function type within the
3004 // function and isn't necessarily referring to one of FD's parameters.
Dmitri Gribenko66b6bb12019-04-10 20:25:07 +00003005 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
Richard Smith70b13042015-01-09 01:19:56 +00003006 return FD->getCanonicalDecl()->getParamDecl(i);
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00003007 }
3008 }
3009 return D;
3010}
3011
3012
Douglas Gregorf3010112011-01-07 16:43:16 +00003013llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
3014LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00003015 D = getCanonicalParmVarDecl(D);
Chris Lattnercab02a62011-02-17 20:34:02 +00003016 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor14cf7522010-04-30 18:55:50 +00003017 Current = Current->Outer) {
Chris Lattnercab02a62011-02-17 20:34:02 +00003018
Douglas Gregor14cf7522010-04-30 18:55:50 +00003019 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00003020 const Decl *CheckD = D;
3021 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00003022 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00003023 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00003024 return &Found->second;
Fangrui Song6907ce22018-07-30 19:24:48 +00003025
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00003026 // If this is a tag declaration, it's possible that we need to look for
3027 // a previous declaration.
3028 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregorec9fd132012-01-14 16:38:05 +00003029 CheckD = Tag->getPreviousDecl();
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00003030 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003031 CheckD = nullptr;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00003032 } while (CheckD);
Fangrui Song6907ce22018-07-30 19:24:48 +00003033
3034 // If we aren't combined with our outer scope, we're done.
Douglas Gregor14cf7522010-04-30 18:55:50 +00003035 if (!Current->CombineWithOuterScope)
3036 break;
3037 }
Chris Lattnercab02a62011-02-17 20:34:02 +00003038
Serge Pavlov7cd8f602013-07-15 06:14:07 +00003039 // If we're performing a partial substitution during template argument
3040 // deduction, we may not have values for template parameters yet.
3041 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
3042 isa<TemplateTemplateParmDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00003043 return nullptr;
Serge Pavlov7cd8f602013-07-15 06:14:07 +00003044
Serge Pavlove7ad8312015-05-15 10:10:28 +00003045 // Local types referenced prior to definition may require instantiation.
3046 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
3047 if (RD->isLocalClass())
3048 return nullptr;
3049
3050 // Enumeration types referenced prior to definition may appear as a result of
3051 // error recovery.
3052 if (isa<EnumDecl>(D))
Serge Pavlov4c511742015-05-04 16:44:39 +00003053 return nullptr;
3054
Chris Lattnercab02a62011-02-17 20:34:02 +00003055 // If we didn't find the decl, then we either have a sema bug, or we have a
3056 // forward reference to a label declaration. Return null to indicate that
3057 // we have an uninstantiated label.
3058 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Craig Topperc3ec1492014-05-26 06:22:03 +00003059 return nullptr;
Douglas Gregor14cf7522010-04-30 18:55:50 +00003060}
3061
John McCall19c1bfd2010-08-25 05:32:35 +00003062void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00003063 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00003064 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Richard Smith70b13042015-01-09 01:19:56 +00003065 if (Stored.isNull()) {
3066#ifndef NDEBUG
3067 // It should not be present in any surrounding scope either.
3068 LocalInstantiationScope *Current = this;
3069 while (Current->CombineWithOuterScope && Current->Outer) {
3070 Current = Current->Outer;
3071 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3072 "Instantiated local in inner and outer scopes");
3073 }
3074#endif
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003075 Stored = Inst;
Richard Smith70b13042015-01-09 01:19:56 +00003076 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
Richard Smithb2997f52019-05-21 20:10:50 +00003077 Pack->push_back(cast<VarDecl>(Inst));
Richard Smith70b13042015-01-09 01:19:56 +00003078 } else {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003079 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Richard Smith70b13042015-01-09 01:19:56 +00003080 }
Douglas Gregor14cf7522010-04-30 18:55:50 +00003081}
Douglas Gregorf3010112011-01-07 16:43:16 +00003082
James Y Knight48fefa32015-09-30 14:04:23 +00003083void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
Richard Smithb2997f52019-05-21 20:10:50 +00003084 VarDecl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00003085 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00003086 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
3087 Pack->push_back(Inst);
3088}
3089
3090void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
Richard Smith70b13042015-01-09 01:19:56 +00003091#ifndef NDEBUG
3092 // This should be the first time we've been told about this decl.
3093 for (LocalInstantiationScope *Current = this;
3094 Current && Current->CombineWithOuterScope; Current = Current->Outer)
3095 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3096 "Creating local pack after instantiation of local");
3097#endif
3098
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00003099 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00003100 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregorf3010112011-01-07 16:43:16 +00003101 DeclArgumentPack *Pack = new DeclArgumentPack;
3102 Stored = Pack;
3103 ArgumentPacks.push_back(Pack);
3104}
3105
Fangrui Song6907ce22018-07-30 19:24:48 +00003106void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003107 const TemplateArgument *ExplicitArgs,
3108 unsigned NumExplicitArgs) {
3109 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
3110 "Already have a partially-substituted pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00003111 assert((!PartiallySubstitutedPack
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003112 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
3113 "Wrong number of arguments in partially-substituted pack");
3114 PartiallySubstitutedPack = Pack;
3115 ArgsInPartiallySubstitutedPack = ExplicitArgs;
3116 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
3117}
3118
3119NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
3120 const TemplateArgument **ExplicitArgs,
3121 unsigned *NumExplicitArgs) const {
3122 if (ExplicitArgs)
Craig Topperc3ec1492014-05-26 06:22:03 +00003123 *ExplicitArgs = nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003124 if (NumExplicitArgs)
3125 *NumExplicitArgs = 0;
Fangrui Song6907ce22018-07-30 19:24:48 +00003126
3127 for (const LocalInstantiationScope *Current = this; Current;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003128 Current = Current->Outer) {
3129 if (Current->PartiallySubstitutedPack) {
3130 if (ExplicitArgs)
3131 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
3132 if (NumExplicitArgs)
3133 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
Fangrui Song6907ce22018-07-30 19:24:48 +00003134
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003135 return Current->PartiallySubstitutedPack;
3136 }
3137
3138 if (!Current->CombineWithOuterScope)
3139 break;
3140 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003141
3142 return nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003143}