blob: 701be0411f7cb61b3578dc92499bdda3bad207a9 [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,
Vlad Tsyrklevich38839d02019-10-28 14:36:31 -0700366 ConstraintsCheck, TemplateDecl *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,
Vlad Tsyrklevich38839d02019-10-28 14:36:31 -0700375 ConstraintSubstitution, TemplateDecl *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 Smith883dbc42017-05-25 22:47:05 +0000675 // FIXME: For synthesized members other than special members, produce a note.
676 auto *MD = dyn_cast<CXXMethodDecl>(Active->Entity);
677 auto CSM = MD ? getSpecialMember(MD) : CXXInvalid;
678 if (CSM != CXXInvalid) {
679 Diags.Report(Active->PointOfInstantiation,
680 diag::note_member_synthesized_at)
681 << CSM << Context.getTagDeclType(MD->getParent());
682 }
683 break;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000684 }
Gabor Horvath207e7b12018-02-10 14:04:45 +0000685
Richard Smith974c8b72019-10-19 00:04:43 +0000686 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
687 Diags.Report(Active->Entity->getLocation(),
688 diag::note_rewriting_operator_as_spaceship);
689 break;
690
Gabor Horvath207e7b12018-02-10 14:04:45 +0000691 case CodeSynthesisContext::Memoization:
692 break;
Saar Raz5d98ba62019-10-15 15:24:26 +0000693
Vlad Tsyrklevich38839d02019-10-28 14:36:31 -0700694 case CodeSynthesisContext::ConstraintsCheck:
695 if (auto *CD = dyn_cast<ConceptDecl>(Active->Entity)) {
696 SmallVector<char, 128> TemplateArgsStr;
697 llvm::raw_svector_ostream OS(TemplateArgsStr);
698 CD->printName(OS);
699 printTemplateArgumentList(OS, Active->template_arguments(),
700 getPrintingPolicy());
701 Diags.Report(Active->PointOfInstantiation,
702 diag::note_concept_specialization_here)
703 << OS.str()
704 << Active->InstantiationRange;
705 break;
Saar Raz5d98ba62019-10-15 15:24:26 +0000706 }
Vlad Tsyrklevich38839d02019-10-28 14:36:31 -0700707 // TODO: Concepts - implement this for constrained templates and partial
708 // specializations.
709 llvm_unreachable("only concept constraints are supported right now");
Saar Raz5d98ba62019-10-15 15:24:26 +0000710 break;
Vlad Tsyrklevich38839d02019-10-28 14:36:31 -0700711
Saar Raz5d98ba62019-10-15 15:24:26 +0000712 case CodeSynthesisContext::ConstraintSubstitution:
713 Diags.Report(Active->PointOfInstantiation,
714 diag::note_constraint_substitution_here)
715 << Active->InstantiationRange;
716 break;
Gabor Horvath207e7b12018-02-10 14:04:45 +0000717 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000718 }
719}
720
David Blaikie05785d12013-02-20 22:23:23 +0000721Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregoredb76852011-01-27 22:31:44 +0000722 if (InNonInstantiationSFINAEContext)
Craig Topperc3ec1492014-05-26 06:22:03 +0000723 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregoredb76852011-01-27 22:31:44 +0000724
Richard Smith696e3122017-02-23 01:43:54 +0000725 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
726 Active = CodeSynthesisContexts.rbegin(),
727 ActiveEnd = CodeSynthesisContexts.rend();
Douglas Gregor33834512009-06-14 07:33:30 +0000728 Active != ActiveEnd;
Fangrui Song6907ce22018-07-30 19:24:48 +0000729 ++Active)
Douglas Gregor84d49a22009-11-11 21:54:23 +0000730 {
Richard Smith13381222017-02-23 21:43:43 +0000731 switch (Active->Kind) {
Richard Smith696e3122017-02-23 01:43:54 +0000732 case CodeSynthesisContext::TemplateInstantiation:
Richard Smith72249ba2012-04-26 07:24:08 +0000733 // An instantiation of an alias template may or may not be a SFINAE
734 // context, depending on what else is on the stack.
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000735 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smith72249ba2012-04-26 07:24:08 +0000736 break;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +0000737 LLVM_FALLTHROUGH;
Richard Smith696e3122017-02-23 01:43:54 +0000738 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
739 case CodeSynthesisContext::ExceptionSpecInstantiation:
Saar Raz5d98ba62019-10-15 15:24:26 +0000740 case CodeSynthesisContext::ConstraintsCheck:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000741 // This is a template instantiation, so there is no SFINAE.
David Blaikie7a30dc52013-02-21 01:47:18 +0000742 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000743
Richard Smith696e3122017-02-23 01:43:54 +0000744 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
745 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
746 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000747 // A default template argument instantiation and substitution into
Fangrui Song6907ce22018-07-30 19:24:48 +0000748 // template parameters with arguments for prior parameters may or may
Douglas Gregore62e6a02009-11-11 19:13:48 +0000749 // not be a SFINAE context; look further up the stack.
Douglas Gregor33834512009-06-14 07:33:30 +0000750 break;
Mike Stump11289f42009-09-09 15:08:12 +0000751
Richard Smith696e3122017-02-23 01:43:54 +0000752 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
753 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
Saar Raz5d98ba62019-10-15 15:24:26 +0000754 case CodeSynthesisContext::ConstraintSubstitution:
755 // We're either substituting explicitly-specified template arguments
756 // or deduced template arguments or a constraint expression, so SFINAE
757 // applies.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000758 assert(Active->DeductionInfo && "Missing deduction info pointer");
759 return Active->DeductionInfo;
Richard Smith13381222017-02-23 21:43:43 +0000760
761 case CodeSynthesisContext::DeclaringSpecialMember:
Richard Smith883dbc42017-05-25 22:47:05 +0000762 case CodeSynthesisContext::DefiningSynthesizedFunction:
Richard Smith974c8b72019-10-19 00:04:43 +0000763 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
Richard Smith13381222017-02-23 21:43:43 +0000764 // This happens in a context unrelated to template instantiation, so
765 // there is no SFINAE.
766 return None;
Gabor Horvath207e7b12018-02-10 14:04:45 +0000767
Richard Smith5159bbad2018-09-05 22:30:37 +0000768 case CodeSynthesisContext::ExceptionSpecEvaluation:
769 // FIXME: This should not be treated as a SFINAE context, because
770 // we will cache an incorrect exception specification. However, clang
771 // bootstrap relies this! See PR31692.
772 break;
773
Gabor Horvath207e7b12018-02-10 14:04:45 +0000774 case CodeSynthesisContext::Memoization:
775 break;
Douglas Gregor33834512009-06-14 07:33:30 +0000776 }
Richard Smith13381222017-02-23 21:43:43 +0000777
778 // The inner context was transparent for SFINAE. If it occurred within a
779 // non-instantiation SFINAE context, then SFINAE applies.
780 if (Active->SavedInNonInstantiationSFINAEContext)
781 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregor33834512009-06-14 07:33:30 +0000782 }
783
David Blaikie7a30dc52013-02-21 01:47:18 +0000784 return None;
Douglas Gregor33834512009-06-14 07:33:30 +0000785}
786
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000787//===----------------------------------------------------------------------===/
788// Template Instantiation for Types
789//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000790namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000791 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000792 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000793 SourceLocation Loc;
794 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000795
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000796 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000797 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000798
799 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000800 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000801 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000802 DeclarationName Entity)
803 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000804 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000805
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000806 /// Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-08-04 16:50:30 +0000807 /// transformed.
808 ///
809 /// For the purposes of template instantiation, a type has already been
810 /// transformed if it is NULL or if it is not dependent.
Douglas Gregor5597ab42010-05-07 23:12:07 +0000811 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000812
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000813 /// Returns the location of the entity being instantiated, if known.
Douglas Gregord6ff3322009-08-04 16:50:30 +0000814 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000815
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000816 /// Returns the name of the entity being instantiated, if any.
Douglas Gregord6ff3322009-08-04 16:50:30 +0000817 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000818
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000819 /// Sets the "base" location and entity when that
Douglas Gregoref6ab412009-10-27 06:26:26 +0000820 /// information is known based on another transformation.
821 void setBase(SourceLocation Loc, DeclarationName Entity) {
822 this->Loc = Loc;
823 this->Entity = Entity;
824 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000825
826 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
827 SourceRange PatternRange,
Robert Wilhelm16e94b92013-08-09 18:02:13 +0000828 ArrayRef<UnexpandedParameterPack> Unexpanded,
829 bool &ShouldExpand, bool &RetainExpansion,
David Blaikie05785d12013-02-20 22:23:23 +0000830 Optional<unsigned> &NumExpansions) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000831 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000832 PatternRange, Unexpanded,
Fangrui Song6907ce22018-07-30 19:24:48 +0000833 TemplateArgs,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000834 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000835 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000836 NumExpansions);
837 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000838
Fangrui Song6907ce22018-07-30 19:24:48 +0000839 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
Douglas Gregorf3010112011-01-07 16:43:16 +0000840 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
841 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000842
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000843 TemplateArgument ForgetPartiallySubstitutedPack() {
844 TemplateArgument Result;
845 if (NamedDecl *PartialPack
846 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
847 MultiLevelTemplateArgumentList &TemplateArgs
848 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
849 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000850 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000851 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
852 Result = TemplateArgs(Depth, Index);
853 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
854 }
855 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000856
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000857 return Result;
858 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000859
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000860 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
861 if (Arg.isNull())
862 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000863
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000864 if (NamedDecl *PartialPack
865 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
866 MultiLevelTemplateArgumentList &TemplateArgs
867 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
868 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000869 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000870 TemplateArgs.setArgument(Depth, Index, Arg);
871 }
872 }
873
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000874 /// Transform the given declaration by instantiating a reference to
Douglas Gregord6ff3322009-08-04 16:50:30 +0000875 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000876 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000877
Fangrui Song6907ce22018-07-30 19:24:48 +0000878 void transformAttrs(Decl *Old, Decl *New) {
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000879 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
880 }
881
Richard Smithb2997f52019-05-21 20:10:50 +0000882 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
883 if (Old->isParameterPack()) {
884 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);
885 for (auto *New : NewDecls)
886 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
887 Old, cast<VarDecl>(New));
888 return;
889 }
890
891 assert(NewDecls.size() == 1 &&
892 "should only have multiple expansions for a pack");
893 Decl *New = NewDecls.front();
894
Richard Smithc38498f2015-04-27 21:27:54 +0000895 // If we've instantiated the call operator of a lambda or the call
896 // operator template of a generic lambda, update the "instantiation of"
897 // information.
898 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
899 if (NewMD && isLambdaCallOperator(NewMD)) {
900 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
901 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
902 NewTD->setInstantiatedFromMemberTemplate(
903 OldMD->getDescribedFunctionTemplate());
904 else
905 NewMD->setInstantiationOfMemberFunction(OldMD,
906 TSK_ImplicitInstantiation);
907 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000908
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000909 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
Richard Smithc7649dc2016-03-23 20:07:07 +0000910
911 // We recreated a local declaration, but not by instantiating it. There
912 // may be pending dependent diagnostics to produce.
913 if (auto *DC = dyn_cast<DeclContext>(Old))
914 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000915 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000916
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000917 /// Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000918 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000919 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000920
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000921 /// Transform the first qualifier within a scope by instantiating the
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000922 /// declaration.
923 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
Fangrui Song6907ce22018-07-30 19:24:48 +0000924
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000925 /// Rebuild the exception declaration and register the declaration
Douglas Gregorebe10102009-08-20 07:17:43 +0000926 /// as an instantiated local.
Fangrui Song6907ce22018-07-30 19:24:48 +0000927 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000928 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000929 SourceLocation StartLoc,
930 SourceLocation NameLoc,
931 IdentifierInfo *Name);
Mike Stump11289f42009-09-09 15:08:12 +0000932
Fangrui Song6907ce22018-07-30 19:24:48 +0000933 /// Rebuild the Objective-C exception declaration and register the
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000934 /// declaration as an instantiated local.
Fangrui Song6907ce22018-07-30 19:24:48 +0000935 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000936 TypeSourceInfo *TSInfo, QualType T);
Fangrui Song6907ce22018-07-30 19:24:48 +0000937
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000938 /// Check for tag mismatches when instantiating an
John McCall7f41d982009-09-11 04:59:25 +0000939 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000940 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
941 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000942 NestedNameSpecifierLoc QualifierLoc,
943 QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000944
Craig Topperc3ec1492014-05-26 06:22:03 +0000945 TemplateName
946 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
947 SourceLocation NameLoc,
948 QualType ObjectType = QualType(),
Richard Smithfd3dae02017-01-20 00:20:39 +0000949 NamedDecl *FirstQualifierInScope = nullptr,
950 bool AllowInjectedClassName = false);
Douglas Gregor9db53502011-03-02 18:07:45 +0000951
Tyler Nowickic724a83e2014-10-12 20:46:07 +0000952 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
953
John McCalldadc5752010-08-24 06:29:42 +0000954 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
955 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
956 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000957
John McCalldadc5752010-08-24 06:29:42 +0000958 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000959 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000960 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
961 SubstNonTypeTemplateParmPackExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000962
Richard Smithb2997f52019-05-21 20:10:50 +0000963 /// Rebuild a DeclRefExpr for a VarDecl reference.
964 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000965
Richard Smithb2997f52019-05-21 20:10:50 +0000966 /// Transform a reference to a function or init-capture parameter pack.
967 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000968
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000969 /// Transform a FunctionParmPackExpr which was built when we couldn't
Richard Smithb15fe3a2012-09-12 00:56:43 +0000970 /// expand a function parameter pack reference which refers to an expanded
971 /// pack.
972 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
973
Hans Wennborge113c202014-09-18 16:01:32 +0000974 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
Richard Smith2e321552014-11-12 02:00:47 +0000975 FunctionProtoTypeLoc TL) {
976 // Call the base version; it will forward to our overridden version below.
977 return inherited::TransformFunctionProtoType(TLB, TL);
978 }
979
980 template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +0000981 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
982 FunctionProtoTypeLoc TL,
983 CXXRecordDecl *ThisContext,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +0000984 Qualifiers ThisTypeQuals,
Richard Smith2e321552014-11-12 02:00:47 +0000985 Fn TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +0000986
Douglas Gregor715e4612011-01-14 22:40:04 +0000987 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +0000988 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +0000989 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +0000990 bool ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +0000991
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000992 /// Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +0000993 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +0000994 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000995 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000996
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000997 /// Transforms an already-substituted template type parameter pack
Douglas Gregorada4b792011-01-14 02:55:32 +0000998 /// into either itself (if we aren't substituting into its pack expansion)
999 /// or the appropriate substituted argument.
1000 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1001 SubstTemplateTypeParmPackTypeLoc TL);
1002
Richard Smith2589b9802012-07-25 03:56:55 +00001003 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1004 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1005 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
1006 }
1007
David Majnemerb1004102014-03-02 18:46:05 +00001008 TemplateParameterList *TransformTemplateParameterList(
Faisal Vali2cba1332013-10-23 06:44:28 +00001009 TemplateParameterList *OrigTPL) {
1010 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
Fangrui Song6907ce22018-07-30 19:24:48 +00001011
Faisal Vali2cba1332013-10-23 06:44:28 +00001012 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
Fangrui Song6907ce22018-07-30 19:24:48 +00001013 TemplateDeclInstantiator DeclInstantiator(getSema(),
Faisal Vali2cba1332013-10-23 06:44:28 +00001014 /* DeclContext *Owner */ Owner, TemplateArgs);
Fangrui Song6907ce22018-07-30 19:24:48 +00001015 return DeclInstantiator.SubstTemplateParams(OrigTPL);
Faisal Vali2cba1332013-10-23 06:44:28 +00001016 }
John McCall7c454bb2011-07-15 05:09:51 +00001017 private:
1018 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
1019 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001020 TemplateArgument arg);
Douglas Gregord6ff3322009-08-04 16:50:30 +00001021 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001022}
Douglas Gregor04318252009-07-06 15:59:29 +00001023
Douglas Gregor5597ab42010-05-07 23:12:07 +00001024bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1025 if (T.isNull())
1026 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00001027
Douglas Gregor678d76c2011-07-01 01:22:09 +00001028 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +00001029 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001030
Douglas Gregor5597ab42010-05-07 23:12:07 +00001031 getSema().MarkDeclarationsReferencedInType(Loc, T);
1032 return true;
1033}
1034
Eli Friedman8917ad52013-07-19 19:40:38 +00001035static TemplateArgument
1036getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001037 assert(S.ArgumentPackSubstitutionIndex >= 0);
Eli Friedman8917ad52013-07-19 19:40:38 +00001038 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1039 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
1040 if (Arg.isPackExpansion())
1041 Arg = Arg.getPackExpansionPattern();
1042 return Arg;
1043}
1044
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001045Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +00001046 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +00001047 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001048
Douglas Gregor2b6ca462009-09-03 21:38:09 +00001049 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +00001050 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +00001051 // If the corresponding template argument is NULL or non-existent, it's
1052 // because we are performing instantiation from explicitly-specified
1053 // template arguments in a function template, but there were some
1054 // arguments left unspecified.
1055 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1056 TTP->getPosition()))
1057 return D;
1058
Douglas Gregorf5500772011-01-05 15:48:55 +00001059 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
Fangrui Song6907ce22018-07-30 19:24:48 +00001060
Douglas Gregorf5500772011-01-05 15:48:55 +00001061 if (TTP->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001062 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregorf5500772011-01-05 15:48:55 +00001063 "Missing argument pack");
Eli Friedman8917ad52013-07-19 19:40:38 +00001064 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorf5500772011-01-05 15:48:55 +00001065 }
1066
Richard Smith1abacfc2017-08-29 22:14:43 +00001067 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001068 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +00001069 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001070 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001071 }
Mike Stump11289f42009-09-09 15:08:12 +00001072
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001073 // Fall through to find the instantiated declaration for this template
1074 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +00001075 }
Mike Stump11289f42009-09-09 15:08:12 +00001076
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001077 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +00001078}
1079
Douglas Gregor25289362010-03-01 17:25:41 +00001080Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +00001081 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +00001082 if (!Inst)
Craig Topperc3ec1492014-05-26 06:22:03 +00001083 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001084
Douglas Gregorebe10102009-08-20 07:17:43 +00001085 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1086 return Inst;
1087}
1088
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001089NamedDecl *
Fangrui Song6907ce22018-07-30 19:24:48 +00001090TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001091 SourceLocation Loc) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001092 // If the first part of the nested-name-specifier was a template type
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001093 // parameter, instantiate that type parameter down to a tag type.
1094 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001095 const TemplateTypeParmType *TTP
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001096 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Fangrui Song6907ce22018-07-30 19:24:48 +00001097
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001098 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001099 // FIXME: This needs testing w/ member access expressions.
1100 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
Fangrui Song6907ce22018-07-30 19:24:48 +00001101
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001102 if (TTP->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001103 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001104 "Missing argument pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001105
Douglas Gregore1d60df2011-01-14 23:41:42 +00001106 if (getSema().ArgumentPackSubstitutionIndex == -1)
Craig Topperc3ec1492014-05-26 06:22:03 +00001107 return nullptr;
1108
Eli Friedman8917ad52013-07-19 19:40:38 +00001109 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001110 }
1111
1112 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001113 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001114 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Fangrui Song6907ce22018-07-30 19:24:48 +00001115
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001116 if (const TagType *Tag = T->getAs<TagType>())
1117 return Tag->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001118
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001119 // The resulting type is not a tag; complain.
1120 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
Craig Topperc3ec1492014-05-26 06:22:03 +00001121 return nullptr;
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001122 }
1123 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001124
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001125 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001126}
1127
Douglas Gregorebe10102009-08-20 07:17:43 +00001128VarDecl *
1129TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +00001130 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001131 SourceLocation StartLoc,
1132 SourceLocation NameLoc,
1133 IdentifierInfo *Name) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00001134 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001135 StartLoc, NameLoc, Name);
Douglas Gregorf4e837f2010-04-26 17:57:08 +00001136 if (Var)
1137 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1138 return Var;
1139}
1140
Fangrui Song6907ce22018-07-30 19:24:48 +00001141VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1142 TypeSourceInfo *TSInfo,
Douglas Gregorf4e837f2010-04-26 17:57:08 +00001143 QualType T) {
1144 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1145 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +00001146 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1147 return Var;
1148}
1149
John McCall7f41d982009-09-11 04:59:25 +00001150QualType
John McCall954b5de2010-11-04 19:04:38 +00001151TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1152 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001153 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara6150c882010-05-11 21:36:43 +00001154 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +00001155 if (const TagType *TT = T->getAs<TagType>()) {
1156 TagDecl* TD = TT->getDecl();
1157
John McCall954b5de2010-11-04 19:04:38 +00001158 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +00001159
John McCall7f41d982009-09-11 04:59:25 +00001160 IdentifierInfo *Id = TD->getIdentifier();
1161
1162 // TODO: should we even warn on struct/class mismatches for this? Seems
1163 // like it's likely to produce a lot of spurious errors.
Richard Smith80b3c5a2012-08-17 00:12:27 +00001164 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001165 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieucaa33d32011-06-10 03:11:26 +00001166 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001167 TagLocation, Id)) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001168 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1169 << Id
1170 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1171 TD->getKindName());
1172 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1173 }
John McCall7f41d982009-09-11 04:59:25 +00001174 }
1175 }
1176
John McCall954b5de2010-11-04 19:04:38 +00001177 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1178 Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001179 QualifierLoc,
1180 T);
John McCall7f41d982009-09-11 04:59:25 +00001181}
1182
Richard Smithfd3dae02017-01-20 00:20:39 +00001183TemplateName TemplateInstantiator::TransformTemplateName(
1184 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1185 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1186 bool AllowInjectedClassName) {
Douglas Gregor9db53502011-03-02 18:07:45 +00001187 if (TemplateTemplateParmDecl *TTP
1188 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1189 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1190 // If the corresponding template argument is NULL or non-existent, it's
1191 // because we are performing instantiation from explicitly-specified
1192 // template arguments in a function template, but there were some
1193 // arguments left unspecified.
1194 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1195 TTP->getPosition()))
1196 return Name;
Fangrui Song6907ce22018-07-30 19:24:48 +00001197
Douglas Gregor9db53502011-03-02 18:07:45 +00001198 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
Fangrui Song6907ce22018-07-30 19:24:48 +00001199
Douglas Gregor9db53502011-03-02 18:07:45 +00001200 if (TTP->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001201 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregor9db53502011-03-02 18:07:45 +00001202 "Missing argument pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001203
Douglas Gregor9db53502011-03-02 18:07:45 +00001204 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1205 // We have the template argument pack to substitute, but we're not
1206 // actually expanding the enclosing pack expansion yet. So, just
1207 // keep the entire argument pack.
1208 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1209 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001210
1211 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor9db53502011-03-02 18:07:45 +00001212 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001213
Richard Smith1abacfc2017-08-29 22:14:43 +00001214 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001215 assert(!Template.isNull() && "Null template template argument");
Richard Smith1abacfc2017-08-29 22:14:43 +00001216 assert(!Template.getAsQualifiedTemplateName() &&
1217 "template decl to substitute is qualified?");
John McCalld9dfe3a2011-06-30 08:33:18 +00001218
1219 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregor9db53502011-03-02 18:07:45 +00001220 return Template;
1221 }
1222 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001223
Douglas Gregor9db53502011-03-02 18:07:45 +00001224 if (SubstTemplateTemplateParmPackStorage *SubstPack
1225 = Name.getAsSubstTemplateTemplateParmPack()) {
1226 if (getSema().ArgumentPackSubstitutionIndex == -1)
1227 return Name;
Fangrui Song6907ce22018-07-30 19:24:48 +00001228
Eli Friedman8917ad52013-07-19 19:40:38 +00001229 TemplateArgument Arg = SubstPack->getArgumentPack();
1230 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Richard Smith1abacfc2017-08-29 22:14:43 +00001231 return Arg.getAsTemplate().getNameToSubstitute();
Douglas Gregor9db53502011-03-02 18:07:45 +00001232 }
Richard Smithfd3dae02017-01-20 00:20:39 +00001233
1234 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1235 FirstQualifierInScope,
1236 AllowInjectedClassName);
Douglas Gregor9db53502011-03-02 18:07:45 +00001237}
1238
Fangrui Song6907ce22018-07-30 19:24:48 +00001239ExprResult
John McCall47f29ea2009-12-08 09:21:05 +00001240TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +00001241 if (!E->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001242 return E;
Anders Carlsson0b209a82009-09-11 01:22:35 +00001243
Bruno Ricci17ff0262018-10-27 19:21:19 +00001244 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
Anders Carlsson0b209a82009-09-11 01:22:35 +00001245}
1246
John McCalldadc5752010-08-24 06:29:42 +00001247ExprResult
John McCall13481c52010-02-06 08:42:39 +00001248TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001249 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +00001250 // If the corresponding template argument is NULL or non-existent, it's
1251 // because we are performing instantiation from explicitly-specified
1252 // template arguments in a function template, but there were some
1253 // arguments left unspecified.
1254 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1255 NTTP->getPosition()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001256 return E;
Mike Stump11289f42009-09-09 15:08:12 +00001257
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001258 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
Richard Smithb4f96252017-02-21 06:30:38 +00001259
1260 if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1261 // We're performing a partial substitution, so the substituted argument
1262 // could be dependent. As a result we can't create a SubstNonType*Expr
1263 // node now, since that represents a fully-substituted argument.
1264 // FIXME: We should have some AST representation for this.
1265 if (Arg.getKind() == TemplateArgument::Pack) {
1266 // FIXME: This won't work for alias templates.
1267 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1268 "unexpected pack arguments in partial substitution");
1269 Arg = Arg.pack_begin()->getPackExpansionPattern();
1270 }
1271 assert(Arg.getKind() == TemplateArgument::Expression &&
1272 "unexpected nontype template argument kind in partial substitution");
1273 return Arg.getAsExpr();
1274 }
1275
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001276 if (NTTP->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001277 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001278 "Missing argument pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001279
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001280 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001281 // We have an argument pack, but we can't select a particular argument
1282 // out of it yet. Therefore, we'll build an expression to hold on to that
1283 // argument pack.
1284 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
Fangrui Song6907ce22018-07-30 19:24:48 +00001285 E->getLocation(),
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001286 NTTP->getDeclName());
1287 if (TargetType.isNull())
1288 return ExprError();
Richard Smithf1f20e62018-02-14 02:07:53 +00001289
1290 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1291 TargetType.getNonLValueExprType(SemaRef.Context),
1292 TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP,
1293 E->getLocation(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001294 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001295
Eli Friedman8917ad52013-07-19 19:40:38 +00001296 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001297 }
Mike Stump11289f42009-09-09 15:08:12 +00001298
John McCall7c454bb2011-07-15 05:09:51 +00001299 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1300}
1301
Tyler Nowickic724a83e2014-10-12 20:46:07 +00001302const LoopHintAttr *
1303TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1304 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1305
1306 if (TransformedExpr == LH->getValue())
1307 return LH;
1308
1309 // Generate error if there is a problem with the value.
1310 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1311 return LH;
1312
1313 // Create new LoopHintValueAttr with integral expression in place of the
1314 // non-type template parameter.
Erich Keane6a24e802019-09-13 17:39:31 +00001315 return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
1316 LH->getState(), TransformedExpr, *LH);
Tyler Nowickic724a83e2014-10-12 20:46:07 +00001317}
1318
John McCall7c454bb2011-07-15 05:09:51 +00001319ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1320 NonTypeTemplateParmDecl *parm,
1321 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001322 TemplateArgument arg) {
John McCall7c454bb2011-07-15 05:09:51 +00001323 ExprResult result;
1324 QualType type;
1325
John McCall13481c52010-02-06 08:42:39 +00001326 // The template argument itself might be an expression, in which
1327 // case we just return that expression.
John McCall7c454bb2011-07-15 05:09:51 +00001328 if (arg.getKind() == TemplateArgument::Expression) {
1329 Expr *argExpr = arg.getAsExpr();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001330 result = argExpr;
John McCall7c454bb2011-07-15 05:09:51 +00001331 type = argExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001332
Eli Friedmanb826a002012-09-26 02:36:12 +00001333 } else if (arg.getKind() == TemplateArgument::Declaration ||
1334 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001335 ValueDecl *VD;
Eli Friedmanb826a002012-09-26 02:36:12 +00001336 if (arg.getKind() == TemplateArgument::Declaration) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00001337 VD = arg.getAsDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001338
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001339 // Find the instantiation of the template argument. This is
1340 // required for nested templates.
1341 VD = cast_or_null<ValueDecl>(
1342 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1343 if (!VD)
1344 return ExprError();
1345 } else {
1346 // Propagate NULL template argument.
Craig Topperc3ec1492014-05-26 06:22:03 +00001347 VD = nullptr;
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001348 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001349
John McCall15dda372010-02-06 10:23:53 +00001350 // Derive the type we want the substituted decl to have. This had
1351 // better be non-dependent, or these checks will have serious problems.
John McCall7c454bb2011-07-15 05:09:51 +00001352 if (parm->isExpandedParameterPack()) {
1353 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
Fangrui Song6907ce22018-07-30 19:24:48 +00001354 } else if (parm->isParameterPack() &&
John McCall7c454bb2011-07-15 05:09:51 +00001355 isa<PackExpansionType>(parm->getType())) {
1356 type = SemaRef.SubstType(
1357 cast<PackExpansionType>(parm->getType())->getPattern(),
1358 TemplateArgs, loc, parm->getDeclName());
1359 } else {
Richard Smith5f274382016-09-28 23:55:27 +00001360 type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1361 TemplateArgs, loc, parm->getDeclName());
John McCall7c454bb2011-07-15 05:09:51 +00001362 }
1363 assert(!type.isNull() && "type substitution failed for param type");
1364 assert(!type->isDependentType() && "param type still dependent");
1365 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCall13481c52010-02-06 08:42:39 +00001366
John McCall7c454bb2011-07-15 05:09:51 +00001367 if (!result.isInvalid()) type = result.get()->getType();
1368 } else {
1369 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1370
1371 // Note that this type can be different from the type of 'result',
1372 // e.g. if it's an enum type.
1373 type = arg.getIntegralType();
1374 }
1375 if (result.isInvalid()) return ExprError();
1376
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001377 Expr *resultExpr = result.get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001378 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1379 type, resultExpr->getValueKind(), loc, parm, resultExpr);
John McCall13481c52010-02-06 08:42:39 +00001380}
Fangrui Song6907ce22018-07-30 19:24:48 +00001381
1382ExprResult
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001383TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1384 SubstNonTypeTemplateParmPackExpr *E) {
1385 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1386 // We aren't expanding the parameter pack, so just return ourselves.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001387 return E;
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001388 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001389
1390 TemplateArgument Arg = E->getArgumentPack();
1391 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall7c454bb2011-07-15 05:09:51 +00001392 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1393 E->getParameterPackLocation(),
1394 Arg);
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001395}
John McCall13481c52010-02-06 08:42:39 +00001396
Richard Smithb2997f52019-05-21 20:10:50 +00001397ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
1398 SourceLocation Loc) {
Richard Smithb15fe3a2012-09-12 00:56:43 +00001399 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1400 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1401}
1402
1403ExprResult
1404TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1405 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1406 // We can expand this parameter pack now.
Richard Smithb2997f52019-05-21 20:10:50 +00001407 VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1408 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
Richard Smithb15fe3a2012-09-12 00:56:43 +00001409 if (!VD)
1410 return ExprError();
Richard Smithb2997f52019-05-21 20:10:50 +00001411 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
Richard Smithb15fe3a2012-09-12 00:56:43 +00001412 }
1413
1414 QualType T = TransformType(E->getType());
1415 if (T.isNull())
1416 return ExprError();
1417
1418 // Transform each of the parameter expansions into the corresponding
1419 // parameters in the instantiation of the function decl.
Richard Smithb2997f52019-05-21 20:10:50 +00001420 SmallVector<VarDecl *, 8> Vars;
1421 Vars.reserve(E->getNumExpansions());
Richard Smithb15fe3a2012-09-12 00:56:43 +00001422 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1423 I != End; ++I) {
Richard Smithb2997f52019-05-21 20:10:50 +00001424 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
Richard Smithb15fe3a2012-09-12 00:56:43 +00001425 if (!D)
1426 return ExprError();
Richard Smithb2997f52019-05-21 20:10:50 +00001427 Vars.push_back(D);
Richard Smithb15fe3a2012-09-12 00:56:43 +00001428 }
1429
Richard Smith7bf8f6f2019-06-04 17:17:20 +00001430 auto *PackExpr =
1431 FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
1432 E->getParameterPackLocation(), Vars);
1433 getSema().MarkFunctionParmPackReferenced(PackExpr);
1434 return PackExpr;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001435}
1436
1437ExprResult
1438TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
Richard Smithb2997f52019-05-21 20:10:50 +00001439 VarDecl *PD) {
Richard Smithb15fe3a2012-09-12 00:56:43 +00001440 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1441 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1442 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1443 assert(Found && "no instantiation for parameter pack");
1444
1445 Decl *TransformedDecl;
1446 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
Nico Weberc153d242014-07-28 00:02:09 +00001447 // If this is a reference to a function parameter pack which we can
1448 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
Richard Smithb15fe3a2012-09-12 00:56:43 +00001449 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1450 QualType T = TransformType(E->getType());
1451 if (T.isNull())
1452 return ExprError();
Richard Smith7bf8f6f2019-06-04 17:17:20 +00001453 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
1454 E->getExprLoc(), *Pack);
1455 getSema().MarkFunctionParmPackReferenced(PackExpr);
1456 return PackExpr;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001457 }
1458
1459 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1460 } else {
1461 TransformedDecl = Found->get<Decl*>();
1462 }
1463
1464 // We have either an unexpanded pack or a specific expansion.
Richard Smithb2997f52019-05-21 20:10:50 +00001465 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
Richard Smithb15fe3a2012-09-12 00:56:43 +00001466}
1467
1468ExprResult
John McCall13481c52010-02-06 08:42:39 +00001469TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1470 NamedDecl *D = E->getDecl();
Richard Smithb15fe3a2012-09-12 00:56:43 +00001471
1472 // Handle references to non-type template parameters and non-type template
1473 // parameter packs.
John McCall13481c52010-02-06 08:42:39 +00001474 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1475 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1476 return TransformTemplateParmRefExpr(E, NTTP);
Fangrui Song6907ce22018-07-30 19:24:48 +00001477
Douglas Gregor954de172009-10-31 17:21:17 +00001478 // We have a non-type template parameter that isn't fully substituted;
1479 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001480 }
Mike Stump11289f42009-09-09 15:08:12 +00001481
Richard Smithb15fe3a2012-09-12 00:56:43 +00001482 // Handle references to function parameter packs.
Richard Smithb2997f52019-05-21 20:10:50 +00001483 if (VarDecl *PD = dyn_cast<VarDecl>(D))
Richard Smithb15fe3a2012-09-12 00:56:43 +00001484 if (PD->isParameterPack())
1485 return TransformFunctionParmPackRefExpr(E, PD);
1486
John McCall47f29ea2009-12-08 09:21:05 +00001487 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001488}
1489
John McCalldadc5752010-08-24 06:29:42 +00001490ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001491 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001492 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1493 getDescribedFunctionTemplate() &&
1494 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001495 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
Fangrui Song6907ce22018-07-30 19:24:48 +00001496 cast<FunctionDecl>(E->getParam()->getDeclContext()),
Douglas Gregor033f6752009-12-23 23:03:06 +00001497 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001498}
1499
Richard Smith2e321552014-11-12 02:00:47 +00001500template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +00001501QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1502 FunctionProtoTypeLoc TL,
1503 CXXRecordDecl *ThisContext,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001504 Qualifiers ThisTypeQuals,
Richard Smith2e321552014-11-12 02:00:47 +00001505 Fn TransformExceptionSpec) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001506 // We need a local instantiation scope for this function prototype.
1507 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
Richard Smith2e321552014-11-12 02:00:47 +00001508 return inherited::TransformFunctionProtoType(
1509 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +00001510}
1511
John McCall58f10c32010-03-11 09:03:00 +00001512ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001513TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001514 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001515 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001516 bool ExpectParameterPack) {
Anastasia Stulovaa29aa472019-11-27 11:03:11 +00001517 auto NewParm =
1518 SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1519 NumExpansions, ExpectParameterPack);
1520 if (NewParm && SemaRef.getLangOpts().OpenCL)
1521 SemaRef.deduceOpenCLAddressSpace(NewParm);
1522 return NewParm;
John McCall58f10c32010-03-11 09:03:00 +00001523}
1524
Mike Stump11289f42009-09-09 15:08:12 +00001525QualType
John McCall550e0c22009-10-21 00:40:46 +00001526TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001527 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001528 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001529 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001530 // Replace the template type parameter with its corresponding
1531 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001532
1533 // If the corresponding template argument is NULL or doesn't exist, it's
1534 // because we are performing instantiation from explicitly-specified
1535 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001536 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001537 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1538 TemplateTypeParmTypeLoc NewTL
1539 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1540 NewTL.setNameLoc(TL.getNameLoc());
1541 return TL.getType();
1542 }
Mike Stump11289f42009-09-09 15:08:12 +00001543
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001544 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
Fangrui Song6907ce22018-07-30 19:24:48 +00001545
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001546 if (T->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001547 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001548 "Missing argument pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001549
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001550 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001551 // We have the template argument pack, but we're not expanding the
1552 // enclosing pack expansion yet. Just save the template argument
1553 // pack for later substitution.
1554 QualType Result
1555 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1556 SubstTemplateTypeParmPackTypeLoc NewTL
1557 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1558 NewTL.setNameLoc(TL.getNameLoc());
1559 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001560 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001561
Eli Friedman8917ad52013-07-19 19:40:38 +00001562 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001563 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001564
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001565 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001566 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001567
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001568 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001569
1570 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001571 QualType Result
1572 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1573 SubstTemplateTypeParmTypeLoc NewTL
1574 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1575 NewTL.setNameLoc(TL.getNameLoc());
1576 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001577 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001578
1579 // The template type parameter comes from an inner template (e.g.,
1580 // the template parameter list of a member template inside the
1581 // template we are instantiating). Create a new template type
1582 // parameter with the template "level" reduced by one.
Craig Topperc3ec1492014-05-26 06:22:03 +00001583 TemplateTypeParmDecl *NewTTPDecl = nullptr;
Chandler Carruth08836322011-05-01 00:51:33 +00001584 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1585 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1586 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1587
Richard Smithb4f96252017-02-21 06:30:38 +00001588 QualType Result = getSema().Context.getTemplateTypeParmType(
1589 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1590 T->isParameterPack(), NewTTPDecl);
John McCall550e0c22009-10-21 00:40:46 +00001591 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1592 NewTL.setNameLoc(TL.getNameLoc());
1593 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001594}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001595
Fangrui Song6907ce22018-07-30 19:24:48 +00001596QualType
Douglas Gregorada4b792011-01-14 02:55:32 +00001597TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1598 TypeLocBuilder &TLB,
1599 SubstTemplateTypeParmPackTypeLoc TL) {
1600 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1601 // We aren't expanding the parameter pack, so just return ourselves.
1602 SubstTemplateTypeParmPackTypeLoc NewTL
1603 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1604 NewTL.setNameLoc(TL.getNameLoc());
1605 return TL.getType();
1606 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001607
1608 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1609 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1610 QualType Result = Arg.getAsType();
1611
Douglas Gregorada4b792011-01-14 02:55:32 +00001612 Result = getSema().Context.getSubstTemplateTypeParmType(
1613 TL.getTypePtr()->getReplacedParameter(),
1614 Result);
1615 SubstTemplateTypeParmTypeLoc NewTL
1616 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1617 NewTL.setNameLoc(TL.getNameLoc());
1618 return Result;
1619}
1620
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001621/// Perform substitution on the type T with a given set of template
John McCall76d824f2009-08-25 22:02:44 +00001622/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001623///
1624/// This routine substitutes the given template arguments into the
1625/// type T and produces the instantiated type.
1626///
1627/// \param T the type into which the template arguments will be
1628/// substituted. If this type is not dependent, it will be returned
1629/// immediately.
1630///
James Dennett634962f2012-06-14 21:40:34 +00001631/// \param Args the template arguments that will be
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001632/// substituted for the top-level template parameters within T.
1633///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001634/// \param Loc the location in the source code where this substitution
1635/// is being performed. It will typically be the location of the
1636/// declarator (if we're instantiating the type of some declaration)
1637/// or the location of the type in the source code (if, e.g., we're
1638/// instantiating the type of a cast expression).
1639///
1640/// \param Entity the name of the entity associated with a declaration
1641/// being instantiated (if any). May be empty to indicate that there
1642/// is no such entity (if, e.g., this is a type that occurs as part of
1643/// a cast expression) or that the entity has no name (e.g., an
1644/// unnamed function parameter).
1645///
Richard Smithee579842017-01-30 20:39:26 +00001646/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1647/// acceptable as the top level type of the result.
1648///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001649/// \returns If the instantiation succeeds, the instantiated
1650/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001651TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001652 const MultiLevelTemplateArgumentList &Args,
1653 SourceLocation Loc,
Richard Smithee579842017-01-30 20:39:26 +00001654 DeclarationName Entity,
1655 bool AllowDeducedTST) {
Richard Smith696e3122017-02-23 01:43:54 +00001656 assert(!CodeSynthesisContexts.empty() &&
John McCall609459e2009-10-21 00:58:09 +00001657 "Cannot perform an instantiation without some context on the "
1658 "instantiation stack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001659
1660 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001661 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001662 return T;
1663
1664 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
Richard Smithee579842017-01-30 20:39:26 +00001665 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
1666 : Instantiator.TransformType(T);
John McCall609459e2009-10-21 00:58:09 +00001667}
1668
Douglas Gregor5499af42011-01-05 23:12:31 +00001669TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1670 const MultiLevelTemplateArgumentList &Args,
1671 SourceLocation Loc,
1672 DeclarationName Entity) {
Richard Smith696e3122017-02-23 01:43:54 +00001673 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001674 "Cannot perform an instantiation without some context on the "
1675 "instantiation stack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001676
Douglas Gregor5499af42011-01-05 23:12:31 +00001677 if (TL.getType().isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001678 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001679
Fangrui Song6907ce22018-07-30 19:24:48 +00001680 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001681 !TL.getType()->isVariablyModifiedType()) {
1682 // FIXME: Make a copy of the TypeLoc data here, so that we can
1683 // return a new TypeSourceInfo. Inefficient!
1684 TypeLocBuilder TLB;
1685 TLB.pushFullCopy(TL);
1686 return TLB.getTypeSourceInfo(Context, TL.getType());
1687 }
1688
1689 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1690 TypeLocBuilder TLB;
1691 TLB.reserve(TL.getFullDataSize());
1692 QualType Result = Instantiator.TransformType(TLB, TL);
1693 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001694 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001695
1696 return TLB.getTypeSourceInfo(Context, Result);
1697}
1698
John McCall609459e2009-10-21 00:58:09 +00001699/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001700QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001701 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001702 SourceLocation Loc, DeclarationName Entity) {
Richard Smith696e3122017-02-23 01:43:54 +00001703 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregor79cf6032009-03-10 20:44:00 +00001704 "Cannot perform an instantiation without some context on the "
1705 "instantiation stack");
1706
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001707 // If T is not a dependent type or a variably-modified type, there
1708 // is nothing to do.
Douglas Gregor678d76c2011-07-01 01:22:09 +00001709 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001710 return T;
1711
Douglas Gregord6ff3322009-08-04 16:50:30 +00001712 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1713 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001714}
Douglas Gregor463421d2009-03-03 04:44:36 +00001715
John McCallb29f78f2010-04-09 17:38:44 +00001716static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Nico Weberc0973372016-02-01 22:31:51 +00001717 if (T->getType()->isInstantiationDependentType() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00001718 T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001719 return true;
1720
Abramo Bagnara6d810632010-12-14 22:11:44 +00001721 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00001722 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCallb29f78f2010-04-09 17:38:44 +00001723 return false;
1724
David Blaikie6adc78e2013-02-18 22:06:02 +00001725 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Nico Weberc0973372016-02-01 22:31:51 +00001726 for (ParmVarDecl *P : FP.getParams()) {
Reid Klecknera09e44c2013-07-31 21:00:18 +00001727 // This must be synthesized from a typedef.
1728 if (!P) continue;
1729
Nico Weberc0973372016-02-01 22:31:51 +00001730 // If there are any parameters, a new TypeSourceInfo that refers to the
1731 // instantiated parameters must be built.
1732 return true;
John McCallb29f78f2010-04-09 17:38:44 +00001733 }
1734
1735 return false;
1736}
1737
1738/// A form of SubstType intended specifically for instantiating the
1739/// type of a FunctionDecl. Its purpose is solely to force the
Richard Smith2e321552014-11-12 02:00:47 +00001740/// instantiation of default-argument expressions and to avoid
1741/// instantiating an exception-specification.
John McCallb29f78f2010-04-09 17:38:44 +00001742TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1743 const MultiLevelTemplateArgumentList &Args,
1744 SourceLocation Loc,
Douglas Gregor3024f072012-04-16 07:05:22 +00001745 DeclarationName Entity,
1746 CXXRecordDecl *ThisContext,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001747 Qualifiers ThisTypeQuals) {
Richard Smith696e3122017-02-23 01:43:54 +00001748 assert(!CodeSynthesisContexts.empty() &&
John McCallb29f78f2010-04-09 17:38:44 +00001749 "Cannot perform an instantiation without some context on the "
1750 "instantiation stack");
Nico Weberc0973372016-02-01 22:31:51 +00001751
John McCallb29f78f2010-04-09 17:38:44 +00001752 if (!NeedsInstantiationAsFunctionType(T))
1753 return T;
1754
1755 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1756
1757 TypeLocBuilder TLB;
1758
1759 TypeLoc TL = T->getTypeLoc();
1760 TLB.reserve(TL.getFullDataSize());
1761
Douglas Gregor3024f072012-04-16 07:05:22 +00001762 QualType Result;
David Blaikie6adc78e2013-02-18 22:06:02 +00001763
Richard Smith2e321552014-11-12 02:00:47 +00001764 if (FunctionProtoTypeLoc Proto =
1765 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1766 // Instantiate the type, other than its exception specification. The
1767 // exception specification is instantiated in InitFunctionInstantiation
1768 // once we've built the FunctionDecl.
1769 // FIXME: Set the exception specification to EST_Uninstantiated here,
1770 // instead of rebuilding the function type again later.
1771 Result = Instantiator.TransformFunctionProtoType(
1772 TLB, Proto, ThisContext, ThisTypeQuals,
1773 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1774 bool &Changed) { return false; });
Douglas Gregor3024f072012-04-16 07:05:22 +00001775 } else {
1776 Result = Instantiator.TransformType(TLB, TL);
1777 }
John McCallb29f78f2010-04-09 17:38:44 +00001778 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001779 return nullptr;
John McCallb29f78f2010-04-09 17:38:44 +00001780
1781 return TLB.getTypeSourceInfo(Context, Result);
1782}
1783
Richard Smithcd198152017-06-07 21:46:22 +00001784bool Sema::SubstExceptionSpec(SourceLocation Loc,
1785 FunctionProtoType::ExceptionSpecInfo &ESI,
1786 SmallVectorImpl<QualType> &ExceptionStorage,
1787 const MultiLevelTemplateArgumentList &Args) {
1788 assert(ESI.Type != EST_Uninstantiated);
1789
1790 bool Changed = false;
1791 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
1792 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
1793 Changed);
1794}
1795
Richard Smith2e321552014-11-12 02:00:47 +00001796void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1797 const MultiLevelTemplateArgumentList &Args) {
1798 FunctionProtoType::ExceptionSpecInfo ESI =
1799 Proto->getExtProtoInfo().ExceptionSpec;
Richard Smith2e321552014-11-12 02:00:47 +00001800
1801 SmallVector<QualType, 4> ExceptionStorage;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001802 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
Richard Smithcd198152017-06-07 21:46:22 +00001803 ESI, ExceptionStorage, Args))
Richard Smith2e321552014-11-12 02:00:47 +00001804 // On error, recover by dropping the exception specification.
1805 ESI.Type = EST_None;
1806
1807 UpdateExceptionSpec(New, ESI);
1808}
1809
Fangrui Song6907ce22018-07-30 19:24:48 +00001810ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001811 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall8fb0d9d2011-05-01 22:35:37 +00001812 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001813 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001814 bool ExpectParameterPack) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001815 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Craig Topperc3ec1492014-05-26 06:22:03 +00001816 TypeSourceInfo *NewDI = nullptr;
1817
Douglas Gregor5499af42011-01-05 23:12:31 +00001818 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00001819 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1820
Fangrui Song6907ce22018-07-30 19:24:48 +00001821 // We have a function parameter pack. Substitute into the pattern of the
Douglas Gregor5499af42011-01-05 23:12:31 +00001822 // expansion.
Fangrui Song6907ce22018-07-30 19:24:48 +00001823 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
Douglas Gregor5499af42011-01-05 23:12:31 +00001824 OldParm->getLocation(), OldParm->getDeclName());
1825 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001826 return nullptr;
1827
Douglas Gregor5499af42011-01-05 23:12:31 +00001828 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1829 // We still have unexpanded parameter packs, which means that
1830 // our function parameter is still a function parameter pack.
1831 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001832 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001833 NumExpansions);
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001834 } else if (ExpectParameterPack) {
1835 // We expected to get a parameter pack but didn't (because the type
1836 // itself is not a pack expansion type), so complain. This can occur when
1837 // the substitution goes through an alias template that "loses" the
1838 // pack expansion.
Fangrui Song6907ce22018-07-30 19:24:48 +00001839 Diag(OldParm->getLocation(),
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001840 diag::err_function_parameter_pack_without_parameter_packs)
1841 << NewDI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001842 return nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +00001843 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001844 } else {
Fangrui Song6907ce22018-07-30 19:24:48 +00001845 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
Douglas Gregor5499af42011-01-05 23:12:31 +00001846 OldParm->getDeclName());
1847 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001848
Douglas Gregor940bca72010-04-12 07:48:19 +00001849 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001850 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001851
1852 if (NewDI->getType()->isVoidType()) {
1853 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
Craig Topperc3ec1492014-05-26 06:22:03 +00001854 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001855 }
1856
1857 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001858 OldParm->getInnerLocStart(),
Douglas Gregor940bca72010-04-12 07:48:19 +00001859 OldParm->getLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001860 OldParm->getIdentifier(),
1861 NewDI->getType(), NewDI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001862 OldParm->getStorageClass());
Douglas Gregor940bca72010-04-12 07:48:19 +00001863 if (!NewParm)
Craig Topperc3ec1492014-05-26 06:22:03 +00001864 return nullptr;
1865
Douglas Gregor940bca72010-04-12 07:48:19 +00001866 // Mark the (new) default argument as uninstantiated (if any).
1867 if (OldParm->hasUninstantiatedDefaultArg()) {
1868 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1869 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001870 } else if (OldParm->hasUnparsedDefaultArg()) {
1871 NewParm->setUnparsedDefaultArg();
1872 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001873 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1874 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
Serge Pavlov73c6a242015-08-23 10:22:28 +00001875 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1876 // Instantiate default arguments for methods of local classes (DR1484)
1877 // and non-defining declarations.
1878 Sema::ContextRAII SavedContext(*this, OwningFunc);
Akira Hatanakad644e022016-12-16 03:19:41 +00001879 LocalInstantiationScope Local(*this, true);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001880 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
John McCalldc40b612015-12-11 01:56:36 +00001881 if (NewArg.isUsable()) {
1882 // It would be nice if we still had this.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001883 SourceLocation EqualLoc = NewArg.get()->getBeginLoc();
John McCalldc40b612015-12-11 01:56:36 +00001884 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1885 }
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001886 } else {
1887 // FIXME: if we non-lazily instantiated non-dependent default args for
1888 // non-dependent parameter types we could remove a bunch of duplicate
1889 // conversion warnings for such arguments.
1890 NewParm->setUninstantiatedDefaultArg(Arg);
1891 }
1892 }
Douglas Gregor940bca72010-04-12 07:48:19 +00001893
1894 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Fangrui Song6907ce22018-07-30 19:24:48 +00001895
Douglas Gregorf3010112011-01-07 16:43:16 +00001896 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smith928be492012-01-25 02:14:59 +00001897 // Add the new parameter to the instantiated parameter pack.
Douglas Gregorf3010112011-01-07 16:43:16 +00001898 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1899 } else {
1900 // Introduce an Old -> New mapping
Fangrui Song6907ce22018-07-30 19:24:48 +00001901 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001902 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001903
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001904 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1905 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001906 NewParm->setDeclContext(CurContext);
John McCall8fb0d9d2011-05-01 22:35:37 +00001907
1908 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1909 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rosea0a86be2013-03-08 22:25:36 +00001910
1911 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1912
Fangrui Song6907ce22018-07-30 19:24:48 +00001913 return NewParm;
Douglas Gregor940bca72010-04-12 07:48:19 +00001914}
1915
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001916/// Substitute the given template arguments into the given set of
Douglas Gregordd472162011-01-07 00:20:55 +00001917/// parameters, producing the set of parameter types that would be generated
1918/// from such a substitution.
David Majnemer59f77922016-06-24 04:05:48 +00001919bool Sema::SubstParmTypes(
1920 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1921 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1922 const MultiLevelTemplateArgumentList &TemplateArgs,
1923 SmallVectorImpl<QualType> &ParamTypes,
1924 SmallVectorImpl<ParmVarDecl *> *OutParams,
1925 ExtParameterInfoBuilder &ParamInfos) {
Richard Smith696e3122017-02-23 01:43:54 +00001926 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregordd472162011-01-07 00:20:55 +00001927 "Cannot perform an instantiation without some context on the "
1928 "instantiation stack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001929
1930 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
Douglas Gregordd472162011-01-07 00:20:55 +00001931 DeclarationName());
David Majnemer59f77922016-06-24 04:05:48 +00001932 return Instantiator.TransformFunctionTypeParams(
1933 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
Douglas Gregordd472162011-01-07 00:20:55 +00001934}
1935
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001936/// Perform substitution on the base class specifiers of the
John McCall76d824f2009-08-25 22:02:44 +00001937/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001938///
1939/// Produces a diagnostic and returns true on error, returns false and
1940/// attaches the instantiated base classes to the class template
1941/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001942bool
John McCall76d824f2009-08-25 22:02:44 +00001943Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1944 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001945 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001946 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001947 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Richard Trieub5841332015-04-15 01:21:42 +00001948 for (const auto &Base : Pattern->bases()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001949 if (!Base.getType()->isDependentType()) {
1950 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay76d0b462013-06-21 18:58:32 +00001951 if (RD->isInvalidDecl())
1952 Instantiation->setInvalidDecl();
1953 }
Aaron Ballman574705e2014-03-13 15:41:46 +00001954 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001955 continue;
1956 }
1957
Douglas Gregor752a5952011-01-03 22:36:02 +00001958 SourceLocation EllipsisLoc;
Douglas Gregorc52264e2011-03-02 02:04:06 +00001959 TypeSourceInfo *BaseTypeLoc;
Aaron Ballman574705e2014-03-13 15:41:46 +00001960 if (Base.isPackExpansion()) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001961 // This is a pack expansion. See whether we should expand it now, or
1962 // wait until later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001963 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Aaron Ballman574705e2014-03-13 15:41:46 +00001964 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001965 Unexpanded);
1966 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001967 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001968 Optional<unsigned> NumExpansions;
Fangrui Song6907ce22018-07-30 19:24:48 +00001969 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
Aaron Ballman574705e2014-03-13 15:41:46 +00001970 Base.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001971 Unexpanded,
Fangrui Song6907ce22018-07-30 19:24:48 +00001972 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001973 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001974 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001975 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001976 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001977 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001978
Douglas Gregor752a5952011-01-03 22:36:02 +00001979 // If we should expand this pack expansion now, do so.
1980 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001981 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001982 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
Fangrui Song6907ce22018-07-30 19:24:48 +00001983
Aaron Ballman574705e2014-03-13 15:41:46 +00001984 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001985 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001986 Base.getSourceRange().getBegin(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001987 DeclarationName());
1988 if (!BaseTypeLoc) {
1989 Invalid = true;
1990 continue;
1991 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001992
Douglas Gregor752a5952011-01-03 22:36:02 +00001993 if (CXXBaseSpecifier *InstantiatedBase
1994 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001995 Base.getSourceRange(),
1996 Base.isVirtual(),
1997 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001998 BaseTypeLoc,
1999 SourceLocation()))
2000 InstantiatedBases.push_back(InstantiatedBase);
2001 else
2002 Invalid = true;
2003 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002004
Douglas Gregor752a5952011-01-03 22:36:02 +00002005 continue;
2006 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002007
Douglas Gregor752a5952011-01-03 22:36:02 +00002008 // The resulting base specifier will (still) be a pack expansion.
Aaron Ballman574705e2014-03-13 15:41:46 +00002009 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregorc52264e2011-03-02 02:04:06 +00002010 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Aaron Ballman574705e2014-03-13 15:41:46 +00002011 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00002012 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00002013 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00002014 DeclarationName());
2015 } else {
Aaron Ballman574705e2014-03-13 15:41:46 +00002016 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00002017 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00002018 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00002019 DeclarationName());
Douglas Gregor752a5952011-01-03 22:36:02 +00002020 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002021
Nick Lewycky19b9f952010-07-26 16:56:01 +00002022 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00002023 Invalid = true;
2024 continue;
2025 }
2026
2027 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002028 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00002029 Base.getSourceRange(),
2030 Base.isVirtual(),
2031 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00002032 BaseTypeLoc,
2033 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00002034 InstantiatedBases.push_back(InstantiatedBase);
2035 else
2036 Invalid = true;
2037 }
2038
Craig Topperaa700cb2015-12-27 21:55:19 +00002039 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
Douglas Gregor463421d2009-03-03 04:44:36 +00002040 Invalid = true;
2041
2042 return Invalid;
2043}
2044
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002045// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00002046namespace clang {
2047 namespace sema {
2048 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
2049 const MultiLevelTemplateArgumentList &TemplateArgs);
Erich Keanea32910d2017-03-23 18:51:54 +00002050 Attr *instantiateTemplateAttributeForDecl(
2051 const Attr *At, ASTContext &C, Sema &S,
2052 const MultiLevelTemplateArgumentList &TemplateArgs);
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00002053 }
2054}
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002055
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002056/// Instantiate the definition of a class from a given pattern.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002057///
2058/// \param PointOfInstantiation The point of instantiation within the
2059/// source code.
2060///
2061/// \param Instantiation is the declaration whose definition is being
2062/// instantiated. This will be either a class template specialization
2063/// or a member class of a class template specialization.
2064///
2065/// \param Pattern is the pattern from which the instantiation
2066/// occurs. This will be either the declaration of a class template or
2067/// the declaration of a member class of a class template.
2068///
2069/// \param TemplateArgs The template arguments to be substituted into
2070/// the pattern.
2071///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002072/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002073///
2074/// \param Complain whether to complain if the class cannot be instantiated due
2075/// to the lack of a definition.
2076///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002077/// \returns true if an error occurred, false otherwise.
2078bool
2079Sema::InstantiateClass(SourceLocation PointOfInstantiation,
2080 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002081 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002082 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002083 bool Complain) {
Mike Stump11289f42009-09-09 15:08:12 +00002084 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002085 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Vassil Vassilevb21ee082016-08-18 22:01:25 +00002086 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00002087 Instantiation->getInstantiatedFromMemberClass(),
2088 Pattern, PatternDef, TSK, Complain))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002089 return true;
Anton Afanasyevd880de22019-03-30 08:42:48 +00002090
2091 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
Lubos Lunakab8cde42019-05-12 10:39:21 +00002092 std::string Name;
2093 llvm::raw_string_ostream OS(Name);
2094 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
2095 /*Qualified=*/true);
2096 return Name;
Anton Afanasyevd880de22019-03-30 08:42:48 +00002097 });
2098
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002099 Pattern = PatternDef;
2100
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002101 // Record the point of instantiation.
Fangrui Song6907ce22018-07-30 19:24:48 +00002102 if (MemberSpecializationInfo *MSInfo
Douglas Gregord6ba93d2009-10-15 15:54:05 +00002103 = Instantiation->getMemberSpecializationInfo()) {
2104 MSInfo->setTemplateSpecializationKind(TSK);
2105 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Fangrui Song6907ce22018-07-30 19:24:48 +00002106 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weber3ffc4c92011-12-20 20:32:49 +00002107 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregoref6ab412009-10-27 06:26:26 +00002108 Spec->setTemplateSpecializationKind(TSK);
2109 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00002110 }
Richard Smitha1087602014-03-10 00:04:29 +00002111
Douglas Gregorf3430ae2009-03-25 21:23:52 +00002112 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002113 if (Inst.isInvalid())
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002114 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002115 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
Jordan Rose1e879d82018-03-23 00:07:18 +00002116 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00002117 "instantiating class definition");
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002118
2119 // Enter the scope of this instantiation. We don't use
2120 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00002121 ContextRAII SavedContext(*this, Instantiation);
Faisal Valid143a0c2017-04-01 21:30:49 +00002122 EnterExpressionEvaluationContext EvalContext(
2123 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002124
Douglas Gregor51121572010-03-24 01:33:17 +00002125 // If this is an instantiation of a local class, merge this local
2126 // instantiation scope with the enclosing scope. Otherwise, every
2127 // instantiation of a class has its own local instantiation scope.
2128 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00002129 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00002130
Volodymyr Sapsai4fbaa622017-09-21 19:54:12 +00002131 // Some class state isn't processed immediately but delayed till class
2132 // instantiation completes. We may not be ready to handle any delayed state
2133 // already on the stack as it might correspond to a different class, so save
2134 // it now and put it back later.
2135 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
Reid Kleckner5b640342016-02-26 19:51:02 +00002136
John McCall6602bb12010-08-01 02:01:53 +00002137 // Pull attributes from the pattern onto the instantiation.
2138 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2139
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002140 // Start the definition of this instantiation.
2141 Instantiation->startDefinition();
Richard Smitha1087602014-03-10 00:04:29 +00002142
2143 // The instantiation is visible here, even if it was first declared in an
2144 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00002145 Instantiation->setVisibleDespiteOwningModule();
Richard Smitha1087602014-03-10 00:04:29 +00002146
2147 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregore9029562010-05-06 00:28:52 +00002148 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002149
John McCall76d824f2009-08-25 22:02:44 +00002150 // Do substitution on the base class specifiers.
2151 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002152 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002153
Douglas Gregor869853e2010-11-10 19:44:59 +00002154 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002155 SmallVector<Decl*, 4> Fields;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002156 // Delay instantiation of late parsed attributes.
2157 LateInstantiatedAttrVec LateAttrs;
2158 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2159
Richard Smith921f1322019-05-13 23:35:21 +00002160 bool MightHaveConstexprVirtualFunctions = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002161 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002162 // Don't instantiate members not belonging in this semantic context.
2163 // e.g. for:
2164 // @code
2165 // template <int i> class A {
2166 // class B *g;
2167 // };
2168 // @endcode
2169 // 'class B' has the template as lexical context but semantically it is
2170 // introduced in namespace scope.
Aaron Ballman629afae2014-03-07 19:56:05 +00002171 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002172 continue;
2173
Erik Pilkingtona3a462e2018-07-23 22:47:37 +00002174 // BlockDecls can appear in a default-member-initializer. They must be the
2175 // child of a BlockExpr, so we only know how to instantiate them from there.
2176 if (isa<BlockDecl>(Member))
2177 continue;
2178
Aaron Ballman629afae2014-03-07 19:56:05 +00002179 if (Member->isInvalidDecl()) {
Richard Smithded9c2e2012-07-11 22:37:56 +00002180 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002181 continue;
2182 }
2183
Aaron Ballman629afae2014-03-07 19:56:05 +00002184 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002185 if (NewMember) {
Richard Smith938f40b2011-06-11 17:19:42 +00002186 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCall48871652010-08-21 09:40:31 +00002187 Fields.push_back(Field);
Richard Smith7d137e32012-03-23 03:33:32 +00002188 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2189 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2190 // specialization causes the implicit instantiation of the definitions
2191 // of unscoped member enumerations.
2192 // Record a point of instantiation for this implicit instantiation.
Richard Smithb66d7772012-03-23 23:09:08 +00002193 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2194 Enum->isCompleteDefinition()) {
Richard Smith7d137e32012-03-23 03:33:32 +00002195 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2196 assert(MSInfo && "no spec info for member enum specialization");
2197 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2198 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2199 }
Richard Smithded9c2e2012-07-11 22:37:56 +00002200 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2201 if (SA->isFailed()) {
2202 // A static_assert failed. Bail out; instantiating this
2203 // class is probably not meaningful.
2204 Instantiation->setInvalidDecl();
2205 break;
2206 }
Richard Smith921f1322019-05-13 23:35:21 +00002207 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
2208 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
2209 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
2210 MightHaveConstexprVirtualFunctions = true;
Richard Smith7d137e32012-03-23 03:33:32 +00002211 }
2212
2213 if (NewMember->isInvalidDecl())
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002214 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002215 } else {
2216 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002217 // instantiations was a semantic disaster, and we'll want to mark the
2218 // declaration invalid.
2219 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002220 }
2221 }
2222
2223 // Finish checking fields.
Craig Topperc3ec1492014-05-26 06:22:03 +00002224 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
Erich Keanec480f302018-07-12 21:09:05 +00002225 SourceLocation(), SourceLocation(), ParsedAttributesView());
Douglas Gregor0be31a22010-07-02 17:43:08 +00002226 CheckCompletedCXXClass(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002227
Reid Kleckner93f661a2015-03-17 21:51:43 +00002228 // Default arguments are parsed, if not instantiated. We can go instantiate
Hans Wennborg92ce2af2019-12-02 16:25:23 +01002229 // default arg exprs for default constructors if necessary now. Unless we're
2230 // parsing a class, in which case wait until that's finished.
2231 if (ParsingClassDepth == 0)
2232 ActOnFinishCXXNonNestedClass();
Reid Kleckner93f661a2015-03-17 21:51:43 +00002233
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002234 // Instantiate late parsed attributes, and attach them to their decls.
2235 // See Sema::InstantiateAttrs
2236 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2237 E = LateAttrs.end(); I != E; ++I) {
2238 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2239 CurrentInstantiationScope = I->Scope;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002240
2241 // Allow 'this' within late-parsed attributes.
2242 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2243 CXXRecordDecl *ThisContext =
2244 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002245 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002246 ND && ND->isCXXInstanceMember());
2247
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002248 Attr *NewAttr =
2249 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2250 I->NewDecl->addAttr(NewAttr);
2251 LocalInstantiationScope::deleteScopes(I->Scope,
2252 Instantiator.getStartingScope());
2253 }
2254 Instantiator.disableLateAttributeInstantiation();
2255 LateAttrs.clear();
2256
Richard Smithd3b5c9082012-07-27 04:22:15 +00002257 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002258
Richard Smitha1087602014-03-10 00:04:29 +00002259 // FIXME: We should do something similar for explicit instantiations so they
2260 // end up in the right module.
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002261 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidise3789482012-02-11 01:59:57 +00002262 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002263 Instantiation->setLocStart(Pattern->getInnerLocStart());
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00002264 Instantiation->setBraceRange(Pattern->getBraceRange());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002265 }
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002266
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002267 if (!Instantiation->isInvalidDecl()) {
John McCalla0a96892012-08-10 03:15:35 +00002268 // Perform any dependent diagnostics from the pattern.
2269 PerformDependentDiagnostics(Pattern, TemplateArgs);
2270
Douglas Gregor869853e2010-11-10 19:44:59 +00002271 // Instantiate any out-of-line class template partial
2272 // specializations now.
Richard Smith10b55fc2013-09-26 03:49:48 +00002273 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregor869853e2010-11-10 19:44:59 +00002274 P = Instantiator.delayed_partial_spec_begin(),
2275 PEnd = Instantiator.delayed_partial_spec_end();
2276 P != PEnd; ++P) {
2277 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smith10b55fc2013-09-26 03:49:48 +00002278 P->first, P->second)) {
2279 Instantiation->setInvalidDecl();
2280 break;
2281 }
2282 }
2283
2284 // Instantiate any out-of-line variable template partial
2285 // specializations now.
2286 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2287 P = Instantiator.delayed_var_partial_spec_begin(),
2288 PEnd = Instantiator.delayed_var_partial_spec_end();
2289 P != PEnd; ++P) {
2290 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2291 P->first, P->second)) {
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002292 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002293 break;
2294 }
2295 }
2296 }
2297
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002298 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00002299 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002300
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002301 if (!Instantiation->isInvalidDecl()) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00002302 Consumer.HandleTagDeclDefinition(Instantiation);
2303
Douglas Gregor88d292c2010-05-13 16:44:06 +00002304 // Always emit the vtable for an explicit instantiation definition
Richard Smith921f1322019-05-13 23:35:21 +00002305 // of a polymorphic class template specialization. Otherwise, eagerly
2306 // instantiate only constexpr virtual functions in preparation for their use
2307 // in constant evaluation.
Douglas Gregor88d292c2010-05-13 16:44:06 +00002308 if (TSK == TSK_ExplicitInstantiationDefinition)
2309 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
Richard Smith921f1322019-05-13 23:35:21 +00002310 else if (MightHaveConstexprVirtualFunctions)
2311 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
2312 /*ConstexprOnly*/ true);
Douglas Gregor88d292c2010-05-13 16:44:06 +00002313 }
2314
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002315 return Instantiation->isInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002316}
2317
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002318/// Instantiate the definition of an enum from a given pattern.
Richard Smith4b38ded2012-03-14 23:13:10 +00002319///
2320/// \param PointOfInstantiation The point of instantiation within the
2321/// source code.
2322/// \param Instantiation is the declaration whose definition is being
2323/// instantiated. This will be a member enumeration of a class
2324/// temploid specialization, or a local enumeration within a
2325/// function temploid specialization.
2326/// \param Pattern The templated declaration from which the instantiation
2327/// occurs.
2328/// \param TemplateArgs The template arguments to be substituted into
2329/// the pattern.
2330/// \param TSK The kind of implicit or explicit instantiation to perform.
2331///
2332/// \return \c true if an error occurred, \c false otherwise.
2333bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2334 EnumDecl *Instantiation, EnumDecl *Pattern,
2335 const MultiLevelTemplateArgumentList &TemplateArgs,
2336 TemplateSpecializationKind TSK) {
2337 EnumDecl *PatternDef = Pattern->getDefinition();
Vassil Vassilevb21ee082016-08-18 22:01:25 +00002338 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00002339 Instantiation->getInstantiatedFromMemberEnum(),
2340 Pattern, PatternDef, TSK,/*Complain*/true))
2341 return true;
2342 Pattern = PatternDef;
2343
2344 // Record the point of instantiation.
2345 if (MemberSpecializationInfo *MSInfo
2346 = Instantiation->getMemberSpecializationInfo()) {
2347 MSInfo->setTemplateSpecializationKind(TSK);
2348 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2349 }
2350
2351 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002352 if (Inst.isInvalid())
Richard Smith4b38ded2012-03-14 23:13:10 +00002353 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002354 if (Inst.isAlreadyInstantiating())
2355 return false;
Jordan Rose1e879d82018-03-23 00:07:18 +00002356 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00002357 "instantiating enum definition");
Richard Smith4b38ded2012-03-14 23:13:10 +00002358
Richard Smitha1087602014-03-10 00:04:29 +00002359 // The instantiation is visible here, even if it was first declared in an
2360 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00002361 Instantiation->setVisibleDespiteOwningModule();
Richard Smitha1087602014-03-10 00:04:29 +00002362
Richard Smith4b38ded2012-03-14 23:13:10 +00002363 // Enter the scope of this instantiation. We don't use
2364 // PushDeclContext because we don't have a scope.
2365 ContextRAII SavedContext(*this, Instantiation);
Faisal Valid143a0c2017-04-01 21:30:49 +00002366 EnterExpressionEvaluationContext EvalContext(
2367 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith4b38ded2012-03-14 23:13:10 +00002368
2369 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2370
2371 // Pull attributes from the pattern onto the instantiation.
2372 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2373
2374 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2375 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2376
2377 // Exit the scope of this instantiation.
2378 SavedContext.pop();
2379
2380 return Instantiation->isInvalidDecl();
2381}
2382
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002383
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002384/// Instantiate the definition of a field from the given pattern.
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002385///
2386/// \param PointOfInstantiation The point of instantiation within the
2387/// source code.
2388/// \param Instantiation is the declaration whose definition is being
2389/// instantiated. This will be a class of a class temploid
2390/// specialization, or a local enumeration within a function temploid
2391/// specialization.
2392/// \param Pattern The templated declaration from which the instantiation
2393/// occurs.
2394/// \param TemplateArgs The template arguments to be substituted into
2395/// the pattern.
2396///
2397/// \return \c true if an error occurred, \c false otherwise.
2398bool Sema::InstantiateInClassInitializer(
2399 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2400 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2401 // If there is no initializer, we don't need to do anything.
2402 if (!Pattern->hasInClassInitializer())
2403 return false;
2404
2405 assert(Instantiation->getInClassInitStyle() ==
2406 Pattern->getInClassInitStyle() &&
2407 "pattern and instantiation disagree about init style");
2408
2409 // Error out if we haven't parsed the initializer of the pattern yet because
2410 // we are waiting for the closing brace of the outer class.
2411 Expr *OldInit = Pattern->getInClassInitializer();
2412 if (!OldInit) {
2413 RecordDecl *PatternRD = Pattern->getParent();
2414 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
Richard Smith8dbc6b22016-11-22 22:55:12 +00002415 Diag(PointOfInstantiation,
2416 diag::err_in_class_initializer_not_yet_parsed)
2417 << OutermostClass << Pattern;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002418 Diag(Pattern->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002419 Instantiation->setInvalidDecl();
2420 return true;
2421 }
2422
2423 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2424 if (Inst.isInvalid())
2425 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002426 if (Inst.isAlreadyInstantiating()) {
2427 // Error out if we hit an instantiation cycle for this initializer.
2428 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2429 << Instantiation;
2430 return true;
2431 }
Jordan Rose1e879d82018-03-23 00:07:18 +00002432 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00002433 "instantiating default member init");
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002434
2435 // Enter the scope of this instantiation. We don't use PushDeclContext because
2436 // we don't have a scope.
2437 ContextRAII SavedContext(*this, Instantiation->getParent());
Faisal Valid143a0c2017-04-01 21:30:49 +00002438 EnterExpressionEvaluationContext EvalContext(
2439 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002440
Serge Pavlov907233f2015-04-28 17:58:47 +00002441 LocalInstantiationScope Scope(*this, true);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002442
2443 // Instantiate the initializer.
2444 ActOnStartCXXInClassMemberInitializer();
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002445 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002446
2447 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2448 /*CXXDirectInit=*/false);
2449 Expr *Init = NewInit.get();
2450 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2451 ActOnFinishCXXInClassMemberInitializer(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002452 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002453
Richard Smith4b054b22016-08-24 21:25:37 +00002454 if (auto *L = getASTMutationListener())
2455 L->DefaultMemberInitializerInstantiated(Instantiation);
2456
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002457 // Return true if the in-class initializer is still missing.
2458 return !Instantiation->getInClassInitializer();
2459}
2460
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002461namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002462 /// A partial specialization whose template arguments have matched
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002463 /// a given template-id.
2464 struct PartialSpecMatchResult {
2465 ClassTemplatePartialSpecializationDecl *Partial;
2466 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002467 };
2468}
2469
Richard Smithe6d4b772017-06-07 02:42:27 +00002470bool Sema::usesPartialOrExplicitSpecialization(
2471 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
2472 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
2473 TSK_ExplicitSpecialization)
2474 return true;
2475
2476 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2477 ClassTemplateSpec->getSpecializedTemplate()
2478 ->getPartialSpecializations(PartialSpecs);
2479 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2480 TemplateDeductionInfo Info(Loc);
2481 if (!DeduceTemplateArguments(PartialSpecs[I],
2482 ClassTemplateSpec->getTemplateArgs(), Info))
2483 return true;
2484 }
2485
2486 return false;
2487}
2488
Richard Smith32b43762017-01-08 22:45:21 +00002489/// Get the instantiation pattern to use to instantiate the definition of a
2490/// given ClassTemplateSpecializationDecl (either the pattern of the primary
2491/// template or of a partial specialization).
2492static CXXRecordDecl *
2493getPatternForClassTemplateSpecialization(
2494 Sema &S, SourceLocation PointOfInstantiation,
Larisse Voufo72caf2b2013-08-22 00:59:14 +00002495 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2496 TemplateSpecializationKind TSK, bool Complain) {
Richard Smith32b43762017-01-08 22:45:21 +00002497 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2498 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
2499 return nullptr;
2500
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002501 llvm::PointerUnion<ClassTemplateDecl *,
2502 ClassTemplatePartialSpecializationDecl *>
2503 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2504 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
2505 // Find best matching specialization.
2506 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregor2373c592009-05-31 09:31:02 +00002507
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002508 // C++ [temp.class.spec.match]p1:
2509 // When a class template is used in a context that requires an
2510 // instantiation of the class, it is necessary to determine
2511 // whether the instantiation is to be generated using the primary
2512 // template or one of the partial specializations. This is done by
2513 // matching the template arguments of the class template
2514 // specialization with the template argument lists of the partial
2515 // specializations.
2516 typedef PartialSpecMatchResult MatchResult;
2517 SmallVector<MatchResult, 4> Matched;
2518 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2519 Template->getPartialSpecializations(PartialSpecs);
2520 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2521 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2522 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2523 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2524 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
2525 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
2526 // Store the failed-deduction information for use in diagnostics, later.
2527 // TODO: Actually use the failed-deduction info?
2528 FailedCandidates.addCandidate().set(
2529 DeclAccessPair::make(Template, AS_public), Partial,
2530 MakeDeductionFailureInfo(S.Context, Result, Info));
2531 (void)Result;
2532 } else {
2533 Matched.push_back(PartialSpecMatchResult());
2534 Matched.back().Partial = Partial;
2535 Matched.back().Args = Info.take();
2536 }
2537 }
2538
2539 // If we're dealing with a member template where the template parameters
2540 // have been instantiated, this provides the original template parameters
2541 // from which the member template's parameters were instantiated.
2542
2543 if (Matched.size() >= 1) {
2544 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
2545 if (Matched.size() == 1) {
2546 // -- If exactly one matching specialization is found, the
2547 // instantiation is generated from that specialization.
2548 // We don't need to do anything for this.
2549 } else {
2550 // -- If more than one matching specialization is found, the
2551 // partial order rules (14.5.4.2) are used to determine
2552 // whether one of the specializations is more specialized
2553 // than the others. If none of the specializations is more
2554 // specialized than all of the other matching
2555 // specializations, then the use of the class template is
2556 // ambiguous and the program is ill-formed.
2557 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2558 PEnd = Matched.end();
2559 P != PEnd; ++P) {
2560 if (S.getMoreSpecializedPartialSpecialization(
2561 P->Partial, Best->Partial, PointOfInstantiation) ==
2562 P->Partial)
2563 Best = P;
2564 }
2565
2566 // Determine if the best partial specialization is more specialized than
2567 // the others.
2568 bool Ambiguous = false;
2569 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2570 PEnd = Matched.end();
2571 P != PEnd; ++P) {
2572 if (P != Best && S.getMoreSpecializedPartialSpecialization(
2573 P->Partial, Best->Partial,
2574 PointOfInstantiation) != Best->Partial) {
2575 Ambiguous = true;
2576 break;
2577 }
2578 }
2579
2580 if (Ambiguous) {
2581 // Partial ordering did not produce a clear winner. Complain.
2582 Inst.Clear();
2583 ClassTemplateSpec->setInvalidDecl();
2584 S.Diag(PointOfInstantiation,
2585 diag::err_partial_spec_ordering_ambiguous)
2586 << ClassTemplateSpec;
2587
2588 // Print the matching partial specializations.
2589 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2590 PEnd = Matched.end();
2591 P != PEnd; ++P)
2592 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2593 << S.getTemplateArgumentBindingsText(
2594 P->Partial->getTemplateParameters(), *P->Args);
2595
2596 return nullptr;
2597 }
2598 }
2599
2600 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002601 } else {
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002602 // -- If no matches are found, the instantiation is generated
2603 // from the primary template.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002604 }
Douglas Gregor2373c592009-05-31 09:31:02 +00002605 }
2606
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002607 CXXRecordDecl *Pattern = nullptr;
2608 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2609 if (auto *PartialSpec =
2610 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
Douglas Gregorbe999392009-09-15 16:23:51 +00002611 // Instantiate using the best class template partial specialization.
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002612 while (PartialSpec->getInstantiatedFromMember()) {
Douglas Gregor21610382009-10-29 00:04:11 +00002613 // If we've found an explicit specialization of this class template,
2614 // stop here and use that as the pattern.
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002615 if (PartialSpec->isMemberSpecialization())
Douglas Gregor21610382009-10-29 00:04:11 +00002616 break;
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002617
2618 PartialSpec = PartialSpec->getInstantiatedFromMember();
Douglas Gregor21610382009-10-29 00:04:11 +00002619 }
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002620 Pattern = PartialSpec;
Douglas Gregor170bc422009-06-12 22:31:52 +00002621 } else {
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002622 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2623 while (Template->getInstantiatedFromMemberTemplate()) {
Douglas Gregorcf915552009-10-13 16:30:37 +00002624 // If we've found an explicit specialization of this class template,
2625 // stop here and use that as the pattern.
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002626 if (Template->isMemberSpecialization())
Douglas Gregorcf915552009-10-13 16:30:37 +00002627 break;
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002628
2629 Template = Template->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00002630 }
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002631 Pattern = Template->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00002632 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002633
Richard Smith32b43762017-01-08 22:45:21 +00002634 return Pattern;
2635}
Mike Stump11289f42009-09-09 15:08:12 +00002636
Richard Smith32b43762017-01-08 22:45:21 +00002637bool Sema::InstantiateClassTemplateSpecialization(
2638 SourceLocation PointOfInstantiation,
2639 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2640 TemplateSpecializationKind TSK, bool Complain) {
2641 // Perform the actual instantiation on the canonical declaration.
2642 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2643 ClassTemplateSpec->getCanonicalDecl());
2644 if (ClassTemplateSpec->isInvalidDecl())
2645 return true;
2646
2647 CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization(
2648 *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
2649 if (!Pattern)
2650 return true;
2651
2652 return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
2653 getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
2654 Complain);
Douglas Gregor463421d2009-03-03 04:44:36 +00002655}
Douglas Gregor90a1a652009-03-19 17:26:29 +00002656
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002657/// Instantiates the definitions of all of the member
John McCall76d824f2009-08-25 22:02:44 +00002658/// of the given class, which is an instantiation of a class template
2659/// or a member class of a template.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002660void
2661Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002662 CXXRecordDecl *Instantiation,
2663 const MultiLevelTemplateArgumentList &TemplateArgs,
2664 TemplateSpecializationKind TSK) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00002665 // FIXME: We need to notify the ASTMutationListener that we did all of these
2666 // things, in case we have an explicit instantiation definition in a PCM, a
2667 // module, or preamble, and the declaration is in an imported AST.
David Majnemer192d1792013-11-27 08:20:38 +00002668 assert(
2669 (TSK == TSK_ExplicitInstantiationDefinition ||
2670 TSK == TSK_ExplicitInstantiationDeclaration ||
2671 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2672 "Unexpected template specialization kind!");
Aaron Ballman629afae2014-03-07 19:56:05 +00002673 for (auto *D : Instantiation->decls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002674 bool SuppressNew = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002675 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Louis Dionned2695792018-10-04 15:49:42 +00002676 if (FunctionDecl *Pattern =
2677 Function->getInstantiatedFromMemberFunction()) {
2678
2679 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2680 continue;
2681
2682 MemberSpecializationInfo *MSInfo =
2683 Function->getMemberSpecializationInfo();
Douglas Gregor1d957a32009-10-27 18:42:08 +00002684 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002685 if (MSInfo->getTemplateSpecializationKind()
2686 == TSK_ExplicitSpecialization)
2687 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002688
2689 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2690 Function,
Douglas Gregor1d957a32009-10-27 18:42:08 +00002691 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002692 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002693 SuppressNew) ||
2694 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002695 continue;
Richard Smitheb36ddf2014-04-24 22:45:46 +00002696
2697 // C++11 [temp.explicit]p8:
2698 // An explicit instantiation definition that names a class template
2699 // specialization explicitly instantiates the class template
2700 // specialization and is only an explicit instantiation definition
2701 // of members whose definition is visible at the point of
2702 // instantiation.
2703 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002704 continue;
2705
Richard Smitheb36ddf2014-04-24 22:45:46 +00002706 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2707
2708 if (Function->isDefined()) {
2709 // Let the ASTConsumer know that this function has been explicitly
2710 // instantiated now, and its linkage might have changed.
2711 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2712 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002713 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Richard Smitheb36ddf2014-04-24 22:45:46 +00002714 } else if (TSK == TSK_ImplicitInstantiation) {
2715 PendingLocalImplicitInstantiations.push_back(
2716 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor1d957a32009-10-27 18:42:08 +00002717 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002718 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002719 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002720 if (isa<VarTemplateSpecializationDecl>(Var))
2721 continue;
2722
Douglas Gregor86d142a2009-10-08 07:24:58 +00002723 if (Var->isStaticDataMember()) {
Louis Dionned2695792018-10-04 15:49:42 +00002724 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2725 continue;
2726
Douglas Gregor1d957a32009-10-27 18:42:08 +00002727 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2728 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002729 if (MSInfo->getTemplateSpecializationKind()
2730 == TSK_ExplicitSpecialization)
2731 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002732
2733 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2734 Var,
Douglas Gregor1d957a32009-10-27 18:42:08 +00002735 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002736 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002737 SuppressNew) ||
2738 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002739 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002740
Douglas Gregor1d957a32009-10-27 18:42:08 +00002741 if (TSK == TSK_ExplicitInstantiationDefinition) {
2742 // C++0x [temp.explicit]p8:
2743 // An explicit instantiation definition that names a class template
Fangrui Song6907ce22018-07-30 19:24:48 +00002744 // specialization explicitly instantiates the class template
2745 // specialization and is only an explicit instantiation definition
2746 // of members whose definition is visible at the point of
Douglas Gregor1d957a32009-10-27 18:42:08 +00002747 // instantiation.
Richard Smith62f19e72016-06-25 00:15:56 +00002748 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002749 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002750
Douglas Gregor1d957a32009-10-27 18:42:08 +00002751 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00002752 InstantiateVariableDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00002753 } else {
2754 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2755 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002756 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002757 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Louis Dionned2695792018-10-04 15:49:42 +00002758 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2759 continue;
2760
Douglas Gregor1da22252010-04-18 18:11:38 +00002761 // Always skip the injected-class-name, along with any
2762 // redeclarations of nested classes, since both would cause us
2763 // to try to instantiate the members of a class twice.
Richard Smith069ecf62014-11-20 22:56:34 +00002764 // Skip closure types; they'll get instantiated when we instantiate
2765 // the corresponding lambda-expression.
2766 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2767 Record->isLambda())
Douglas Gregord801b062009-10-07 23:56:10 +00002768 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002769
Douglas Gregor1d957a32009-10-27 18:42:08 +00002770 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2771 assert(MSInfo && "No member specialization information?");
Fangrui Song6907ce22018-07-30 19:24:48 +00002772
Douglas Gregor06aa50412010-04-09 21:02:29 +00002773 if (MSInfo->getTemplateSpecializationKind()
2774 == TSK_ExplicitSpecialization)
2775 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00002776
Reid Kleckner5f789ba2019-04-29 21:32:05 +00002777 if (Context.getTargetInfo().getTriple().isOSWindows() &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00002778 TSK == TSK_ExplicitInstantiationDeclaration) {
Reid Kleckner5f789ba2019-04-29 21:32:05 +00002779 // On Windows, explicit instantiation decl of the outer class doesn't
2780 // affect the inner class. Typically extern template declarations are
2781 // used in combination with dll import/export annotations, but those
2782 // are not propagated from the outer class templates to inner classes.
2783 // Therefore, do not instantiate inner classes on this platform, so
2784 // that users don't end up with undefined symbols during linking.
Hans Wennborga86a83b2016-05-26 19:42:56 +00002785 continue;
2786 }
2787
Fangrui Song6907ce22018-07-30 19:24:48 +00002788 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2789 Record,
Douglas Gregor1d957a32009-10-27 18:42:08 +00002790 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002791 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002792 SuppressNew) ||
2793 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002794 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002795
Douglas Gregor1d957a32009-10-27 18:42:08 +00002796 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2797 assert(Pattern && "Missing instantiated-from-template information");
Fangrui Song6907ce22018-07-30 19:24:48 +00002798
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002799 if (!Record->getDefinition()) {
2800 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002801 // C++0x [temp.explicit]p8:
2802 // An explicit instantiation definition that names a class template
Fangrui Song6907ce22018-07-30 19:24:48 +00002803 // specialization explicitly instantiates the class template
2804 // specialization and is only an explicit instantiation definition
2805 // of members whose definition is visible at the point of
Douglas Gregor1d957a32009-10-27 18:42:08 +00002806 // instantiation.
2807 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2808 MSInfo->setTemplateSpecializationKind(TSK);
2809 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2810 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002811
Douglas Gregor1d957a32009-10-27 18:42:08 +00002812 continue;
2813 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002814
Douglas Gregor1d957a32009-10-27 18:42:08 +00002815 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002816 TemplateArgs,
2817 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002818 } else {
2819 if (TSK == TSK_ExplicitInstantiationDefinition &&
2820 Record->getTemplateSpecializationKind() ==
2821 TSK_ExplicitInstantiationDeclaration) {
2822 Record->setTemplateSpecializationKind(TSK);
2823 MarkVTableUsed(PointOfInstantiation, Record, true);
2824 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002825 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002826
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002827 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002828 if (Pattern)
Fangrui Song6907ce22018-07-30 19:24:48 +00002829 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
Douglas Gregor1d957a32009-10-27 18:42:08 +00002830 TSK);
Aaron Ballman629afae2014-03-07 19:56:05 +00002831 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smith4b38ded2012-03-14 23:13:10 +00002832 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2833 assert(MSInfo && "No member specialization information?");
2834
2835 if (MSInfo->getTemplateSpecializationKind()
2836 == TSK_ExplicitSpecialization)
2837 continue;
2838
2839 if (CheckSpecializationInstantiationRedecl(
2840 PointOfInstantiation, TSK, Enum,
2841 MSInfo->getTemplateSpecializationKind(),
2842 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2843 SuppressNew)
2844 continue;
2845
2846 if (Enum->getDefinition())
2847 continue;
2848
Richard Smith6739a102016-05-05 00:56:12 +00002849 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
Richard Smith4b38ded2012-03-14 23:13:10 +00002850 assert(Pattern && "Missing instantiated-from-template information");
2851
2852 if (TSK == TSK_ExplicitInstantiationDefinition) {
2853 if (!Pattern->getDefinition())
2854 continue;
2855
2856 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2857 } else {
2858 MSInfo->setTemplateSpecializationKind(TSK);
2859 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2860 }
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002861 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2862 // No need to instantiate in-class initializers during explicit
2863 // instantiation.
2864 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2865 CXXRecordDecl *ClassPattern =
2866 Instantiation->getTemplateInstantiationPattern();
2867 DeclContext::lookup_result Lookup =
2868 ClassPattern->lookup(Field->getDeclName());
David Majnemer76a25622016-06-09 05:26:56 +00002869 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002870 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2871 TemplateArgs);
2872 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002873 }
2874 }
2875}
2876
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002877/// Instantiate the definitions of all of the members of the
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002878/// given class template specialization, which was named as part of an
2879/// explicit instantiation.
Mike Stump11289f42009-09-09 15:08:12 +00002880void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002881Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002882 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002883 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2884 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002885 // C++0x [temp.explicit]p7:
2886 // An explicit instantiation that names a class template
2887 // specialization is an explicit instantion of the same kind
2888 // (declaration or definition) of each of its members (not
2889 // including members inherited from base classes) that has not
2890 // been previously explicitly specialized in the translation unit
2891 // containing the explicit instantiation, except as described
2892 // below.
2893 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002894 getTemplateInstantiationArgs(ClassTemplateSpec),
2895 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002896}
2897
John McCalldadc5752010-08-24 06:29:42 +00002898StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002899Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002900 if (!S)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002901 return S;
Douglas Gregorebe10102009-08-20 07:17:43 +00002902
2903 TemplateInstantiator Instantiator(*this, TemplateArgs,
2904 SourceLocation(),
2905 DeclarationName());
2906 return Instantiator.TransformStmt(S);
2907}
2908
John McCalldadc5752010-08-24 06:29:42 +00002909ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002910Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002911 if (!E)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002912 return E;
Mike Stump11289f42009-09-09 15:08:12 +00002913
Douglas Gregora16548e2009-08-11 05:31:07 +00002914 TemplateInstantiator Instantiator(*this, TemplateArgs,
2915 SourceLocation(),
2916 DeclarationName());
2917 return Instantiator.TransformExpr(E);
2918}
2919
Richard Smithd59b8322012-12-19 01:39:02 +00002920ExprResult Sema::SubstInitializer(Expr *Init,
2921 const MultiLevelTemplateArgumentList &TemplateArgs,
2922 bool CXXDirectInit) {
2923 TemplateInstantiator Instantiator(*this, TemplateArgs,
2924 SourceLocation(),
2925 DeclarationName());
2926 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2927}
2928
Craig Topper99d23532015-12-24 23:58:29 +00002929bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002930 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002931 SmallVectorImpl<Expr *> &Outputs) {
Craig Topper99d23532015-12-24 23:58:29 +00002932 if (Exprs.empty())
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002933 return false;
Richard Smithd59b8322012-12-19 01:39:02 +00002934
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002935 TemplateInstantiator Instantiator(*this, TemplateArgs,
2936 SourceLocation(),
2937 DeclarationName());
Craig Topper99d23532015-12-24 23:58:29 +00002938 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2939 IsCall, Outputs);
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002940}
2941
Douglas Gregor14454802011-02-25 02:25:35 +00002942NestedNameSpecifierLoc
2943Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
Fangrui Song6907ce22018-07-30 19:24:48 +00002944 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor14454802011-02-25 02:25:35 +00002945 if (!NNS)
2946 return NestedNameSpecifierLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002947
Douglas Gregor14454802011-02-25 02:25:35 +00002948 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2949 DeclarationName());
2950 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2951}
2952
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002953/// Do template substitution on declaration name info.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002954DeclarationNameInfo
2955Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2956 const MultiLevelTemplateArgumentList &TemplateArgs) {
2957 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2958 NameInfo.getName());
2959 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2960}
2961
Douglas Gregoraa594892009-03-31 18:38:02 +00002962TemplateName
Douglas Gregordf846d12011-03-02 18:46:51 +00002963Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2964 TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002965 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002966 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2967 DeclarationName());
Douglas Gregordf846d12011-03-02 18:46:51 +00002968 CXXScopeSpec SS;
2969 SS.Adopt(QualifierLoc);
2970 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregoraa594892009-03-31 18:38:02 +00002971}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002972
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002973bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2974 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002975 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002976 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2977 DeclarationName());
Fangrui Song6907ce22018-07-30 19:24:48 +00002978
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002979 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00002980}
Douglas Gregor14cf7522010-04-30 18:55:50 +00002981
Richard Smith70b13042015-01-09 01:19:56 +00002982static const Decl *getCanonicalParmVarDecl(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002983 // When storing ParmVarDecls in the local instantiation scope, we always
2984 // want to use the ParmVarDecl from the canonical function declaration,
2985 // since the map is then valid for any redeclaration or definition of that
2986 // function.
2987 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2988 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2989 unsigned i = PV->getFunctionScopeIndex();
Richard Smith70b13042015-01-09 01:19:56 +00002990 // This parameter might be from a freestanding function type within the
2991 // function and isn't necessarily referring to one of FD's parameters.
Dmitri Gribenko66b6bb12019-04-10 20:25:07 +00002992 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
Richard Smith70b13042015-01-09 01:19:56 +00002993 return FD->getCanonicalDecl()->getParamDecl(i);
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002994 }
2995 }
2996 return D;
2997}
2998
2999
Douglas Gregorf3010112011-01-07 16:43:16 +00003000llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
3001LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00003002 D = getCanonicalParmVarDecl(D);
Chris Lattnercab02a62011-02-17 20:34:02 +00003003 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor14cf7522010-04-30 18:55:50 +00003004 Current = Current->Outer) {
Chris Lattnercab02a62011-02-17 20:34:02 +00003005
Douglas Gregor14cf7522010-04-30 18:55:50 +00003006 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00003007 const Decl *CheckD = D;
3008 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00003009 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00003010 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00003011 return &Found->second;
Fangrui Song6907ce22018-07-30 19:24:48 +00003012
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00003013 // If this is a tag declaration, it's possible that we need to look for
3014 // a previous declaration.
3015 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregorec9fd132012-01-14 16:38:05 +00003016 CheckD = Tag->getPreviousDecl();
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00003017 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003018 CheckD = nullptr;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00003019 } while (CheckD);
Fangrui Song6907ce22018-07-30 19:24:48 +00003020
3021 // If we aren't combined with our outer scope, we're done.
Douglas Gregor14cf7522010-04-30 18:55:50 +00003022 if (!Current->CombineWithOuterScope)
3023 break;
3024 }
Chris Lattnercab02a62011-02-17 20:34:02 +00003025
Serge Pavlov7cd8f602013-07-15 06:14:07 +00003026 // If we're performing a partial substitution during template argument
3027 // deduction, we may not have values for template parameters yet.
3028 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
3029 isa<TemplateTemplateParmDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00003030 return nullptr;
Serge Pavlov7cd8f602013-07-15 06:14:07 +00003031
Serge Pavlove7ad8312015-05-15 10:10:28 +00003032 // Local types referenced prior to definition may require instantiation.
3033 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
3034 if (RD->isLocalClass())
3035 return nullptr;
3036
3037 // Enumeration types referenced prior to definition may appear as a result of
3038 // error recovery.
3039 if (isa<EnumDecl>(D))
Serge Pavlov4c511742015-05-04 16:44:39 +00003040 return nullptr;
3041
Chris Lattnercab02a62011-02-17 20:34:02 +00003042 // If we didn't find the decl, then we either have a sema bug, or we have a
3043 // forward reference to a label declaration. Return null to indicate that
3044 // we have an uninstantiated label.
3045 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Craig Topperc3ec1492014-05-26 06:22:03 +00003046 return nullptr;
Douglas Gregor14cf7522010-04-30 18:55:50 +00003047}
3048
John McCall19c1bfd2010-08-25 05:32:35 +00003049void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00003050 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00003051 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Richard Smith70b13042015-01-09 01:19:56 +00003052 if (Stored.isNull()) {
3053#ifndef NDEBUG
3054 // It should not be present in any surrounding scope either.
3055 LocalInstantiationScope *Current = this;
3056 while (Current->CombineWithOuterScope && Current->Outer) {
3057 Current = Current->Outer;
3058 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3059 "Instantiated local in inner and outer scopes");
3060 }
3061#endif
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003062 Stored = Inst;
Richard Smith70b13042015-01-09 01:19:56 +00003063 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
Richard Smithb2997f52019-05-21 20:10:50 +00003064 Pack->push_back(cast<VarDecl>(Inst));
Richard Smith70b13042015-01-09 01:19:56 +00003065 } else {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003066 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Richard Smith70b13042015-01-09 01:19:56 +00003067 }
Douglas Gregor14cf7522010-04-30 18:55:50 +00003068}
Douglas Gregorf3010112011-01-07 16:43:16 +00003069
James Y Knight48fefa32015-09-30 14:04:23 +00003070void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
Richard Smithb2997f52019-05-21 20:10:50 +00003071 VarDecl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00003072 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00003073 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
3074 Pack->push_back(Inst);
3075}
3076
3077void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
Richard Smith70b13042015-01-09 01:19:56 +00003078#ifndef NDEBUG
3079 // This should be the first time we've been told about this decl.
3080 for (LocalInstantiationScope *Current = this;
3081 Current && Current->CombineWithOuterScope; Current = Current->Outer)
3082 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3083 "Creating local pack after instantiation of local");
3084#endif
3085
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00003086 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00003087 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregorf3010112011-01-07 16:43:16 +00003088 DeclArgumentPack *Pack = new DeclArgumentPack;
3089 Stored = Pack;
3090 ArgumentPacks.push_back(Pack);
3091}
3092
Fangrui Song6907ce22018-07-30 19:24:48 +00003093void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003094 const TemplateArgument *ExplicitArgs,
3095 unsigned NumExplicitArgs) {
3096 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
3097 "Already have a partially-substituted pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00003098 assert((!PartiallySubstitutedPack
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003099 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
3100 "Wrong number of arguments in partially-substituted pack");
3101 PartiallySubstitutedPack = Pack;
3102 ArgsInPartiallySubstitutedPack = ExplicitArgs;
3103 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
3104}
3105
3106NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
3107 const TemplateArgument **ExplicitArgs,
3108 unsigned *NumExplicitArgs) const {
3109 if (ExplicitArgs)
Craig Topperc3ec1492014-05-26 06:22:03 +00003110 *ExplicitArgs = nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003111 if (NumExplicitArgs)
3112 *NumExplicitArgs = 0;
Fangrui Song6907ce22018-07-30 19:24:48 +00003113
3114 for (const LocalInstantiationScope *Current = this; Current;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003115 Current = Current->Outer) {
3116 if (Current->PartiallySubstitutedPack) {
3117 if (ExplicitArgs)
3118 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
3119 if (NumExplicitArgs)
3120 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
Fangrui Song6907ce22018-07-30 19:24:48 +00003121
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003122 return Current->PartiallySubstitutedPack;
3123 }
3124
3125 if (!Current->CombineWithOuterScope)
3126 break;
3127 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003128
3129 return nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003130}