blob: 7b09b77da326e1df4c47f076833dd2e1074802c8 [file] [log] [blame]
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation.
10//
11//===----------------------------------------------------------------------===/
12
John McCall83024632010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregord6ff3322009-08-04 16:50:30 +000014#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
Faisal Vali2cba1332013-10-23 06:44:28 +000017#include "clang/AST/ASTLambda.h"
Richard Smith4b054b22016-08-24 21:25:37 +000018#include "clang/AST/ASTMutationListener.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/Basic/LangOptions.h"
John McCall8b0666c2010-08-20 18:27:03 +000022#include "clang/Sema/DeclSpec.h"
Richard Smith938f40b2011-06-11 17:19:42 +000023#include "clang/Sema/Initialization.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000024#include "clang/Sema/Lookup.h"
Richard Smithe19b95d2016-05-26 20:23:13 +000025#include "clang/Sema/PrettyDeclStackTrace.h"
John McCallde6836a2010-08-24 07:21:54 +000026#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000027#include "clang/Sema/TemplateDeduction.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000028
29using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000030using namespace sema;
Douglas Gregorfe1e1102009-02-27 19:31:52 +000031
Douglas Gregor4ea568f2009-03-10 18:03:33 +000032//===----------------------------------------------------------------------===/
33// Template Instantiation Support
34//===----------------------------------------------------------------------===/
35
Douglas Gregor01afeef2009-08-28 20:31:08 +000036/// \brief Retrieve the template argument list(s) that should be used to
37/// instantiate the definition of the given declaration.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000038///
39/// \param D the declaration for which we are computing template instantiation
40/// arguments.
41///
42/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor8c702532010-02-05 07:33:43 +000043///
44/// \param RelativeToPrimary true if we should get the template
45/// arguments relative to the primary template, even when we're
46/// dealing with a specialization. This is only relevant for function
47/// template specializations.
Douglas Gregor1bd7a942010-05-03 23:29:10 +000048///
49/// \param Pattern If non-NULL, indicates the pattern from which we will be
50/// instantiating the definition of the given declaration, \p D. This is
51/// used to determine the proper set of template instantiation arguments for
52/// friend function template specializations.
Douglas Gregora654dd82009-08-28 17:37:35 +000053MultiLevelTemplateArgumentList
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000054Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor8c702532010-02-05 07:33:43 +000055 const TemplateArgumentList *Innermost,
Douglas Gregor1bd7a942010-05-03 23:29:10 +000056 bool RelativeToPrimary,
57 const FunctionDecl *Pattern) {
Douglas Gregora654dd82009-08-28 17:37:35 +000058 // Accumulate the set of template argument lists in this structure.
59 MultiLevelTemplateArgumentList Result;
Mike Stump11289f42009-09-09 15:08:12 +000060
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000061 if (Innermost)
62 Result.addOuterTemplateArguments(Innermost);
63
Douglas Gregora654dd82009-08-28 17:37:35 +000064 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregora51c9cc2011-05-22 00:21:10 +000065 if (!Ctx) {
Douglas Gregora654dd82009-08-28 17:37:35 +000066 Ctx = D->getDeclContext();
Larisse Voufo39a1e502013-08-06 01:03:05 +000067
68 // Add template arguments from a variable template instantiation.
69 if (VarTemplateSpecializationDecl *Spec =
70 dyn_cast<VarTemplateSpecializationDecl>(D)) {
71 // We're done when we hit an explicit specialization.
72 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
73 !isa<VarTemplatePartialSpecializationDecl>(Spec))
74 return Result;
75
76 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
77
78 // If this variable template specialization was instantiated from a
79 // specialized member that is a variable template, we're done.
80 assert(Spec->getSpecializedTemplate() && "No variable template?");
Richard Smithbeef3452014-01-16 23:39:20 +000081 llvm::PointerUnion<VarTemplateDecl*,
82 VarTemplatePartialSpecializationDecl*> Specialized
83 = Spec->getSpecializedTemplateOrPartial();
84 if (VarTemplatePartialSpecializationDecl *Partial =
85 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
86 if (Partial->isMemberSpecialization())
87 return Result;
88 } else {
89 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
90 if (Tmpl->isMemberSpecialization())
91 return Result;
92 }
Larisse Voufo39a1e502013-08-06 01:03:05 +000093 }
94
Douglas Gregor55462622011-06-15 14:20:42 +000095 // If we have a template template parameter with translation unit context,
96 // then we're performing substitution into a default template argument of
97 // this template template parameter before we've constructed the template
98 // that will own this template template parameter. In this case, we
99 // use empty template parameter lists for all of the outer templates
100 // to avoid performing any substitutions.
101 if (Ctx->isTranslationUnit()) {
102 if (TemplateTemplateParmDecl *TTP
103 = dyn_cast<TemplateTemplateParmDecl>(D)) {
104 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +0000105 Result.addOuterTemplateArguments(None);
Douglas Gregor55462622011-06-15 14:20:42 +0000106 return Result;
107 }
108 }
Douglas Gregora51c9cc2011-05-22 00:21:10 +0000109 }
110
John McCall970d5302009-08-29 03:16:09 +0000111 while (!Ctx->isFileContext()) {
Douglas Gregora654dd82009-08-28 17:37:35 +0000112 // Add template arguments from a class template instantiation.
Mike Stump11289f42009-09-09 15:08:12 +0000113 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregora654dd82009-08-28 17:37:35 +0000114 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
115 // We're done when we hit an explicit specialization.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000116 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
117 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregora654dd82009-08-28 17:37:35 +0000118 break;
Mike Stump11289f42009-09-09 15:08:12 +0000119
Douglas Gregora654dd82009-08-28 17:37:35 +0000120 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000121
122 // If this class template specialization was instantiated from a
123 // specialized member that is a class template, we're done.
124 assert(Spec->getSpecializedTemplate() && "No class template?");
125 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
126 break;
Mike Stump11289f42009-09-09 15:08:12 +0000127 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000128 // Add template arguments from a function template specialization.
John McCall970d5302009-08-29 03:16:09 +0000129 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor8c702532010-02-05 07:33:43 +0000130 if (!RelativeToPrimary &&
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000131 (Function->getTemplateSpecializationKind() ==
132 TSK_ExplicitSpecialization &&
133 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorcf915552009-10-13 16:30:37 +0000134 break;
135
Douglas Gregora654dd82009-08-28 17:37:35 +0000136 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorcf915552009-10-13 16:30:37 +0000137 = Function->getTemplateSpecializationArgs()) {
138 // Add the template arguments for this specialization.
Douglas Gregora654dd82009-08-28 17:37:35 +0000139 Result.addOuterTemplateArguments(TemplateArgs);
John McCall970d5302009-08-29 03:16:09 +0000140
Douglas Gregorcf915552009-10-13 16:30:37 +0000141 // If this function was instantiated from a specialized member that is
142 // a function template, we're done.
143 assert(Function->getPrimaryTemplate() && "No function template?");
144 if (Function->getPrimaryTemplate()->isMemberSpecialization())
145 break;
Faisal Vali2cba1332013-10-23 06:44:28 +0000146
147 // If this function is a generic lambda specialization, we are done.
148 if (isGenericLambdaCallOperatorSpecialization(Function))
149 break;
150
Douglas Gregor43669f82011-03-05 17:54:25 +0000151 } else if (FunctionTemplateDecl *FunTmpl
152 = Function->getDescribedFunctionTemplate()) {
153 // Add the "injected" template arguments.
Richard Smith841d8b22013-05-17 03:04:50 +0000154 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000155 }
156
John McCall970d5302009-08-29 03:16:09 +0000157 // If this is a friend declaration and it declares an entity at
158 // namespace scope, take arguments from its lexical parent
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000159 // instead of its semantic parent, unless of course the pattern we're
160 // instantiating actually comes from the file's context!
John McCall970d5302009-08-29 03:16:09 +0000161 if (Function->getFriendObjectKind() &&
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000162 Function->getDeclContext()->isFileContext() &&
163 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCall970d5302009-08-29 03:16:09 +0000164 Ctx = Function->getLexicalDeclContext();
Douglas Gregor8c702532010-02-05 07:33:43 +0000165 RelativeToPrimary = false;
John McCall970d5302009-08-29 03:16:09 +0000166 continue;
167 }
Douglas Gregor9961ce92010-07-08 18:37:38 +0000168 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
169 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
170 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith841d8b22013-05-17 03:04:50 +0000171 const TemplateSpecializationType *TST =
172 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
173 Result.addOuterTemplateArguments(
174 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor9961ce92010-07-08 18:37:38 +0000175 if (ClassTemplate->isMemberSpecialization())
176 break;
177 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000178 }
John McCall970d5302009-08-29 03:16:09 +0000179
180 Ctx = Ctx->getParent();
Douglas Gregor8c702532010-02-05 07:33:43 +0000181 RelativeToPrimary = false;
Douglas Gregorb4850462009-05-14 23:26:13 +0000182 }
Mike Stump11289f42009-09-09 15:08:12 +0000183
Douglas Gregora654dd82009-08-28 17:37:35 +0000184 return Result;
Douglas Gregorb4850462009-05-14 23:26:13 +0000185}
186
Richard Smith696e3122017-02-23 01:43:54 +0000187bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000188 switch (Kind) {
189 case TemplateInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000190 case ExceptionSpecInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000191 case DefaultTemplateArgumentInstantiation:
192 case DefaultFunctionArgumentInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000193 case ExplicitTemplateArgumentSubstitution:
194 case DeducedTemplateArgumentSubstitution:
195 case PriorTemplateArgumentSubstitution:
Richard Smith8a874c92012-07-08 02:38:24 +0000196 return true;
197
Douglas Gregor84d49a22009-11-11 21:54:23 +0000198 case DefaultTemplateArgumentChecking:
199 return false;
200 }
David Blaikie8a40f702012-01-17 06:56:22 +0000201
Richard Smith696e3122017-02-23 01:43:54 +0000202 llvm_unreachable("Invalid SynthesisKind!");
Douglas Gregor84d49a22009-11-11 21:54:23 +0000203}
204
Benjamin Kramer7761a042015-03-06 16:36:50 +0000205Sema::InstantiatingTemplate::InstantiatingTemplate(
Richard Smith696e3122017-02-23 01:43:54 +0000206 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000207 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
208 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000209 sema::TemplateDeductionInfo *DeductionInfo)
210 : SemaRef(SemaRef), SavedInNonInstantiationSFINAEContext(
211 SemaRef.InNonInstantiationSFINAEContext) {
Akira Hatanaka43556c12016-11-03 15:04:58 +0000212 // Don't allow further instantiation if a fatal error and an uncompilable
Akira Hatanaka40c15ab2016-11-03 17:11:28 +0000213 // error have occurred. Any diagnostics we might have raised will not be
Akira Hatanaka43556c12016-11-03 15:04:58 +0000214 // visible, and we do not need to construct a correct AST.
215 if (SemaRef.Diags.hasFatalErrorOccurred() &&
216 SemaRef.Diags.hasUncompilableErrorOccurred()) {
David Majnemer8c969ea2015-01-30 05:01:23 +0000217 Invalid = true;
218 return;
219 }
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000220 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
221 if (!Invalid) {
Richard Smith696e3122017-02-23 01:43:54 +0000222 CodeSynthesisContext Inst;
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000223 Inst.Kind = Kind;
224 Inst.PointOfInstantiation = PointOfInstantiation;
225 Inst.Entity = Entity;
226 Inst.Template = Template;
227 Inst.TemplateArgs = TemplateArgs.data();
228 Inst.NumTemplateArgs = TemplateArgs.size();
229 Inst.DeductionInfo = DeductionInfo;
230 Inst.InstantiationRange = InstantiationRange;
Richard Smith54f18e82016-08-31 02:15:21 +0000231 AlreadyInstantiating =
232 !SemaRef.InstantiatingSpecializations
233 .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
234 .second;
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000235 SemaRef.InNonInstantiationSFINAEContext = false;
Richard Smith696e3122017-02-23 01:43:54 +0000236 SemaRef.CodeSynthesisContexts.push_back(Inst);
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000237 if (!Inst.isInstantiationRecord())
238 ++SemaRef.NonInstantiationEntries;
239 }
240}
241
Benjamin Kramer7761a042015-03-06 16:36:50 +0000242Sema::InstantiatingTemplate::InstantiatingTemplate(
243 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
244 SourceRange InstantiationRange)
245 : InstantiatingTemplate(SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000246 CodeSynthesisContext::TemplateInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000247 PointOfInstantiation, InstantiationRange, Entity) {}
Douglas Gregor79cf6032009-03-10 20:44:00 +0000248
Benjamin Kramer7761a042015-03-06 16:36:50 +0000249Sema::InstantiatingTemplate::InstantiatingTemplate(
250 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
251 ExceptionSpecification, SourceRange InstantiationRange)
252 : InstantiatingTemplate(
Richard Smith696e3122017-02-23 01:43:54 +0000253 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000254 PointOfInstantiation, InstantiationRange, Entity) {}
Richard Smithf623c962012-04-17 00:58:00 +0000255
Benjamin Kramer7761a042015-03-06 16:36:50 +0000256Sema::InstantiatingTemplate::InstantiatingTemplate(
Richard Smith54f18e82016-08-31 02:15:21 +0000257 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
258 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
259 SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000260 : InstantiatingTemplate(
261 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000262 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
Richard Smith54f18e82016-08-31 02:15:21 +0000263 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
264 Template, TemplateArgs) {}
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000265
Benjamin Kramer7761a042015-03-06 16:36:50 +0000266Sema::InstantiatingTemplate::InstantiatingTemplate(
267 Sema &SemaRef, SourceLocation PointOfInstantiation,
268 FunctionTemplateDecl *FunctionTemplate,
269 ArrayRef<TemplateArgument> TemplateArgs,
Richard Smith696e3122017-02-23 01:43:54 +0000270 CodeSynthesisContext::SynthesisKind Kind,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000271 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
272 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
273 InstantiationRange, FunctionTemplate, nullptr,
Richard Smith54f18e82016-08-31 02:15:21 +0000274 TemplateArgs, &DeductionInfo) {
275 assert(
Richard Smith696e3122017-02-23 01:43:54 +0000276 Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
277 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution);
Richard Smith54f18e82016-08-31 02:15:21 +0000278}
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000279
Benjamin Kramer7761a042015-03-06 16:36:50 +0000280Sema::InstantiatingTemplate::InstantiatingTemplate(
281 Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith0e617ec2016-12-27 07:56:27 +0000282 TemplateDecl *Template,
283 ArrayRef<TemplateArgument> TemplateArgs,
284 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
285 : InstantiatingTemplate(
286 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000287 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
Richard Smith0e617ec2016-12-27 07:56:27 +0000288 PointOfInstantiation, InstantiationRange, Template, nullptr,
289 TemplateArgs, &DeductionInfo) {}
290
291Sema::InstantiatingTemplate::InstantiatingTemplate(
292 Sema &SemaRef, SourceLocation PointOfInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000293 ClassTemplatePartialSpecializationDecl *PartialSpec,
294 ArrayRef<TemplateArgument> TemplateArgs,
295 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
296 : InstantiatingTemplate(
297 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000298 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000299 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
300 TemplateArgs, &DeductionInfo) {}
Douglas Gregor637d9982009-06-10 23:47:09 +0000301
Larisse Voufo39a1e502013-08-06 01:03:05 +0000302Sema::InstantiatingTemplate::InstantiatingTemplate(
303 Sema &SemaRef, SourceLocation PointOfInstantiation,
304 VarTemplatePartialSpecializationDecl *PartialSpec,
305 ArrayRef<TemplateArgument> TemplateArgs,
306 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000307 : InstantiatingTemplate(
308 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000309 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000310 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
311 TemplateArgs, &DeductionInfo) {}
Larisse Voufo39a1e502013-08-06 01:03:05 +0000312
Benjamin Kramer7761a042015-03-06 16:36:50 +0000313Sema::InstantiatingTemplate::InstantiatingTemplate(
314 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
315 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
316 : InstantiatingTemplate(
317 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000318 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000319 PointOfInstantiation, InstantiationRange, Param, nullptr,
320 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000321
Benjamin Kramer7761a042015-03-06 16:36:50 +0000322Sema::InstantiatingTemplate::InstantiatingTemplate(
323 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
324 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
325 SourceRange InstantiationRange)
326 : InstantiatingTemplate(
327 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000328 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000329 PointOfInstantiation, InstantiationRange, Param, Template,
330 TemplateArgs) {}
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000331
Benjamin Kramer7761a042015-03-06 16:36:50 +0000332Sema::InstantiatingTemplate::InstantiatingTemplate(
333 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
334 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
335 SourceRange InstantiationRange)
336 : InstantiatingTemplate(
337 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000338 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000339 PointOfInstantiation, InstantiationRange, Param, Template,
340 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000341
Benjamin Kramer7761a042015-03-06 16:36:50 +0000342Sema::InstantiatingTemplate::InstantiatingTemplate(
343 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
344 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
345 SourceRange InstantiationRange)
346 : InstantiatingTemplate(
Richard Smith696e3122017-02-23 01:43:54 +0000347 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000348 PointOfInstantiation, InstantiationRange, Param, Template,
349 TemplateArgs) {}
Anders Carlsson657bad42009-09-05 05:14:19 +0000350
Douglas Gregor85673582009-05-18 17:01:57 +0000351void Sema::InstantiatingTemplate::Clear() {
352 if (!Invalid) {
Richard Smith696e3122017-02-23 01:43:54 +0000353 auto &Active = SemaRef.CodeSynthesisContexts.back();
Richard Smith54f18e82016-08-31 02:15:21 +0000354 if (!Active.isInstantiationRecord()) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000355 assert(SemaRef.NonInstantiationEntries > 0);
356 --SemaRef.NonInstantiationEntries;
357 }
Douglas Gregoredb76852011-01-27 22:31:44 +0000358 SemaRef.InNonInstantiationSFINAEContext
359 = SavedInNonInstantiationSFINAEContext;
Richard Smith0e5d7b82013-07-25 23:08:39 +0000360
361 // Name lookup no longer looks in this template's defining module.
Richard Smith696e3122017-02-23 01:43:54 +0000362 assert(SemaRef.CodeSynthesisContexts.size() >=
363 SemaRef.CodeSynthesisContextLookupModules.size() &&
Richard Smith0e5d7b82013-07-25 23:08:39 +0000364 "forgot to remove a lookup module for a template instantiation");
Richard Smith696e3122017-02-23 01:43:54 +0000365 if (SemaRef.CodeSynthesisContexts.size() ==
366 SemaRef.CodeSynthesisContextLookupModules.size()) {
367 if (Module *M = SemaRef.CodeSynthesisContextLookupModules.back())
Richard Smith0e5d7b82013-07-25 23:08:39 +0000368 SemaRef.LookupModulesCache.erase(M);
Richard Smith696e3122017-02-23 01:43:54 +0000369 SemaRef.CodeSynthesisContextLookupModules.pop_back();
Richard Smith0e5d7b82013-07-25 23:08:39 +0000370 }
371
Richard Smith73c3c212017-02-23 02:09:03 +0000372 // If we've left the code synthesis context for the current context stack,
373 // stop remembering that we've emitted that stack.
374 if (SemaRef.CodeSynthesisContexts.size() ==
375 SemaRef.LastEmittedCodeSynthesisContextDepth)
376 SemaRef.LastEmittedCodeSynthesisContextDepth = 0;
377
Richard Smith54f18e82016-08-31 02:15:21 +0000378 if (!AlreadyInstantiating)
379 SemaRef.InstantiatingSpecializations.erase(
380 std::make_pair(Active.Entity, Active.Kind));
381
Richard Smith696e3122017-02-23 01:43:54 +0000382 SemaRef.CodeSynthesisContexts.pop_back();
Douglas Gregor85673582009-05-18 17:01:57 +0000383 Invalid = true;
384 }
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000385}
386
Douglas Gregor79cf6032009-03-10 20:44:00 +0000387bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
388 SourceLocation PointOfInstantiation,
389 SourceRange InstantiationRange) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000390 assert(SemaRef.NonInstantiationEntries <=
Richard Smith696e3122017-02-23 01:43:54 +0000391 SemaRef.CodeSynthesisContexts.size());
392 if ((SemaRef.CodeSynthesisContexts.size() -
Douglas Gregor84d49a22009-11-11 21:54:23 +0000393 SemaRef.NonInstantiationEntries)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000394 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregor79cf6032009-03-10 20:44:00 +0000395 return false;
396
Mike Stump11289f42009-09-09 15:08:12 +0000397 SemaRef.Diag(PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000398 diag::err_template_recursion_depth_exceeded)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000399 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregor79cf6032009-03-10 20:44:00 +0000400 << InstantiationRange;
401 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000402 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000403 return true;
404}
405
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000406/// \brief Prints the current instantiation stack through a series of
407/// notes.
408void Sema::PrintInstantiationStack() {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000409 // Determine which template instantiations to skip, if any.
Richard Smith696e3122017-02-23 01:43:54 +0000410 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000411 unsigned Limit = Diags.getTemplateBacktraceLimit();
Richard Smith696e3122017-02-23 01:43:54 +0000412 if (Limit && Limit < CodeSynthesisContexts.size()) {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000413 SkipStart = Limit / 2 + Limit % 2;
Richard Smith696e3122017-02-23 01:43:54 +0000414 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000415 }
416
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000417 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000418 unsigned InstantiationIdx = 0;
Richard Smith696e3122017-02-23 01:43:54 +0000419 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
420 Active = CodeSynthesisContexts.rbegin(),
421 ActiveEnd = CodeSynthesisContexts.rend();
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000422 Active != ActiveEnd;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000423 ++Active, ++InstantiationIdx) {
424 // Skip this instantiation?
425 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
426 if (InstantiationIdx == SkipStart) {
427 // Note that we're skipping instantiations.
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000428 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000429 diag::note_instantiation_contexts_suppressed)
Richard Smith696e3122017-02-23 01:43:54 +0000430 << unsigned(CodeSynthesisContexts.size() - Limit);
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000431 }
432 continue;
433 }
434
Douglas Gregor79cf6032009-03-10 20:44:00 +0000435 switch (Active->Kind) {
Richard Smith696e3122017-02-23 01:43:54 +0000436 case CodeSynthesisContext::TemplateInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000437 Decl *D = Active->Entity;
Douglas Gregor85673582009-05-18 17:01:57 +0000438 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
439 unsigned DiagID = diag::note_template_member_class_here;
440 if (isa<ClassTemplateSpecializationDecl>(Record))
441 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000442 Diags.Report(Active->PointOfInstantiation, DiagID)
Richard Smith792c22d2016-12-24 04:09:05 +0000443 << Record << Active->InstantiationRange;
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000444 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +0000445 unsigned DiagID;
446 if (Function->getPrimaryTemplate())
447 DiagID = diag::note_function_template_spec_here;
448 else
449 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000450 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000451 << Function
452 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000453 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000454 Diags.Report(Active->PointOfInstantiation,
Larisse Voufodbd65772013-08-14 20:15:02 +0000455 VD->isStaticDataMember()?
456 diag::note_template_static_data_member_def_here
457 : diag::note_template_variable_def_here)
Richard Smith3f1b5d02011-05-05 21:57:07 +0000458 << VD
459 << Active->InstantiationRange;
Richard Smith4b38ded2012-03-14 23:13:10 +0000460 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
461 Diags.Report(Active->PointOfInstantiation,
462 diag::note_template_enum_def_here)
463 << ED
464 << Active->InstantiationRange;
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000465 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
466 Diags.Report(Active->PointOfInstantiation,
467 diag::note_template_nsdmi_here)
468 << FD << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000469 } else {
470 Diags.Report(Active->PointOfInstantiation,
471 diag::note_template_type_alias_instantiation_here)
472 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000473 << Active->InstantiationRange;
Douglas Gregor85673582009-05-18 17:01:57 +0000474 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000475 break;
476 }
477
Richard Smith696e3122017-02-23 01:43:54 +0000478 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
Richard Smith54f18e82016-08-31 02:15:21 +0000479 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000480 SmallVector<char, 128> TemplateArgsStr;
481 llvm::raw_svector_ostream OS(TemplateArgsStr);
482 Template->printName(OS);
David Majnemer6fbeee32016-07-07 04:43:07 +0000483 TemplateSpecializationType::PrintTemplateArgumentList(
484 OS, Active->template_arguments(), getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000485 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000486 diag::note_default_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000487 << OS.str()
Douglas Gregor79cf6032009-03-10 20:44:00 +0000488 << Active->InstantiationRange;
489 break;
490 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000491
Richard Smith696e3122017-02-23 01:43:54 +0000492 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000493 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000494 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000495 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000496 << FnTmpl
497 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
498 Active->TemplateArgs,
499 Active->NumTemplateArgs)
500 << Active->InstantiationRange;
Douglas Gregor637d9982009-06-10 23:47:09 +0000501 break;
502 }
Mike Stump11289f42009-09-09 15:08:12 +0000503
Richard Smith696e3122017-02-23 01:43:54 +0000504 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
Richard Smithe68a38f2016-12-24 04:20:31 +0000505 if (FunctionTemplateDecl *FnTmpl =
506 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000507 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000508 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000509 << FnTmpl
510 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
511 Active->TemplateArgs,
512 Active->NumTemplateArgs)
513 << Active->InstantiationRange;
Richard Smithe68a38f2016-12-24 04:20:31 +0000514 } else {
515 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
516 isa<VarTemplateSpecializationDecl>(Active->Entity);
Richard Smith0e617ec2016-12-27 07:56:27 +0000517 bool IsTemplate = false;
Richard Smithe68a38f2016-12-24 04:20:31 +0000518 TemplateParameterList *Params;
Richard Smith0e617ec2016-12-27 07:56:27 +0000519 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
520 IsTemplate = true;
521 Params = D->getTemplateParameters();
522 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
Richard Smithe68a38f2016-12-24 04:20:31 +0000523 Active->Entity)) {
524 Params = D->getTemplateParameters();
525 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
526 Active->Entity)) {
527 Params = D->getTemplateParameters();
528 } else {
529 llvm_unreachable("unexpected template kind");
530 }
531
Richard Smithe68a38f2016-12-24 04:20:31 +0000532 Diags.Report(Active->PointOfInstantiation,
533 diag::note_deduced_template_arg_substitution_here)
Richard Smith0e617ec2016-12-27 07:56:27 +0000534 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
Richard Smithe68a38f2016-12-24 04:20:31 +0000535 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
536 Active->NumTemplateArgs)
537 << Active->InstantiationRange;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000538 }
539 break;
Richard Smithe68a38f2016-12-24 04:20:31 +0000540 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000541
Richard Smith696e3122017-02-23 01:43:54 +0000542 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000543 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson657bad42009-09-05 05:14:19 +0000544 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +0000545
Benjamin Kramer9170e912013-02-22 15:46:01 +0000546 SmallVector<char, 128> TemplateArgsStr;
547 llvm::raw_svector_ostream OS(TemplateArgsStr);
548 FD->printName(OS);
David Majnemer6fbeee32016-07-07 04:43:07 +0000549 TemplateSpecializationType::PrintTemplateArgumentList(
550 OS, Active->template_arguments(), getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000551 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000552 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000553 << OS.str()
Anders Carlsson657bad42009-09-05 05:14:19 +0000554 << Active->InstantiationRange;
555 break;
556 }
Mike Stump11289f42009-09-09 15:08:12 +0000557
Richard Smith696e3122017-02-23 01:43:54 +0000558 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000559 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000560 std::string Name;
561 if (!Parm->getName().empty())
562 Name = std::string(" '") + Parm->getName().str() + "'";
Craig Topperc3ec1492014-05-26 06:22:03 +0000563
564 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000565 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
566 TemplateParams = Template->getTemplateParameters();
567 else
568 TemplateParams =
569 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
570 ->getTemplateParameters();
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000571 Diags.Report(Active->PointOfInstantiation,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000572 diag::note_prior_template_arg_substitution)
573 << isa<TemplateTemplateParmDecl>(Parm)
574 << Name
Douglas Gregorca4686d2011-01-04 23:35:54 +0000575 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000576 Active->TemplateArgs,
577 Active->NumTemplateArgs)
578 << Active->InstantiationRange;
579 break;
580 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000581
Richard Smith696e3122017-02-23 01:43:54 +0000582 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
Craig Topperc3ec1492014-05-26 06:22:03 +0000583 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000584 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
585 TemplateParams = Template->getTemplateParameters();
586 else
587 TemplateParams =
588 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
589 ->getTemplateParameters();
590
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000591 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000592 diag::note_template_default_arg_checking)
Douglas Gregorca4686d2011-01-04 23:35:54 +0000593 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000594 Active->TemplateArgs,
595 Active->NumTemplateArgs)
596 << Active->InstantiationRange;
597 break;
598 }
Richard Smithf623c962012-04-17 00:58:00 +0000599
Richard Smith696e3122017-02-23 01:43:54 +0000600 case CodeSynthesisContext::ExceptionSpecInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000601 Diags.Report(Active->PointOfInstantiation,
602 diag::note_template_exception_spec_instantiation_here)
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000603 << cast<FunctionDecl>(Active->Entity)
Richard Smithf623c962012-04-17 00:58:00 +0000604 << Active->InstantiationRange;
605 break;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000606 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000607 }
608}
609
David Blaikie05785d12013-02-20 22:23:23 +0000610Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregoredb76852011-01-27 22:31:44 +0000611 if (InNonInstantiationSFINAEContext)
Craig Topperc3ec1492014-05-26 06:22:03 +0000612 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregoredb76852011-01-27 22:31:44 +0000613
Richard Smith696e3122017-02-23 01:43:54 +0000614 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
615 Active = CodeSynthesisContexts.rbegin(),
616 ActiveEnd = CodeSynthesisContexts.rend();
Douglas Gregor33834512009-06-14 07:33:30 +0000617 Active != ActiveEnd;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000618 ++Active)
619 {
Douglas Gregor33834512009-06-14 07:33:30 +0000620 switch(Active->Kind) {
Richard Smith696e3122017-02-23 01:43:54 +0000621 case CodeSynthesisContext::TemplateInstantiation:
Richard Smith72249ba2012-04-26 07:24:08 +0000622 // An instantiation of an alias template may or may not be a SFINAE
623 // context, depending on what else is on the stack.
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000624 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smith72249ba2012-04-26 07:24:08 +0000625 break;
626 // Fall through.
Richard Smith696e3122017-02-23 01:43:54 +0000627 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
628 case CodeSynthesisContext::ExceptionSpecInstantiation:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000629 // This is a template instantiation, so there is no SFINAE.
David Blaikie7a30dc52013-02-21 01:47:18 +0000630 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000631
Richard Smith696e3122017-02-23 01:43:54 +0000632 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
633 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
634 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000635 // A default template argument instantiation and substitution into
636 // template parameters with arguments for prior parameters may or may
637 // not be a SFINAE context; look further up the stack.
Douglas Gregor33834512009-06-14 07:33:30 +0000638 break;
Mike Stump11289f42009-09-09 15:08:12 +0000639
Richard Smith696e3122017-02-23 01:43:54 +0000640 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
641 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000642 // We're either substitution explicitly-specified template arguments
643 // or deduced template arguments, so SFINAE applies.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000644 assert(Active->DeductionInfo && "Missing deduction info pointer");
645 return Active->DeductionInfo;
Douglas Gregor33834512009-06-14 07:33:30 +0000646 }
647 }
648
David Blaikie7a30dc52013-02-21 01:47:18 +0000649 return None;
Douglas Gregor33834512009-06-14 07:33:30 +0000650}
651
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000652/// \brief Retrieve the depth and index of a parameter pack.
653static std::pair<unsigned, unsigned>
654getDepthAndIndex(NamedDecl *ND) {
655 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
656 return std::make_pair(TTP->getDepth(), TTP->getIndex());
657
658 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
659 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
660
661 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
662 return std::make_pair(TTP->getDepth(), TTP->getIndex());
663}
664
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000665//===----------------------------------------------------------------------===/
666// Template Instantiation for Types
667//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000668namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000669 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000670 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000671 SourceLocation Loc;
672 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000673
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000674 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000675 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000676
677 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000678 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000679 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000680 DeclarationName Entity)
681 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000682 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000683
Mike Stump11289f42009-09-09 15:08:12 +0000684 /// \brief Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-08-04 16:50:30 +0000685 /// transformed.
686 ///
687 /// For the purposes of template instantiation, a type has already been
688 /// transformed if it is NULL or if it is not dependent.
Douglas Gregor5597ab42010-05-07 23:12:07 +0000689 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000690
Douglas Gregord6ff3322009-08-04 16:50:30 +0000691 /// \brief Returns the location of the entity being instantiated, if known.
692 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000693
Douglas Gregord6ff3322009-08-04 16:50:30 +0000694 /// \brief Returns the name of the entity being instantiated, if any.
695 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000696
Douglas Gregoref6ab412009-10-27 06:26:26 +0000697 /// \brief Sets the "base" location and entity when that
698 /// information is known based on another transformation.
699 void setBase(SourceLocation Loc, DeclarationName Entity) {
700 this->Loc = Loc;
701 this->Entity = Entity;
702 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000703
704 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
705 SourceRange PatternRange,
Robert Wilhelm16e94b92013-08-09 18:02:13 +0000706 ArrayRef<UnexpandedParameterPack> Unexpanded,
707 bool &ShouldExpand, bool &RetainExpansion,
David Blaikie05785d12013-02-20 22:23:23 +0000708 Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000709 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
710 PatternRange, Unexpanded,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000711 TemplateArgs,
712 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000713 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000714 NumExpansions);
715 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000716
Douglas Gregorf3010112011-01-07 16:43:16 +0000717 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
718 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
719 }
720
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000721 TemplateArgument ForgetPartiallySubstitutedPack() {
722 TemplateArgument Result;
723 if (NamedDecl *PartialPack
724 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
725 MultiLevelTemplateArgumentList &TemplateArgs
726 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
727 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000728 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000729 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
730 Result = TemplateArgs(Depth, Index);
731 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
732 }
733 }
734
735 return Result;
736 }
737
738 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
739 if (Arg.isNull())
740 return;
741
742 if (NamedDecl *PartialPack
743 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
744 MultiLevelTemplateArgumentList &TemplateArgs
745 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
746 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000747 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000748 TemplateArgs.setArgument(Depth, Index, Arg);
749 }
750 }
751
Douglas Gregord6ff3322009-08-04 16:50:30 +0000752 /// \brief Transform the given declaration by instantiating a reference to
753 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000754 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000755
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000756 void transformAttrs(Decl *Old, Decl *New) {
757 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
758 }
759
760 void transformedLocalDecl(Decl *Old, Decl *New) {
Richard Smithc38498f2015-04-27 21:27:54 +0000761 // If we've instantiated the call operator of a lambda or the call
762 // operator template of a generic lambda, update the "instantiation of"
763 // information.
764 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
765 if (NewMD && isLambdaCallOperator(NewMD)) {
766 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
767 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
768 NewTD->setInstantiatedFromMemberTemplate(
769 OldMD->getDescribedFunctionTemplate());
770 else
771 NewMD->setInstantiationOfMemberFunction(OldMD,
772 TSK_ImplicitInstantiation);
773 }
774
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000775 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
Richard Smithc7649dc2016-03-23 20:07:07 +0000776
777 // We recreated a local declaration, but not by instantiating it. There
778 // may be pending dependent diagnostics to produce.
779 if (auto *DC = dyn_cast<DeclContext>(Old))
780 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000781 }
782
Mike Stump11289f42009-09-09 15:08:12 +0000783 /// \brief Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000784 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000785 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000786
Dmitri Gribenko00bcdd32012-09-12 17:01:48 +0000787 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000788 /// declaration.
789 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
790
Douglas Gregorebe10102009-08-20 07:17:43 +0000791 /// \brief Rebuild the exception declaration and register the declaration
792 /// as an instantiated local.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000793 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000794 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000795 SourceLocation StartLoc,
796 SourceLocation NameLoc,
797 IdentifierInfo *Name);
Mike Stump11289f42009-09-09 15:08:12 +0000798
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000799 /// \brief Rebuild the Objective-C exception declaration and register the
800 /// declaration as an instantiated local.
801 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
802 TypeSourceInfo *TSInfo, QualType T);
803
John McCall7f41d982009-09-11 04:59:25 +0000804 /// \brief Check for tag mismatches when instantiating an
805 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000806 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
807 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000808 NestedNameSpecifierLoc QualifierLoc,
809 QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000810
Craig Topperc3ec1492014-05-26 06:22:03 +0000811 TemplateName
812 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
813 SourceLocation NameLoc,
814 QualType ObjectType = QualType(),
Richard Smithfd3dae02017-01-20 00:20:39 +0000815 NamedDecl *FirstQualifierInScope = nullptr,
816 bool AllowInjectedClassName = false);
Douglas Gregor9db53502011-03-02 18:07:45 +0000817
Tyler Nowickic724a83e2014-10-12 20:46:07 +0000818 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
819
John McCalldadc5752010-08-24 06:29:42 +0000820 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
821 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
822 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000823
John McCalldadc5752010-08-24 06:29:42 +0000824 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000825 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000826 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
827 SubstNonTypeTemplateParmPackExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000828
829 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
830 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
831
832 /// \brief Transform a reference to a function parameter pack.
833 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
834 ParmVarDecl *PD);
835
836 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
837 /// expand a function parameter pack reference which refers to an expanded
838 /// pack.
839 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
840
Hans Wennborge113c202014-09-18 16:01:32 +0000841 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
Richard Smith2e321552014-11-12 02:00:47 +0000842 FunctionProtoTypeLoc TL) {
843 // Call the base version; it will forward to our overridden version below.
844 return inherited::TransformFunctionProtoType(TLB, TL);
845 }
846
847 template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +0000848 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
849 FunctionProtoTypeLoc TL,
850 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +0000851 unsigned ThisTypeQuals,
852 Fn TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +0000853
Douglas Gregor715e4612011-01-14 22:40:04 +0000854 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +0000855 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +0000856 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +0000857 bool ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +0000858
Mike Stump11289f42009-09-09 15:08:12 +0000859 /// \brief Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +0000860 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +0000861 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000862 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000863
Douglas Gregorada4b792011-01-14 02:55:32 +0000864 /// \brief Transforms an already-substituted template type parameter pack
865 /// into either itself (if we aren't substituting into its pack expansion)
866 /// or the appropriate substituted argument.
867 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
868 SubstTemplateTypeParmPackTypeLoc TL);
869
Richard Smith2589b9802012-07-25 03:56:55 +0000870 ExprResult TransformLambdaExpr(LambdaExpr *E) {
871 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
872 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
873 }
874
David Majnemerb1004102014-03-02 18:46:05 +0000875 TemplateParameterList *TransformTemplateParameterList(
Faisal Vali2cba1332013-10-23 06:44:28 +0000876 TemplateParameterList *OrigTPL) {
877 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
878
879 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
880 TemplateDeclInstantiator DeclInstantiator(getSema(),
881 /* DeclContext *Owner */ Owner, TemplateArgs);
882 return DeclInstantiator.SubstTemplateParams(OrigTPL);
883 }
John McCall7c454bb2011-07-15 05:09:51 +0000884 private:
885 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
886 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +0000887 TemplateArgument arg);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000888 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000889}
Douglas Gregor04318252009-07-06 15:59:29 +0000890
Douglas Gregor5597ab42010-05-07 23:12:07 +0000891bool TemplateInstantiator::AlreadyTransformed(QualType T) {
892 if (T.isNull())
893 return true;
894
Douglas Gregor678d76c2011-07-01 01:22:09 +0000895 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +0000896 return false;
897
898 getSema().MarkDeclarationsReferencedInType(Loc, T);
899 return true;
900}
901
Eli Friedman8917ad52013-07-19 19:40:38 +0000902static TemplateArgument
903getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
904 assert(S.ArgumentPackSubstitutionIndex >= 0);
905 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
906 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
907 if (Arg.isPackExpansion())
908 Arg = Arg.getPackExpansionPattern();
909 return Arg;
910}
911
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000912Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000913 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +0000914 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000915
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000916 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000917 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +0000918 // If the corresponding template argument is NULL or non-existent, it's
919 // because we are performing instantiation from explicitly-specified
920 // template arguments in a function template, but there were some
921 // arguments left unspecified.
922 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
923 TTP->getPosition()))
924 return D;
925
Douglas Gregorf5500772011-01-05 15:48:55 +0000926 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
927
928 if (TTP->isParameterPack()) {
929 assert(Arg.getKind() == TemplateArgument::Pack &&
930 "Missing argument pack");
Eli Friedman8917ad52013-07-19 19:40:38 +0000931 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorf5500772011-01-05 15:48:55 +0000932 }
933
934 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000935 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +0000936 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000937 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +0000938 }
Mike Stump11289f42009-09-09 15:08:12 +0000939
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000940 // Fall through to find the instantiated declaration for this template
941 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +0000942 }
Mike Stump11289f42009-09-09 15:08:12 +0000943
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000944 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000945}
946
Douglas Gregor25289362010-03-01 17:25:41 +0000947Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +0000948 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +0000949 if (!Inst)
Craig Topperc3ec1492014-05-26 06:22:03 +0000950 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000951
Douglas Gregorebe10102009-08-20 07:17:43 +0000952 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
953 return Inst;
954}
955
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000956NamedDecl *
957TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
958 SourceLocation Loc) {
959 // If the first part of the nested-name-specifier was a template type
960 // parameter, instantiate that type parameter down to a tag type.
961 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
962 const TemplateTypeParmType *TTP
963 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000964
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000965 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000966 // FIXME: This needs testing w/ member access expressions.
967 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
968
969 if (TTP->isParameterPack()) {
970 assert(Arg.getKind() == TemplateArgument::Pack &&
971 "Missing argument pack");
972
Douglas Gregore1d60df2011-01-14 23:41:42 +0000973 if (getSema().ArgumentPackSubstitutionIndex == -1)
Craig Topperc3ec1492014-05-26 06:22:03 +0000974 return nullptr;
975
Eli Friedman8917ad52013-07-19 19:40:38 +0000976 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000977 }
978
979 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000980 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000981 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000982
983 if (const TagType *Tag = T->getAs<TagType>())
984 return Tag->getDecl();
985
986 // The resulting type is not a tag; complain.
987 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
Craig Topperc3ec1492014-05-26 06:22:03 +0000988 return nullptr;
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000989 }
990 }
991
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000992 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000993}
994
Douglas Gregorebe10102009-08-20 07:17:43 +0000995VarDecl *
996TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000997 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000998 SourceLocation StartLoc,
999 SourceLocation NameLoc,
1000 IdentifierInfo *Name) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00001001 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001002 StartLoc, NameLoc, Name);
Douglas Gregorf4e837f2010-04-26 17:57:08 +00001003 if (Var)
1004 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1005 return Var;
1006}
1007
1008VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1009 TypeSourceInfo *TSInfo,
1010 QualType T) {
1011 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1012 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +00001013 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1014 return Var;
1015}
1016
John McCall7f41d982009-09-11 04:59:25 +00001017QualType
John McCall954b5de2010-11-04 19:04:38 +00001018TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1019 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001020 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara6150c882010-05-11 21:36:43 +00001021 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +00001022 if (const TagType *TT = T->getAs<TagType>()) {
1023 TagDecl* TD = TT->getDecl();
1024
John McCall954b5de2010-11-04 19:04:38 +00001025 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +00001026
John McCall7f41d982009-09-11 04:59:25 +00001027 IdentifierInfo *Id = TD->getIdentifier();
1028
1029 // TODO: should we even warn on struct/class mismatches for this? Seems
1030 // like it's likely to produce a lot of spurious errors.
Richard Smith80b3c5a2012-08-17 00:12:27 +00001031 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001032 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieucaa33d32011-06-10 03:11:26 +00001033 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001034 TagLocation, Id)) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001035 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1036 << Id
1037 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1038 TD->getKindName());
1039 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1040 }
John McCall7f41d982009-09-11 04:59:25 +00001041 }
1042 }
1043
John McCall954b5de2010-11-04 19:04:38 +00001044 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1045 Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001046 QualifierLoc,
1047 T);
John McCall7f41d982009-09-11 04:59:25 +00001048}
1049
Richard Smithfd3dae02017-01-20 00:20:39 +00001050TemplateName TemplateInstantiator::TransformTemplateName(
1051 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1052 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1053 bool AllowInjectedClassName) {
Douglas Gregor9db53502011-03-02 18:07:45 +00001054 if (TemplateTemplateParmDecl *TTP
1055 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1056 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1057 // If the corresponding template argument is NULL or non-existent, it's
1058 // because we are performing instantiation from explicitly-specified
1059 // template arguments in a function template, but there were some
1060 // arguments left unspecified.
1061 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1062 TTP->getPosition()))
1063 return Name;
1064
1065 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1066
1067 if (TTP->isParameterPack()) {
1068 assert(Arg.getKind() == TemplateArgument::Pack &&
1069 "Missing argument pack");
1070
1071 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1072 // We have the template argument pack to substitute, but we're not
1073 // actually expanding the enclosing pack expansion yet. So, just
1074 // keep the entire argument pack.
1075 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1076 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001077
1078 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor9db53502011-03-02 18:07:45 +00001079 }
1080
1081 TemplateName Template = Arg.getAsTemplate();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001082 assert(!Template.isNull() && "Null template template argument");
John McCalld9dfe3a2011-06-30 08:33:18 +00001083
Douglas Gregor9d9f8db2011-03-05 20:06:51 +00001084 // We don't ever want to substitute for a qualified template name, since
1085 // the qualifier is handled separately. So, look through the qualified
1086 // template name to its underlying declaration.
1087 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1088 Template = TemplateName(QTN->getTemplateDecl());
John McCalld9dfe3a2011-06-30 08:33:18 +00001089
1090 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregor9db53502011-03-02 18:07:45 +00001091 return Template;
1092 }
1093 }
1094
1095 if (SubstTemplateTemplateParmPackStorage *SubstPack
1096 = Name.getAsSubstTemplateTemplateParmPack()) {
1097 if (getSema().ArgumentPackSubstitutionIndex == -1)
1098 return Name;
1099
Eli Friedman8917ad52013-07-19 19:40:38 +00001100 TemplateArgument Arg = SubstPack->getArgumentPack();
1101 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1102 return Arg.getAsTemplate();
Douglas Gregor9db53502011-03-02 18:07:45 +00001103 }
Richard Smithfd3dae02017-01-20 00:20:39 +00001104
1105 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1106 FirstQualifierInScope,
1107 AllowInjectedClassName);
Douglas Gregor9db53502011-03-02 18:07:45 +00001108}
1109
John McCalldadc5752010-08-24 06:29:42 +00001110ExprResult
John McCall47f29ea2009-12-08 09:21:05 +00001111TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +00001112 if (!E->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001113 return E;
Anders Carlsson0b209a82009-09-11 01:22:35 +00001114
Wei Panc354d212013-09-16 13:57:27 +00001115 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
Anders Carlsson0b209a82009-09-11 01:22:35 +00001116}
1117
John McCalldadc5752010-08-24 06:29:42 +00001118ExprResult
John McCall13481c52010-02-06 08:42:39 +00001119TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001120 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +00001121 // If the corresponding template argument is NULL or non-existent, it's
1122 // because we are performing instantiation from explicitly-specified
1123 // template arguments in a function template, but there were some
1124 // arguments left unspecified.
1125 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1126 NTTP->getPosition()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001127 return E;
Mike Stump11289f42009-09-09 15:08:12 +00001128
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001129 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
Richard Smithb4f96252017-02-21 06:30:38 +00001130
1131 if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1132 // We're performing a partial substitution, so the substituted argument
1133 // could be dependent. As a result we can't create a SubstNonType*Expr
1134 // node now, since that represents a fully-substituted argument.
1135 // FIXME: We should have some AST representation for this.
1136 if (Arg.getKind() == TemplateArgument::Pack) {
1137 // FIXME: This won't work for alias templates.
1138 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1139 "unexpected pack arguments in partial substitution");
1140 Arg = Arg.pack_begin()->getPackExpansionPattern();
1141 }
1142 assert(Arg.getKind() == TemplateArgument::Expression &&
1143 "unexpected nontype template argument kind in partial substitution");
1144 return Arg.getAsExpr();
1145 }
1146
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001147 if (NTTP->isParameterPack()) {
1148 assert(Arg.getKind() == TemplateArgument::Pack &&
1149 "Missing argument pack");
1150
1151 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001152 // We have an argument pack, but we can't select a particular argument
1153 // out of it yet. Therefore, we'll build an expression to hold on to that
1154 // argument pack.
1155 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1156 E->getLocation(),
1157 NTTP->getDeclName());
1158 if (TargetType.isNull())
1159 return ExprError();
1160
1161 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1162 NTTP,
1163 E->getLocation(),
1164 Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001165 }
1166
Eli Friedman8917ad52013-07-19 19:40:38 +00001167 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001168 }
Mike Stump11289f42009-09-09 15:08:12 +00001169
John McCall7c454bb2011-07-15 05:09:51 +00001170 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1171}
1172
Tyler Nowickic724a83e2014-10-12 20:46:07 +00001173const LoopHintAttr *
1174TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1175 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1176
1177 if (TransformedExpr == LH->getValue())
1178 return LH;
1179
1180 // Generate error if there is a problem with the value.
1181 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1182 return LH;
1183
1184 // Create new LoopHintValueAttr with integral expression in place of the
1185 // non-type template parameter.
1186 return LoopHintAttr::CreateImplicit(
1187 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1188 LH->getState(), TransformedExpr, LH->getRange());
1189}
1190
John McCall7c454bb2011-07-15 05:09:51 +00001191ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1192 NonTypeTemplateParmDecl *parm,
1193 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001194 TemplateArgument arg) {
John McCall7c454bb2011-07-15 05:09:51 +00001195 ExprResult result;
1196 QualType type;
1197
John McCall13481c52010-02-06 08:42:39 +00001198 // The template argument itself might be an expression, in which
1199 // case we just return that expression.
John McCall7c454bb2011-07-15 05:09:51 +00001200 if (arg.getKind() == TemplateArgument::Expression) {
1201 Expr *argExpr = arg.getAsExpr();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001202 result = argExpr;
John McCall7c454bb2011-07-15 05:09:51 +00001203 type = argExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001204
Eli Friedmanb826a002012-09-26 02:36:12 +00001205 } else if (arg.getKind() == TemplateArgument::Declaration ||
1206 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001207 ValueDecl *VD;
Eli Friedmanb826a002012-09-26 02:36:12 +00001208 if (arg.getKind() == TemplateArgument::Declaration) {
1209 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001210
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001211 // Find the instantiation of the template argument. This is
1212 // required for nested templates.
1213 VD = cast_or_null<ValueDecl>(
1214 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1215 if (!VD)
1216 return ExprError();
1217 } else {
1218 // Propagate NULL template argument.
Craig Topperc3ec1492014-05-26 06:22:03 +00001219 VD = nullptr;
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001220 }
1221
John McCall15dda372010-02-06 10:23:53 +00001222 // Derive the type we want the substituted decl to have. This had
1223 // better be non-dependent, or these checks will have serious problems.
John McCall7c454bb2011-07-15 05:09:51 +00001224 if (parm->isExpandedParameterPack()) {
1225 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1226 } else if (parm->isParameterPack() &&
1227 isa<PackExpansionType>(parm->getType())) {
1228 type = SemaRef.SubstType(
1229 cast<PackExpansionType>(parm->getType())->getPattern(),
1230 TemplateArgs, loc, parm->getDeclName());
1231 } else {
Richard Smith5f274382016-09-28 23:55:27 +00001232 type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1233 TemplateArgs, loc, parm->getDeclName());
John McCall7c454bb2011-07-15 05:09:51 +00001234 }
1235 assert(!type.isNull() && "type substitution failed for param type");
1236 assert(!type->isDependentType() && "param type still dependent");
1237 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCall13481c52010-02-06 08:42:39 +00001238
John McCall7c454bb2011-07-15 05:09:51 +00001239 if (!result.isInvalid()) type = result.get()->getType();
1240 } else {
1241 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1242
1243 // Note that this type can be different from the type of 'result',
1244 // e.g. if it's an enum type.
1245 type = arg.getIntegralType();
1246 }
1247 if (result.isInvalid()) return ExprError();
1248
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001249 Expr *resultExpr = result.get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001250 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1251 type, resultExpr->getValueKind(), loc, parm, resultExpr);
John McCall13481c52010-02-06 08:42:39 +00001252}
1253
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001254ExprResult
1255TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1256 SubstNonTypeTemplateParmPackExpr *E) {
1257 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1258 // We aren't expanding the parameter pack, so just return ourselves.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001259 return E;
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001260 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001261
1262 TemplateArgument Arg = E->getArgumentPack();
1263 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall7c454bb2011-07-15 05:09:51 +00001264 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1265 E->getParameterPackLocation(),
1266 Arg);
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001267}
John McCall13481c52010-02-06 08:42:39 +00001268
John McCalldadc5752010-08-24 06:29:42 +00001269ExprResult
Richard Smithb15fe3a2012-09-12 00:56:43 +00001270TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1271 SourceLocation Loc) {
1272 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1273 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1274}
1275
1276ExprResult
1277TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1278 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1279 // We can expand this parameter pack now.
1280 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1281 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1282 if (!VD)
1283 return ExprError();
1284 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1285 }
1286
1287 QualType T = TransformType(E->getType());
1288 if (T.isNull())
1289 return ExprError();
1290
1291 // Transform each of the parameter expansions into the corresponding
1292 // parameters in the instantiation of the function decl.
James Y Knight48fefa32015-09-30 14:04:23 +00001293 SmallVector<ParmVarDecl *, 8> Parms;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001294 Parms.reserve(E->getNumExpansions());
1295 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1296 I != End; ++I) {
1297 ParmVarDecl *D =
1298 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1299 if (!D)
1300 return ExprError();
1301 Parms.push_back(D);
1302 }
1303
1304 return FunctionParmPackExpr::Create(getSema().Context, T,
1305 E->getParameterPack(),
1306 E->getParameterPackLocation(), Parms);
1307}
1308
1309ExprResult
1310TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1311 ParmVarDecl *PD) {
1312 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1313 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1314 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1315 assert(Found && "no instantiation for parameter pack");
1316
1317 Decl *TransformedDecl;
1318 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
Nico Weberc153d242014-07-28 00:02:09 +00001319 // If this is a reference to a function parameter pack which we can
1320 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
Richard Smithb15fe3a2012-09-12 00:56:43 +00001321 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1322 QualType T = TransformType(E->getType());
1323 if (T.isNull())
1324 return ExprError();
1325 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1326 E->getExprLoc(), *Pack);
1327 }
1328
1329 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1330 } else {
1331 TransformedDecl = Found->get<Decl*>();
1332 }
1333
1334 // We have either an unexpanded pack or a specific expansion.
1335 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1336 E->getExprLoc());
1337}
1338
1339ExprResult
John McCall13481c52010-02-06 08:42:39 +00001340TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1341 NamedDecl *D = E->getDecl();
Richard Smithb15fe3a2012-09-12 00:56:43 +00001342
1343 // Handle references to non-type template parameters and non-type template
1344 // parameter packs.
John McCall13481c52010-02-06 08:42:39 +00001345 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1346 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1347 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor954de172009-10-31 17:21:17 +00001348
1349 // We have a non-type template parameter that isn't fully substituted;
1350 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001351 }
Mike Stump11289f42009-09-09 15:08:12 +00001352
Richard Smithb15fe3a2012-09-12 00:56:43 +00001353 // Handle references to function parameter packs.
1354 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1355 if (PD->isParameterPack())
1356 return TransformFunctionParmPackRefExpr(E, PD);
1357
John McCall47f29ea2009-12-08 09:21:05 +00001358 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001359}
1360
John McCalldadc5752010-08-24 06:29:42 +00001361ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001362 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001363 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1364 getDescribedFunctionTemplate() &&
1365 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001366 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1367 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1368 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001369}
1370
Richard Smith2e321552014-11-12 02:00:47 +00001371template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +00001372QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1373 FunctionProtoTypeLoc TL,
1374 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +00001375 unsigned ThisTypeQuals,
1376 Fn TransformExceptionSpec) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001377 // We need a local instantiation scope for this function prototype.
1378 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
Richard Smith2e321552014-11-12 02:00:47 +00001379 return inherited::TransformFunctionProtoType(
1380 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +00001381}
1382
John McCall58f10c32010-03-11 09:03:00 +00001383ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001384TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001385 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001386 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001387 bool ExpectParameterPack) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001388 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001389 NumExpansions, ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +00001390}
1391
Mike Stump11289f42009-09-09 15:08:12 +00001392QualType
John McCall550e0c22009-10-21 00:40:46 +00001393TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001394 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001395 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001396 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001397 // Replace the template type parameter with its corresponding
1398 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001399
1400 // If the corresponding template argument is NULL or doesn't exist, it's
1401 // because we are performing instantiation from explicitly-specified
1402 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001403 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001404 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1405 TemplateTypeParmTypeLoc NewTL
1406 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1407 NewTL.setNameLoc(TL.getNameLoc());
1408 return TL.getType();
1409 }
Mike Stump11289f42009-09-09 15:08:12 +00001410
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001411 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1412
1413 if (T->isParameterPack()) {
1414 assert(Arg.getKind() == TemplateArgument::Pack &&
1415 "Missing argument pack");
1416
1417 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001418 // We have the template argument pack, but we're not expanding the
1419 // enclosing pack expansion yet. Just save the template argument
1420 // pack for later substitution.
1421 QualType Result
1422 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1423 SubstTemplateTypeParmPackTypeLoc NewTL
1424 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1425 NewTL.setNameLoc(TL.getNameLoc());
1426 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001427 }
1428
Eli Friedman8917ad52013-07-19 19:40:38 +00001429 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001430 }
1431
1432 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001433 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001434
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001435 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001436
1437 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001438 QualType Result
1439 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1440 SubstTemplateTypeParmTypeLoc NewTL
1441 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1442 NewTL.setNameLoc(TL.getNameLoc());
1443 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001444 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001445
1446 // The template type parameter comes from an inner template (e.g.,
1447 // the template parameter list of a member template inside the
1448 // template we are instantiating). Create a new template type
1449 // parameter with the template "level" reduced by one.
Craig Topperc3ec1492014-05-26 06:22:03 +00001450 TemplateTypeParmDecl *NewTTPDecl = nullptr;
Chandler Carruth08836322011-05-01 00:51:33 +00001451 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1452 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1453 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1454
Richard Smithb4f96252017-02-21 06:30:38 +00001455 QualType Result = getSema().Context.getTemplateTypeParmType(
1456 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1457 T->isParameterPack(), NewTTPDecl);
John McCall550e0c22009-10-21 00:40:46 +00001458 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1459 NewTL.setNameLoc(TL.getNameLoc());
1460 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001461}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001462
Douglas Gregorada4b792011-01-14 02:55:32 +00001463QualType
1464TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1465 TypeLocBuilder &TLB,
1466 SubstTemplateTypeParmPackTypeLoc TL) {
1467 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1468 // We aren't expanding the parameter pack, so just return ourselves.
1469 SubstTemplateTypeParmPackTypeLoc NewTL
1470 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1471 NewTL.setNameLoc(TL.getNameLoc());
1472 return TL.getType();
1473 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001474
1475 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1476 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1477 QualType Result = Arg.getAsType();
1478
Douglas Gregorada4b792011-01-14 02:55:32 +00001479 Result = getSema().Context.getSubstTemplateTypeParmType(
1480 TL.getTypePtr()->getReplacedParameter(),
1481 Result);
1482 SubstTemplateTypeParmTypeLoc NewTL
1483 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1484 NewTL.setNameLoc(TL.getNameLoc());
1485 return Result;
1486}
1487
John McCall76d824f2009-08-25 22:02:44 +00001488/// \brief Perform substitution on the type T with a given set of template
1489/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001490///
1491/// This routine substitutes the given template arguments into the
1492/// type T and produces the instantiated type.
1493///
1494/// \param T the type into which the template arguments will be
1495/// substituted. If this type is not dependent, it will be returned
1496/// immediately.
1497///
James Dennett634962f2012-06-14 21:40:34 +00001498/// \param Args the template arguments that will be
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001499/// substituted for the top-level template parameters within T.
1500///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001501/// \param Loc the location in the source code where this substitution
1502/// is being performed. It will typically be the location of the
1503/// declarator (if we're instantiating the type of some declaration)
1504/// or the location of the type in the source code (if, e.g., we're
1505/// instantiating the type of a cast expression).
1506///
1507/// \param Entity the name of the entity associated with a declaration
1508/// being instantiated (if any). May be empty to indicate that there
1509/// is no such entity (if, e.g., this is a type that occurs as part of
1510/// a cast expression) or that the entity has no name (e.g., an
1511/// unnamed function parameter).
1512///
Richard Smithee579842017-01-30 20:39:26 +00001513/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1514/// acceptable as the top level type of the result.
1515///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001516/// \returns If the instantiation succeeds, the instantiated
1517/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001518TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001519 const MultiLevelTemplateArgumentList &Args,
1520 SourceLocation Loc,
Richard Smithee579842017-01-30 20:39:26 +00001521 DeclarationName Entity,
1522 bool AllowDeducedTST) {
Richard Smith696e3122017-02-23 01:43:54 +00001523 assert(!CodeSynthesisContexts.empty() &&
John McCall609459e2009-10-21 00:58:09 +00001524 "Cannot perform an instantiation without some context on the "
1525 "instantiation stack");
1526
Douglas Gregor678d76c2011-07-01 01:22:09 +00001527 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001528 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001529 return T;
1530
1531 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
Richard Smithee579842017-01-30 20:39:26 +00001532 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
1533 : Instantiator.TransformType(T);
John McCall609459e2009-10-21 00:58:09 +00001534}
1535
Douglas Gregor5499af42011-01-05 23:12:31 +00001536TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1537 const MultiLevelTemplateArgumentList &Args,
1538 SourceLocation Loc,
1539 DeclarationName Entity) {
Richard Smith696e3122017-02-23 01:43:54 +00001540 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001541 "Cannot perform an instantiation without some context on the "
1542 "instantiation stack");
1543
1544 if (TL.getType().isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001545 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001546
Douglas Gregor678d76c2011-07-01 01:22:09 +00001547 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001548 !TL.getType()->isVariablyModifiedType()) {
1549 // FIXME: Make a copy of the TypeLoc data here, so that we can
1550 // return a new TypeSourceInfo. Inefficient!
1551 TypeLocBuilder TLB;
1552 TLB.pushFullCopy(TL);
1553 return TLB.getTypeSourceInfo(Context, TL.getType());
1554 }
1555
1556 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1557 TypeLocBuilder TLB;
1558 TLB.reserve(TL.getFullDataSize());
1559 QualType Result = Instantiator.TransformType(TLB, TL);
1560 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001561 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001562
1563 return TLB.getTypeSourceInfo(Context, Result);
1564}
1565
John McCall609459e2009-10-21 00:58:09 +00001566/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001567QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001568 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001569 SourceLocation Loc, DeclarationName Entity) {
Richard Smith696e3122017-02-23 01:43:54 +00001570 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregor79cf6032009-03-10 20:44:00 +00001571 "Cannot perform an instantiation without some context on the "
1572 "instantiation stack");
1573
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001574 // If T is not a dependent type or a variably-modified type, there
1575 // is nothing to do.
Douglas Gregor678d76c2011-07-01 01:22:09 +00001576 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001577 return T;
1578
Douglas Gregord6ff3322009-08-04 16:50:30 +00001579 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1580 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001581}
Douglas Gregor463421d2009-03-03 04:44:36 +00001582
John McCallb29f78f2010-04-09 17:38:44 +00001583static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Nico Weberc0973372016-02-01 22:31:51 +00001584 if (T->getType()->isInstantiationDependentType() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00001585 T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001586 return true;
1587
Abramo Bagnara6d810632010-12-14 22:11:44 +00001588 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00001589 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCallb29f78f2010-04-09 17:38:44 +00001590 return false;
1591
David Blaikie6adc78e2013-02-18 22:06:02 +00001592 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Nico Weberc0973372016-02-01 22:31:51 +00001593 for (ParmVarDecl *P : FP.getParams()) {
Reid Klecknera09e44c2013-07-31 21:00:18 +00001594 // This must be synthesized from a typedef.
1595 if (!P) continue;
1596
Nico Weberc0973372016-02-01 22:31:51 +00001597 // If there are any parameters, a new TypeSourceInfo that refers to the
1598 // instantiated parameters must be built.
1599 return true;
John McCallb29f78f2010-04-09 17:38:44 +00001600 }
1601
1602 return false;
1603}
1604
1605/// A form of SubstType intended specifically for instantiating the
1606/// type of a FunctionDecl. Its purpose is solely to force the
Richard Smith2e321552014-11-12 02:00:47 +00001607/// instantiation of default-argument expressions and to avoid
1608/// instantiating an exception-specification.
John McCallb29f78f2010-04-09 17:38:44 +00001609TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1610 const MultiLevelTemplateArgumentList &Args,
1611 SourceLocation Loc,
Douglas Gregor3024f072012-04-16 07:05:22 +00001612 DeclarationName Entity,
1613 CXXRecordDecl *ThisContext,
1614 unsigned ThisTypeQuals) {
Richard Smith696e3122017-02-23 01:43:54 +00001615 assert(!CodeSynthesisContexts.empty() &&
John McCallb29f78f2010-04-09 17:38:44 +00001616 "Cannot perform an instantiation without some context on the "
1617 "instantiation stack");
Nico Weberc0973372016-02-01 22:31:51 +00001618
John McCallb29f78f2010-04-09 17:38:44 +00001619 if (!NeedsInstantiationAsFunctionType(T))
1620 return T;
1621
1622 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1623
1624 TypeLocBuilder TLB;
1625
1626 TypeLoc TL = T->getTypeLoc();
1627 TLB.reserve(TL.getFullDataSize());
1628
Douglas Gregor3024f072012-04-16 07:05:22 +00001629 QualType Result;
David Blaikie6adc78e2013-02-18 22:06:02 +00001630
Richard Smith2e321552014-11-12 02:00:47 +00001631 if (FunctionProtoTypeLoc Proto =
1632 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1633 // Instantiate the type, other than its exception specification. The
1634 // exception specification is instantiated in InitFunctionInstantiation
1635 // once we've built the FunctionDecl.
1636 // FIXME: Set the exception specification to EST_Uninstantiated here,
1637 // instead of rebuilding the function type again later.
1638 Result = Instantiator.TransformFunctionProtoType(
1639 TLB, Proto, ThisContext, ThisTypeQuals,
1640 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1641 bool &Changed) { return false; });
Douglas Gregor3024f072012-04-16 07:05:22 +00001642 } else {
1643 Result = Instantiator.TransformType(TLB, TL);
1644 }
John McCallb29f78f2010-04-09 17:38:44 +00001645 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001646 return nullptr;
John McCallb29f78f2010-04-09 17:38:44 +00001647
1648 return TLB.getTypeSourceInfo(Context, Result);
1649}
1650
Richard Smith2e321552014-11-12 02:00:47 +00001651void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1652 const MultiLevelTemplateArgumentList &Args) {
1653 FunctionProtoType::ExceptionSpecInfo ESI =
1654 Proto->getExtProtoInfo().ExceptionSpec;
1655 assert(ESI.Type != EST_Uninstantiated);
1656
1657 TemplateInstantiator Instantiator(*this, Args, New->getLocation(),
1658 New->getDeclName());
1659
1660 SmallVector<QualType, 4> ExceptionStorage;
1661 bool Changed = false;
1662 if (Instantiator.TransformExceptionSpec(
1663 New->getTypeSourceInfo()->getTypeLoc().getLocEnd(), ESI,
1664 ExceptionStorage, Changed))
1665 // On error, recover by dropping the exception specification.
1666 ESI.Type = EST_None;
1667
1668 UpdateExceptionSpec(New, ESI);
1669}
1670
Douglas Gregor940bca72010-04-12 07:48:19 +00001671ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001672 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall8fb0d9d2011-05-01 22:35:37 +00001673 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001674 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001675 bool ExpectParameterPack) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001676 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Craig Topperc3ec1492014-05-26 06:22:03 +00001677 TypeSourceInfo *NewDI = nullptr;
1678
Douglas Gregor5499af42011-01-05 23:12:31 +00001679 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00001680 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1681
Douglas Gregor5499af42011-01-05 23:12:31 +00001682 // We have a function parameter pack. Substitute into the pattern of the
1683 // expansion.
1684 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1685 OldParm->getLocation(), OldParm->getDeclName());
1686 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001687 return nullptr;
1688
Douglas Gregor5499af42011-01-05 23:12:31 +00001689 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1690 // We still have unexpanded parameter packs, which means that
1691 // our function parameter is still a function parameter pack.
1692 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001693 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001694 NumExpansions);
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001695 } else if (ExpectParameterPack) {
1696 // We expected to get a parameter pack but didn't (because the type
1697 // itself is not a pack expansion type), so complain. This can occur when
1698 // the substitution goes through an alias template that "loses" the
1699 // pack expansion.
1700 Diag(OldParm->getLocation(),
1701 diag::err_function_parameter_pack_without_parameter_packs)
1702 << NewDI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001703 return nullptr;
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001704 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001705 } else {
1706 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1707 OldParm->getDeclName());
1708 }
1709
Douglas Gregor940bca72010-04-12 07:48:19 +00001710 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001711 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001712
1713 if (NewDI->getType()->isVoidType()) {
1714 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
Craig Topperc3ec1492014-05-26 06:22:03 +00001715 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001716 }
1717
1718 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001719 OldParm->getInnerLocStart(),
Douglas Gregor940bca72010-04-12 07:48:19 +00001720 OldParm->getLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001721 OldParm->getIdentifier(),
1722 NewDI->getType(), NewDI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001723 OldParm->getStorageClass());
Douglas Gregor940bca72010-04-12 07:48:19 +00001724 if (!NewParm)
Craig Topperc3ec1492014-05-26 06:22:03 +00001725 return nullptr;
1726
Douglas Gregor940bca72010-04-12 07:48:19 +00001727 // Mark the (new) default argument as uninstantiated (if any).
1728 if (OldParm->hasUninstantiatedDefaultArg()) {
1729 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1730 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001731 } else if (OldParm->hasUnparsedDefaultArg()) {
1732 NewParm->setUnparsedDefaultArg();
1733 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001734 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1735 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
Serge Pavlov73c6a242015-08-23 10:22:28 +00001736 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1737 // Instantiate default arguments for methods of local classes (DR1484)
1738 // and non-defining declarations.
1739 Sema::ContextRAII SavedContext(*this, OwningFunc);
Akira Hatanakad644e022016-12-16 03:19:41 +00001740 LocalInstantiationScope Local(*this, true);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001741 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
John McCalldc40b612015-12-11 01:56:36 +00001742 if (NewArg.isUsable()) {
1743 // It would be nice if we still had this.
1744 SourceLocation EqualLoc = NewArg.get()->getLocStart();
1745 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1746 }
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001747 } else {
1748 // FIXME: if we non-lazily instantiated non-dependent default args for
1749 // non-dependent parameter types we could remove a bunch of duplicate
1750 // conversion warnings for such arguments.
1751 NewParm->setUninstantiatedDefaultArg(Arg);
1752 }
1753 }
Douglas Gregor940bca72010-04-12 07:48:19 +00001754
1755 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001756
Douglas Gregorf3010112011-01-07 16:43:16 +00001757 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smith928be492012-01-25 02:14:59 +00001758 // Add the new parameter to the instantiated parameter pack.
Douglas Gregorf3010112011-01-07 16:43:16 +00001759 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1760 } else {
1761 // Introduce an Old -> New mapping
Douglas Gregor5499af42011-01-05 23:12:31 +00001762 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001763 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001764
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001765 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1766 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001767 NewParm->setDeclContext(CurContext);
John McCall8fb0d9d2011-05-01 22:35:37 +00001768
1769 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1770 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rosea0a86be2013-03-08 22:25:36 +00001771
1772 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1773
Douglas Gregor940bca72010-04-12 07:48:19 +00001774 return NewParm;
1775}
1776
Douglas Gregordd472162011-01-07 00:20:55 +00001777/// \brief Substitute the given template arguments into the given set of
1778/// parameters, producing the set of parameter types that would be generated
1779/// from such a substitution.
David Majnemer59f77922016-06-24 04:05:48 +00001780bool Sema::SubstParmTypes(
1781 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1782 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1783 const MultiLevelTemplateArgumentList &TemplateArgs,
1784 SmallVectorImpl<QualType> &ParamTypes,
1785 SmallVectorImpl<ParmVarDecl *> *OutParams,
1786 ExtParameterInfoBuilder &ParamInfos) {
Richard Smith696e3122017-02-23 01:43:54 +00001787 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregordd472162011-01-07 00:20:55 +00001788 "Cannot perform an instantiation without some context on the "
1789 "instantiation stack");
1790
1791 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1792 DeclarationName());
David Majnemer59f77922016-06-24 04:05:48 +00001793 return Instantiator.TransformFunctionTypeParams(
1794 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
Douglas Gregordd472162011-01-07 00:20:55 +00001795}
1796
John McCall76d824f2009-08-25 22:02:44 +00001797/// \brief Perform substitution on the base class specifiers of the
1798/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001799///
1800/// Produces a diagnostic and returns true on error, returns false and
1801/// attaches the instantiated base classes to the class template
1802/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001803bool
John McCall76d824f2009-08-25 22:02:44 +00001804Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1805 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001806 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001807 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001808 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Richard Trieub5841332015-04-15 01:21:42 +00001809 for (const auto &Base : Pattern->bases()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001810 if (!Base.getType()->isDependentType()) {
1811 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay76d0b462013-06-21 18:58:32 +00001812 if (RD->isInvalidDecl())
1813 Instantiation->setInvalidDecl();
1814 }
Aaron Ballman574705e2014-03-13 15:41:46 +00001815 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001816 continue;
1817 }
1818
Douglas Gregor752a5952011-01-03 22:36:02 +00001819 SourceLocation EllipsisLoc;
Douglas Gregorc52264e2011-03-02 02:04:06 +00001820 TypeSourceInfo *BaseTypeLoc;
Aaron Ballman574705e2014-03-13 15:41:46 +00001821 if (Base.isPackExpansion()) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001822 // This is a pack expansion. See whether we should expand it now, or
1823 // wait until later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001824 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Aaron Ballman574705e2014-03-13 15:41:46 +00001825 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001826 Unexpanded);
1827 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001828 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001829 Optional<unsigned> NumExpansions;
Aaron Ballman574705e2014-03-13 15:41:46 +00001830 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1831 Base.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001832 Unexpanded,
Douglas Gregor752a5952011-01-03 22:36:02 +00001833 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001834 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001835 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001836 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001837 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001838 }
1839
1840 // If we should expand this pack expansion now, do so.
1841 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001842 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001843 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1844
Aaron Ballman574705e2014-03-13 15:41:46 +00001845 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001846 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001847 Base.getSourceRange().getBegin(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001848 DeclarationName());
1849 if (!BaseTypeLoc) {
1850 Invalid = true;
1851 continue;
1852 }
1853
1854 if (CXXBaseSpecifier *InstantiatedBase
1855 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001856 Base.getSourceRange(),
1857 Base.isVirtual(),
1858 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001859 BaseTypeLoc,
1860 SourceLocation()))
1861 InstantiatedBases.push_back(InstantiatedBase);
1862 else
1863 Invalid = true;
1864 }
1865
1866 continue;
1867 }
1868
1869 // The resulting base specifier will (still) be a pack expansion.
Aaron Ballman574705e2014-03-13 15:41:46 +00001870 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregorc52264e2011-03-02 02:04:06 +00001871 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Aaron Ballman574705e2014-03-13 15:41:46 +00001872 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001873 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001874 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001875 DeclarationName());
1876 } else {
Aaron Ballman574705e2014-03-13 15:41:46 +00001877 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001878 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001879 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001880 DeclarationName());
Douglas Gregor752a5952011-01-03 22:36:02 +00001881 }
1882
Nick Lewycky19b9f952010-07-26 16:56:01 +00001883 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001884 Invalid = true;
1885 continue;
1886 }
1887
1888 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001889 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001890 Base.getSourceRange(),
1891 Base.isVirtual(),
1892 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001893 BaseTypeLoc,
1894 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001895 InstantiatedBases.push_back(InstantiatedBase);
1896 else
1897 Invalid = true;
1898 }
1899
Craig Topperaa700cb2015-12-27 21:55:19 +00001900 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
Douglas Gregor463421d2009-03-03 04:44:36 +00001901 Invalid = true;
1902
1903 return Invalid;
1904}
1905
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001906// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00001907namespace clang {
1908 namespace sema {
1909 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1910 const MultiLevelTemplateArgumentList &TemplateArgs);
1911 }
1912}
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001913
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001914/// \brief Instantiate the definition of a class from a given pattern.
1915///
1916/// \param PointOfInstantiation The point of instantiation within the
1917/// source code.
1918///
1919/// \param Instantiation is the declaration whose definition is being
1920/// instantiated. This will be either a class template specialization
1921/// or a member class of a class template specialization.
1922///
1923/// \param Pattern is the pattern from which the instantiation
1924/// occurs. This will be either the declaration of a class template or
1925/// the declaration of a member class of a class template.
1926///
1927/// \param TemplateArgs The template arguments to be substituted into
1928/// the pattern.
1929///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001930/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001931///
1932/// \param Complain whether to complain if the class cannot be instantiated due
1933/// to the lack of a definition.
1934///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001935/// \returns true if an error occurred, false otherwise.
1936bool
1937Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1938 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001939 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001940 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001941 bool Complain) {
Mike Stump11289f42009-09-09 15:08:12 +00001942 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001943 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Vassil Vassilevb21ee082016-08-18 22:01:25 +00001944 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00001945 Instantiation->getInstantiatedFromMemberClass(),
1946 Pattern, PatternDef, TSK, Complain))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001947 return true;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001948 Pattern = PatternDef;
1949
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001950 // \brief Record the point of instantiation.
1951 if (MemberSpecializationInfo *MSInfo
1952 = Instantiation->getMemberSpecializationInfo()) {
1953 MSInfo->setTemplateSpecializationKind(TSK);
1954 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregoref6ab412009-10-27 06:26:26 +00001955 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weber3ffc4c92011-12-20 20:32:49 +00001956 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregoref6ab412009-10-27 06:26:26 +00001957 Spec->setTemplateSpecializationKind(TSK);
1958 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001959 }
Richard Smitha1087602014-03-10 00:04:29 +00001960
Douglas Gregorf3430ae2009-03-25 21:23:52 +00001961 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00001962 if (Inst.isInvalid())
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001963 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00001964 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
Richard Smithe19b95d2016-05-26 20:23:13 +00001965 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
1966 "instantiating class definition");
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001967
1968 // Enter the scope of this instantiation. We don't use
1969 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00001970 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor17158422010-05-12 17:27:19 +00001971 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00001972 Sema::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001973
Douglas Gregor51121572010-03-24 01:33:17 +00001974 // If this is an instantiation of a local class, merge this local
1975 // instantiation scope with the enclosing scope. Otherwise, every
1976 // instantiation of a class has its own local instantiation scope.
1977 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00001978 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00001979
Reid Kleckner5b640342016-02-26 19:51:02 +00001980 // All dllexported classes created during instantiation should be fully
1981 // emitted after instantiation completes. We may not be ready to emit any
1982 // delayed classes already on the stack, so save them away and put them back
1983 // later.
1984 decltype(DelayedDllExportClasses) ExportedClasses;
1985 std::swap(ExportedClasses, DelayedDllExportClasses);
1986
John McCall6602bb12010-08-01 02:01:53 +00001987 // Pull attributes from the pattern onto the instantiation.
1988 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1989
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001990 // Start the definition of this instantiation.
1991 Instantiation->startDefinition();
Richard Smitha1087602014-03-10 00:04:29 +00001992
1993 // The instantiation is visible here, even if it was first declared in an
1994 // unimported module.
1995 Instantiation->setHidden(false);
1996
1997 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregore9029562010-05-06 00:28:52 +00001998 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001999
John McCall76d824f2009-08-25 22:02:44 +00002000 // Do substitution on the base class specifiers.
2001 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002002 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002003
Douglas Gregor869853e2010-11-10 19:44:59 +00002004 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002005 SmallVector<Decl*, 4> Fields;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002006 // Delay instantiation of late parsed attributes.
2007 LateInstantiatedAttrVec LateAttrs;
2008 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2009
Aaron Ballman629afae2014-03-07 19:56:05 +00002010 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002011 // Don't instantiate members not belonging in this semantic context.
2012 // e.g. for:
2013 // @code
2014 // template <int i> class A {
2015 // class B *g;
2016 // };
2017 // @endcode
2018 // 'class B' has the template as lexical context but semantically it is
2019 // introduced in namespace scope.
Aaron Ballman629afae2014-03-07 19:56:05 +00002020 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002021 continue;
2022
Aaron Ballman629afae2014-03-07 19:56:05 +00002023 if (Member->isInvalidDecl()) {
Richard Smithded9c2e2012-07-11 22:37:56 +00002024 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002025 continue;
2026 }
2027
Aaron Ballman629afae2014-03-07 19:56:05 +00002028 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002029 if (NewMember) {
Richard Smith938f40b2011-06-11 17:19:42 +00002030 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCall48871652010-08-21 09:40:31 +00002031 Fields.push_back(Field);
Richard Smith7d137e32012-03-23 03:33:32 +00002032 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2033 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2034 // specialization causes the implicit instantiation of the definitions
2035 // of unscoped member enumerations.
2036 // Record a point of instantiation for this implicit instantiation.
Richard Smithb66d7772012-03-23 23:09:08 +00002037 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2038 Enum->isCompleteDefinition()) {
Richard Smith7d137e32012-03-23 03:33:32 +00002039 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2040 assert(MSInfo && "no spec info for member enum specialization");
2041 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2042 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2043 }
Richard Smithded9c2e2012-07-11 22:37:56 +00002044 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2045 if (SA->isFailed()) {
2046 // A static_assert failed. Bail out; instantiating this
2047 // class is probably not meaningful.
2048 Instantiation->setInvalidDecl();
2049 break;
2050 }
Richard Smith7d137e32012-03-23 03:33:32 +00002051 }
2052
2053 if (NewMember->isInvalidDecl())
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002054 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002055 } else {
2056 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002057 // instantiations was a semantic disaster, and we'll want to mark the
2058 // declaration invalid.
2059 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002060 }
2061 }
2062
2063 // Finish checking fields.
Craig Topperc3ec1492014-05-26 06:22:03 +00002064 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2065 SourceLocation(), SourceLocation(), nullptr);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002066 CheckCompletedCXXClass(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002067
Reid Kleckner93f661a2015-03-17 21:51:43 +00002068 // Default arguments are parsed, if not instantiated. We can go instantiate
2069 // default arg exprs for default constructors if necessary now.
Hans Wennborg99000c22015-08-15 01:18:16 +00002070 ActOnFinishCXXNonNestedClass(Instantiation);
Reid Kleckner93f661a2015-03-17 21:51:43 +00002071
Reid Kleckner5b640342016-02-26 19:51:02 +00002072 // Put back the delayed exported classes that we moved out of the way.
2073 std::swap(ExportedClasses, DelayedDllExportClasses);
2074
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002075 // Instantiate late parsed attributes, and attach them to their decls.
2076 // See Sema::InstantiateAttrs
2077 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2078 E = LateAttrs.end(); I != E; ++I) {
2079 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2080 CurrentInstantiationScope = I->Scope;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002081
2082 // Allow 'this' within late-parsed attributes.
2083 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2084 CXXRecordDecl *ThisContext =
2085 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2086 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2087 ND && ND->isCXXInstanceMember());
2088
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002089 Attr *NewAttr =
2090 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2091 I->NewDecl->addAttr(NewAttr);
2092 LocalInstantiationScope::deleteScopes(I->Scope,
2093 Instantiator.getStartingScope());
2094 }
2095 Instantiator.disableLateAttributeInstantiation();
2096 LateAttrs.clear();
2097
Richard Smithd3b5c9082012-07-27 04:22:15 +00002098 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002099
Richard Smitha1087602014-03-10 00:04:29 +00002100 // FIXME: We should do something similar for explicit instantiations so they
2101 // end up in the right module.
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002102 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidise3789482012-02-11 01:59:57 +00002103 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002104 Instantiation->setLocStart(Pattern->getInnerLocStart());
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00002105 Instantiation->setBraceRange(Pattern->getBraceRange());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002106 }
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002107
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002108 if (!Instantiation->isInvalidDecl()) {
John McCalla0a96892012-08-10 03:15:35 +00002109 // Perform any dependent diagnostics from the pattern.
2110 PerformDependentDiagnostics(Pattern, TemplateArgs);
2111
Douglas Gregor869853e2010-11-10 19:44:59 +00002112 // Instantiate any out-of-line class template partial
2113 // specializations now.
Richard Smith10b55fc2013-09-26 03:49:48 +00002114 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregor869853e2010-11-10 19:44:59 +00002115 P = Instantiator.delayed_partial_spec_begin(),
2116 PEnd = Instantiator.delayed_partial_spec_end();
2117 P != PEnd; ++P) {
2118 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smith10b55fc2013-09-26 03:49:48 +00002119 P->first, P->second)) {
2120 Instantiation->setInvalidDecl();
2121 break;
2122 }
2123 }
2124
2125 // Instantiate any out-of-line variable template partial
2126 // specializations now.
2127 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2128 P = Instantiator.delayed_var_partial_spec_begin(),
2129 PEnd = Instantiator.delayed_var_partial_spec_end();
2130 P != PEnd; ++P) {
2131 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2132 P->first, P->second)) {
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002133 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002134 break;
2135 }
2136 }
2137 }
2138
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002139 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00002140 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002141
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002142 if (!Instantiation->isInvalidDecl()) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00002143 Consumer.HandleTagDeclDefinition(Instantiation);
2144
Douglas Gregor88d292c2010-05-13 16:44:06 +00002145 // Always emit the vtable for an explicit instantiation definition
2146 // of a polymorphic class template specialization.
2147 if (TSK == TSK_ExplicitInstantiationDefinition)
2148 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2149 }
2150
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002151 return Instantiation->isInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002152}
2153
Richard Smith4b38ded2012-03-14 23:13:10 +00002154/// \brief Instantiate the definition of an enum from a given pattern.
2155///
2156/// \param PointOfInstantiation The point of instantiation within the
2157/// source code.
2158/// \param Instantiation is the declaration whose definition is being
2159/// instantiated. This will be a member enumeration of a class
2160/// temploid specialization, or a local enumeration within a
2161/// function temploid specialization.
2162/// \param Pattern The templated declaration from which the instantiation
2163/// occurs.
2164/// \param TemplateArgs The template arguments to be substituted into
2165/// the pattern.
2166/// \param TSK The kind of implicit or explicit instantiation to perform.
2167///
2168/// \return \c true if an error occurred, \c false otherwise.
2169bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2170 EnumDecl *Instantiation, EnumDecl *Pattern,
2171 const MultiLevelTemplateArgumentList &TemplateArgs,
2172 TemplateSpecializationKind TSK) {
2173 EnumDecl *PatternDef = Pattern->getDefinition();
Vassil Vassilevb21ee082016-08-18 22:01:25 +00002174 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00002175 Instantiation->getInstantiatedFromMemberEnum(),
2176 Pattern, PatternDef, TSK,/*Complain*/true))
2177 return true;
2178 Pattern = PatternDef;
2179
2180 // Record the point of instantiation.
2181 if (MemberSpecializationInfo *MSInfo
2182 = Instantiation->getMemberSpecializationInfo()) {
2183 MSInfo->setTemplateSpecializationKind(TSK);
2184 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2185 }
2186
2187 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002188 if (Inst.isInvalid())
Richard Smith4b38ded2012-03-14 23:13:10 +00002189 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002190 if (Inst.isAlreadyInstantiating())
2191 return false;
Richard Smithe19b95d2016-05-26 20:23:13 +00002192 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2193 "instantiating enum definition");
Richard Smith4b38ded2012-03-14 23:13:10 +00002194
Richard Smitha1087602014-03-10 00:04:29 +00002195 // The instantiation is visible here, even if it was first declared in an
2196 // unimported module.
2197 Instantiation->setHidden(false);
2198
Richard Smith4b38ded2012-03-14 23:13:10 +00002199 // Enter the scope of this instantiation. We don't use
2200 // PushDeclContext because we don't have a scope.
2201 ContextRAII SavedContext(*this, Instantiation);
2202 EnterExpressionEvaluationContext EvalContext(*this,
2203 Sema::PotentiallyEvaluated);
2204
2205 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2206
2207 // Pull attributes from the pattern onto the instantiation.
2208 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2209
2210 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2211 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2212
2213 // Exit the scope of this instantiation.
2214 SavedContext.pop();
2215
2216 return Instantiation->isInvalidDecl();
2217}
2218
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002219
2220/// \brief Instantiate the definition of a field from the given pattern.
2221///
2222/// \param PointOfInstantiation The point of instantiation within the
2223/// source code.
2224/// \param Instantiation is the declaration whose definition is being
2225/// instantiated. This will be a class of a class temploid
2226/// specialization, or a local enumeration within a function temploid
2227/// specialization.
2228/// \param Pattern The templated declaration from which the instantiation
2229/// occurs.
2230/// \param TemplateArgs The template arguments to be substituted into
2231/// the pattern.
2232///
2233/// \return \c true if an error occurred, \c false otherwise.
2234bool Sema::InstantiateInClassInitializer(
2235 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2236 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2237 // If there is no initializer, we don't need to do anything.
2238 if (!Pattern->hasInClassInitializer())
2239 return false;
2240
2241 assert(Instantiation->getInClassInitStyle() ==
2242 Pattern->getInClassInitStyle() &&
2243 "pattern and instantiation disagree about init style");
2244
2245 // Error out if we haven't parsed the initializer of the pattern yet because
2246 // we are waiting for the closing brace of the outer class.
2247 Expr *OldInit = Pattern->getInClassInitializer();
2248 if (!OldInit) {
2249 RecordDecl *PatternRD = Pattern->getParent();
2250 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
Richard Smith8dbc6b22016-11-22 22:55:12 +00002251 Diag(PointOfInstantiation,
2252 diag::err_in_class_initializer_not_yet_parsed)
2253 << OutermostClass << Pattern;
2254 Diag(Pattern->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002255 Instantiation->setInvalidDecl();
2256 return true;
2257 }
2258
2259 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2260 if (Inst.isInvalid())
2261 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002262 if (Inst.isAlreadyInstantiating()) {
2263 // Error out if we hit an instantiation cycle for this initializer.
2264 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2265 << Instantiation;
2266 return true;
2267 }
Richard Smithe19b95d2016-05-26 20:23:13 +00002268 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2269 "instantiating default member init");
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002270
2271 // Enter the scope of this instantiation. We don't use PushDeclContext because
2272 // we don't have a scope.
2273 ContextRAII SavedContext(*this, Instantiation->getParent());
2274 EnterExpressionEvaluationContext EvalContext(*this,
2275 Sema::PotentiallyEvaluated);
2276
Serge Pavlov907233f2015-04-28 17:58:47 +00002277 LocalInstantiationScope Scope(*this, true);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002278
2279 // Instantiate the initializer.
2280 ActOnStartCXXInClassMemberInitializer();
2281 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2282
2283 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2284 /*CXXDirectInit=*/false);
2285 Expr *Init = NewInit.get();
2286 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2287 ActOnFinishCXXInClassMemberInitializer(
2288 Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2289
Richard Smith4b054b22016-08-24 21:25:37 +00002290 if (auto *L = getASTMutationListener())
2291 L->DefaultMemberInitializerInstantiated(Instantiation);
2292
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002293 // Return true if the in-class initializer is still missing.
2294 return !Instantiation->getInClassInitializer();
2295}
2296
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002297namespace {
2298 /// \brief A partial specialization whose template arguments have matched
2299 /// a given template-id.
2300 struct PartialSpecMatchResult {
2301 ClassTemplatePartialSpecializationDecl *Partial;
2302 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002303 };
2304}
2305
Richard Smith32b43762017-01-08 22:45:21 +00002306/// Get the instantiation pattern to use to instantiate the definition of a
2307/// given ClassTemplateSpecializationDecl (either the pattern of the primary
2308/// template or of a partial specialization).
2309static CXXRecordDecl *
2310getPatternForClassTemplateSpecialization(
2311 Sema &S, SourceLocation PointOfInstantiation,
Larisse Voufo72caf2b2013-08-22 00:59:14 +00002312 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2313 TemplateSpecializationKind TSK, bool Complain) {
Richard Smith32b43762017-01-08 22:45:21 +00002314 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2315 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
2316 return nullptr;
2317
Douglas Gregor463421d2009-03-03 04:44:36 +00002318 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +00002319 CXXRecordDecl *Pattern = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00002320
Douglas Gregor170bc422009-06-12 22:31:52 +00002321 // C++ [temp.class.spec.match]p1:
2322 // When a class template is used in a context that requires an
2323 // instantiation of the class, it is necessary to determine
2324 // whether the instantiation is to be generated using the primary
2325 // template or one of the partial specializations. This is done by
2326 // matching the template arguments of the class template
2327 // specialization with the template argument lists of the partial
2328 // specializations.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002329 typedef PartialSpecMatchResult MatchResult;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002330 SmallVector<MatchResult, 4> Matched;
2331 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor407e9612010-04-30 05:56:50 +00002332 Template->getPartialSpecializations(PartialSpecs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00002333 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
Douglas Gregor407e9612010-04-30 05:56:50 +00002334 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2335 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo98b20f12013-07-19 23:00:19 +00002336 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Richard Smith32b43762017-01-08 22:45:21 +00002337 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
2338 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00002339 // Store the failed-deduction information for use in diagnostics, later.
2340 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00002341 FailedCandidates.addCandidate().set(
2342 DeclAccessPair::make(Template, AS_public), Partial,
Richard Smith32b43762017-01-08 22:45:21 +00002343 MakeDeductionFailureInfo(S.Context, Result, Info));
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002344 (void)Result;
2345 } else {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002346 Matched.push_back(PartialSpecMatchResult());
2347 Matched.back().Partial = Partial;
2348 Matched.back().Args = Info.take();
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002349 }
Douglas Gregor2373c592009-05-31 09:31:02 +00002350 }
2351
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002352 // If we're dealing with a member template where the template parameters
2353 // have been instantiated, this provides the original template parameters
2354 // from which the member template's parameters were instantiated.
Alp Toker965f8822013-11-27 05:22:15 +00002355
Douglas Gregor21610382009-10-29 00:04:11 +00002356 if (Matched.size() >= 1) {
Craig Topper2341c0d2013-07-04 03:08:24 +00002357 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregor21610382009-10-29 00:04:11 +00002358 if (Matched.size() == 1) {
2359 // -- If exactly one matching specialization is found, the
2360 // instantiation is generated from that specialization.
2361 // We don't need to do anything for this.
2362 } else {
2363 // -- If more than one matching specialization is found, the
2364 // partial order rules (14.5.4.2) are used to determine
2365 // whether one of the specializations is more specialized
2366 // than the others. If none of the specializations is more
2367 // specialized than all of the other matching
2368 // specializations, then the use of the class template is
2369 // ambiguous and the program is ill-formed.
Craig Topper2341c0d2013-07-04 03:08:24 +00002370 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2371 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002372 P != PEnd; ++P) {
Richard Smith32b43762017-01-08 22:45:21 +00002373 if (S.getMoreSpecializedPartialSpecialization(
2374 P->Partial, Best->Partial, PointOfInstantiation) == P->Partial)
Douglas Gregor21610382009-10-29 00:04:11 +00002375 Best = P;
Douglas Gregorbe999392009-09-15 16:23:51 +00002376 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002377
Douglas Gregor21610382009-10-29 00:04:11 +00002378 // Determine if the best partial specialization is more specialized than
2379 // the others.
2380 bool Ambiguous = false;
Craig Topper2341c0d2013-07-04 03:08:24 +00002381 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2382 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002383 P != PEnd; ++P) {
2384 if (P != Best &&
Richard Smith32b43762017-01-08 22:45:21 +00002385 S.getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2386 PointOfInstantiation) !=
2387 Best->Partial) {
Douglas Gregor21610382009-10-29 00:04:11 +00002388 Ambiguous = true;
2389 break;
2390 }
2391 }
2392
2393 if (Ambiguous) {
2394 // Partial ordering did not produce a clear winner. Complain.
Richard Smith32b43762017-01-08 22:45:21 +00002395 Inst.Clear();
Douglas Gregor21610382009-10-29 00:04:11 +00002396 ClassTemplateSpec->setInvalidDecl();
Richard Smith32b43762017-01-08 22:45:21 +00002397 S.Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
Douglas Gregor21610382009-10-29 00:04:11 +00002398 << ClassTemplateSpec;
2399
2400 // Print the matching partial specializations.
Craig Topper2341c0d2013-07-04 03:08:24 +00002401 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2402 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002403 P != PEnd; ++P)
Richard Smith32b43762017-01-08 22:45:21 +00002404 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2405 << S.getTemplateArgumentBindingsText(
2406 P->Partial->getTemplateParameters(), *P->Args);
Douglas Gregor01afeef2009-08-28 20:31:08 +00002407
Richard Smith32b43762017-01-08 22:45:21 +00002408 return nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00002409 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002410 }
2411
2412 // Instantiate using the best class template partial specialization.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002413 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregor21610382009-10-29 00:04:11 +00002414 while (OrigPartialSpec->getInstantiatedFromMember()) {
2415 // If we've found an explicit specialization of this class template,
2416 // stop here and use that as the pattern.
2417 if (OrigPartialSpec->isMemberSpecialization())
2418 break;
2419
2420 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2421 }
2422
2423 Pattern = OrigPartialSpec;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002424 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor170bc422009-06-12 22:31:52 +00002425 } else {
2426 // -- If no matches are found, the instantiation is generated
2427 // from the primary template.
Douglas Gregor01afeef2009-08-28 20:31:08 +00002428 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorcf915552009-10-13 16:30:37 +00002429 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2430 // If we've found an explicit specialization of this class template,
2431 // stop here and use that as the pattern.
2432 if (OrigTemplate->isMemberSpecialization())
2433 break;
2434
Douglas Gregor01afeef2009-08-28 20:31:08 +00002435 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00002436 }
2437
Douglas Gregor01afeef2009-08-28 20:31:08 +00002438 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00002439 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002440
Richard Smith32b43762017-01-08 22:45:21 +00002441 return Pattern;
2442}
Mike Stump11289f42009-09-09 15:08:12 +00002443
Richard Smith32b43762017-01-08 22:45:21 +00002444bool Sema::InstantiateClassTemplateSpecialization(
2445 SourceLocation PointOfInstantiation,
2446 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2447 TemplateSpecializationKind TSK, bool Complain) {
2448 // Perform the actual instantiation on the canonical declaration.
2449 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2450 ClassTemplateSpec->getCanonicalDecl());
2451 if (ClassTemplateSpec->isInvalidDecl())
2452 return true;
2453
2454 CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization(
2455 *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
2456 if (!Pattern)
2457 return true;
2458
2459 return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
2460 getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
2461 Complain);
Douglas Gregor463421d2009-03-03 04:44:36 +00002462}
Douglas Gregor90a1a652009-03-19 17:26:29 +00002463
John McCall76d824f2009-08-25 22:02:44 +00002464/// \brief Instantiates the definitions of all of the member
2465/// of the given class, which is an instantiation of a class template
2466/// or a member class of a template.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002467void
2468Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002469 CXXRecordDecl *Instantiation,
2470 const MultiLevelTemplateArgumentList &TemplateArgs,
2471 TemplateSpecializationKind TSK) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00002472 // FIXME: We need to notify the ASTMutationListener that we did all of these
2473 // things, in case we have an explicit instantiation definition in a PCM, a
2474 // module, or preamble, and the declaration is in an imported AST.
David Majnemer192d1792013-11-27 08:20:38 +00002475 assert(
2476 (TSK == TSK_ExplicitInstantiationDefinition ||
2477 TSK == TSK_ExplicitInstantiationDeclaration ||
2478 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2479 "Unexpected template specialization kind!");
Aaron Ballman629afae2014-03-07 19:56:05 +00002480 for (auto *D : Instantiation->decls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002481 bool SuppressNew = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002482 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002483 if (FunctionDecl *Pattern
2484 = Function->getInstantiatedFromMemberFunction()) {
2485 MemberSpecializationInfo *MSInfo
2486 = Function->getMemberSpecializationInfo();
2487 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002488 if (MSInfo->getTemplateSpecializationKind()
2489 == TSK_ExplicitSpecialization)
2490 continue;
2491
Douglas Gregor1d957a32009-10-27 18:42:08 +00002492 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2493 Function,
2494 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002495 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002496 SuppressNew) ||
2497 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002498 continue;
Richard Smitheb36ddf2014-04-24 22:45:46 +00002499
2500 // C++11 [temp.explicit]p8:
2501 // An explicit instantiation definition that names a class template
2502 // specialization explicitly instantiates the class template
2503 // specialization and is only an explicit instantiation definition
2504 // of members whose definition is visible at the point of
2505 // instantiation.
2506 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002507 continue;
2508
Richard Smitheb36ddf2014-04-24 22:45:46 +00002509 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2510
2511 if (Function->isDefined()) {
2512 // Let the ASTConsumer know that this function has been explicitly
2513 // instantiated now, and its linkage might have changed.
2514 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2515 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002516 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Richard Smitheb36ddf2014-04-24 22:45:46 +00002517 } else if (TSK == TSK_ImplicitInstantiation) {
2518 PendingLocalImplicitInstantiations.push_back(
2519 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor1d957a32009-10-27 18:42:08 +00002520 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002521 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002522 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002523 if (isa<VarTemplateSpecializationDecl>(Var))
2524 continue;
2525
Douglas Gregor86d142a2009-10-08 07:24:58 +00002526 if (Var->isStaticDataMember()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002527 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2528 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002529 if (MSInfo->getTemplateSpecializationKind()
2530 == TSK_ExplicitSpecialization)
2531 continue;
2532
Douglas Gregor1d957a32009-10-27 18:42:08 +00002533 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2534 Var,
2535 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002536 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002537 SuppressNew) ||
2538 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002539 continue;
2540
Douglas Gregor1d957a32009-10-27 18:42:08 +00002541 if (TSK == TSK_ExplicitInstantiationDefinition) {
2542 // C++0x [temp.explicit]p8:
2543 // An explicit instantiation definition that names a class template
2544 // specialization explicitly instantiates the class template
2545 // specialization and is only an explicit instantiation definition
2546 // of members whose definition is visible at the point of
2547 // instantiation.
Richard Smith62f19e72016-06-25 00:15:56 +00002548 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002549 continue;
2550
2551 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor86d142a2009-10-08 07:24:58 +00002552 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00002553 } else {
2554 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2555 }
2556 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002557 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Douglas Gregor1da22252010-04-18 18:11:38 +00002558 // Always skip the injected-class-name, along with any
2559 // redeclarations of nested classes, since both would cause us
2560 // to try to instantiate the members of a class twice.
Richard Smith069ecf62014-11-20 22:56:34 +00002561 // Skip closure types; they'll get instantiated when we instantiate
2562 // the corresponding lambda-expression.
2563 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2564 Record->isLambda())
Douglas Gregord801b062009-10-07 23:56:10 +00002565 continue;
2566
Douglas Gregor1d957a32009-10-27 18:42:08 +00002567 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2568 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002569
2570 if (MSInfo->getTemplateSpecializationKind()
2571 == TSK_ExplicitSpecialization)
2572 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00002573
Hans Wennborga86a83b2016-05-26 19:42:56 +00002574 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2575 TSK == TSK_ExplicitInstantiationDeclaration) {
2576 // In MSVC mode, explicit instantiation decl of the outer class doesn't
2577 // affect the inner class.
2578 continue;
2579 }
2580
Douglas Gregor1d957a32009-10-27 18:42:08 +00002581 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2582 Record,
2583 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002584 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002585 SuppressNew) ||
2586 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002587 continue;
2588
Douglas Gregor1d957a32009-10-27 18:42:08 +00002589 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2590 assert(Pattern && "Missing instantiated-from-template information");
2591
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002592 if (!Record->getDefinition()) {
2593 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002594 // C++0x [temp.explicit]p8:
2595 // An explicit instantiation definition that names a class template
2596 // specialization explicitly instantiates the class template
2597 // specialization and is only an explicit instantiation definition
2598 // of members whose definition is visible at the point of
2599 // instantiation.
2600 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2601 MSInfo->setTemplateSpecializationKind(TSK);
2602 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2603 }
2604
2605 continue;
2606 }
2607
2608 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002609 TemplateArgs,
2610 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002611 } else {
2612 if (TSK == TSK_ExplicitInstantiationDefinition &&
2613 Record->getTemplateSpecializationKind() ==
2614 TSK_ExplicitInstantiationDeclaration) {
2615 Record->setTemplateSpecializationKind(TSK);
2616 MarkVTableUsed(PointOfInstantiation, Record, true);
2617 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002618 }
Douglas Gregorc093c1d2009-10-08 01:19:17 +00002619
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002620 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002621 if (Pattern)
2622 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2623 TSK);
Aaron Ballman629afae2014-03-07 19:56:05 +00002624 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smith4b38ded2012-03-14 23:13:10 +00002625 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2626 assert(MSInfo && "No member specialization information?");
2627
2628 if (MSInfo->getTemplateSpecializationKind()
2629 == TSK_ExplicitSpecialization)
2630 continue;
2631
2632 if (CheckSpecializationInstantiationRedecl(
2633 PointOfInstantiation, TSK, Enum,
2634 MSInfo->getTemplateSpecializationKind(),
2635 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2636 SuppressNew)
2637 continue;
2638
2639 if (Enum->getDefinition())
2640 continue;
2641
Richard Smith6739a102016-05-05 00:56:12 +00002642 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
Richard Smith4b38ded2012-03-14 23:13:10 +00002643 assert(Pattern && "Missing instantiated-from-template information");
2644
2645 if (TSK == TSK_ExplicitInstantiationDefinition) {
2646 if (!Pattern->getDefinition())
2647 continue;
2648
2649 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2650 } else {
2651 MSInfo->setTemplateSpecializationKind(TSK);
2652 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2653 }
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002654 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2655 // No need to instantiate in-class initializers during explicit
2656 // instantiation.
2657 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2658 CXXRecordDecl *ClassPattern =
2659 Instantiation->getTemplateInstantiationPattern();
2660 DeclContext::lookup_result Lookup =
2661 ClassPattern->lookup(Field->getDeclName());
David Majnemer76a25622016-06-09 05:26:56 +00002662 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002663 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2664 TemplateArgs);
2665 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002666 }
2667 }
2668}
2669
2670/// \brief Instantiate the definitions of all of the members of the
2671/// given class template specialization, which was named as part of an
2672/// explicit instantiation.
Mike Stump11289f42009-09-09 15:08:12 +00002673void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002674Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002675 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002676 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2677 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002678 // C++0x [temp.explicit]p7:
2679 // An explicit instantiation that names a class template
2680 // specialization is an explicit instantion of the same kind
2681 // (declaration or definition) of each of its members (not
2682 // including members inherited from base classes) that has not
2683 // been previously explicitly specialized in the translation unit
2684 // containing the explicit instantiation, except as described
2685 // below.
2686 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002687 getTemplateInstantiationArgs(ClassTemplateSpec),
2688 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002689}
2690
John McCalldadc5752010-08-24 06:29:42 +00002691StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002692Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002693 if (!S)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002694 return S;
Douglas Gregorebe10102009-08-20 07:17:43 +00002695
2696 TemplateInstantiator Instantiator(*this, TemplateArgs,
2697 SourceLocation(),
2698 DeclarationName());
2699 return Instantiator.TransformStmt(S);
2700}
2701
John McCalldadc5752010-08-24 06:29:42 +00002702ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002703Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002704 if (!E)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002705 return E;
Mike Stump11289f42009-09-09 15:08:12 +00002706
Douglas Gregora16548e2009-08-11 05:31:07 +00002707 TemplateInstantiator Instantiator(*this, TemplateArgs,
2708 SourceLocation(),
2709 DeclarationName());
2710 return Instantiator.TransformExpr(E);
2711}
2712
Richard Smithd59b8322012-12-19 01:39:02 +00002713ExprResult Sema::SubstInitializer(Expr *Init,
2714 const MultiLevelTemplateArgumentList &TemplateArgs,
2715 bool CXXDirectInit) {
2716 TemplateInstantiator Instantiator(*this, TemplateArgs,
2717 SourceLocation(),
2718 DeclarationName());
2719 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2720}
2721
Craig Topper99d23532015-12-24 23:58:29 +00002722bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002723 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002724 SmallVectorImpl<Expr *> &Outputs) {
Craig Topper99d23532015-12-24 23:58:29 +00002725 if (Exprs.empty())
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002726 return false;
Richard Smithd59b8322012-12-19 01:39:02 +00002727
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002728 TemplateInstantiator Instantiator(*this, TemplateArgs,
2729 SourceLocation(),
2730 DeclarationName());
Craig Topper99d23532015-12-24 23:58:29 +00002731 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2732 IsCall, Outputs);
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002733}
2734
Douglas Gregor14454802011-02-25 02:25:35 +00002735NestedNameSpecifierLoc
2736Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2737 const MultiLevelTemplateArgumentList &TemplateArgs) {
2738 if (!NNS)
2739 return NestedNameSpecifierLoc();
2740
2741 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2742 DeclarationName());
2743 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2744}
2745
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002746/// \brief Do template substitution on declaration name info.
2747DeclarationNameInfo
2748Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2749 const MultiLevelTemplateArgumentList &TemplateArgs) {
2750 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2751 NameInfo.getName());
2752 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2753}
2754
Douglas Gregoraa594892009-03-31 18:38:02 +00002755TemplateName
Douglas Gregordf846d12011-03-02 18:46:51 +00002756Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2757 TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002758 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002759 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2760 DeclarationName());
Douglas Gregordf846d12011-03-02 18:46:51 +00002761 CXXScopeSpec SS;
2762 SS.Adopt(QualifierLoc);
2763 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregoraa594892009-03-31 18:38:02 +00002764}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002765
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002766bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2767 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002768 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002769 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2770 DeclarationName());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002771
2772 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00002773}
Douglas Gregor14cf7522010-04-30 18:55:50 +00002774
Richard Smith70b13042015-01-09 01:19:56 +00002775static const Decl *getCanonicalParmVarDecl(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002776 // When storing ParmVarDecls in the local instantiation scope, we always
2777 // want to use the ParmVarDecl from the canonical function declaration,
2778 // since the map is then valid for any redeclaration or definition of that
2779 // function.
2780 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2781 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2782 unsigned i = PV->getFunctionScopeIndex();
Richard Smith70b13042015-01-09 01:19:56 +00002783 // This parameter might be from a freestanding function type within the
2784 // function and isn't necessarily referring to one of FD's parameters.
2785 if (FD->getParamDecl(i) == PV)
2786 return FD->getCanonicalDecl()->getParamDecl(i);
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002787 }
2788 }
2789 return D;
2790}
2791
2792
Douglas Gregorf3010112011-01-07 16:43:16 +00002793llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2794LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002795 D = getCanonicalParmVarDecl(D);
Chris Lattnercab02a62011-02-17 20:34:02 +00002796 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002797 Current = Current->Outer) {
Chris Lattnercab02a62011-02-17 20:34:02 +00002798
Douglas Gregor14cf7522010-04-30 18:55:50 +00002799 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002800 const Decl *CheckD = D;
2801 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00002802 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002803 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00002804 return &Found->second;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002805
2806 // If this is a tag declaration, it's possible that we need to look for
2807 // a previous declaration.
2808 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregorec9fd132012-01-14 16:38:05 +00002809 CheckD = Tag->getPreviousDecl();
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002810 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002811 CheckD = nullptr;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002812 } while (CheckD);
2813
Douglas Gregor14cf7522010-04-30 18:55:50 +00002814 // If we aren't combined with our outer scope, we're done.
2815 if (!Current->CombineWithOuterScope)
2816 break;
2817 }
Chris Lattnercab02a62011-02-17 20:34:02 +00002818
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002819 // If we're performing a partial substitution during template argument
2820 // deduction, we may not have values for template parameters yet.
2821 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2822 isa<TemplateTemplateParmDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00002823 return nullptr;
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002824
Serge Pavlove7ad8312015-05-15 10:10:28 +00002825 // Local types referenced prior to definition may require instantiation.
2826 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2827 if (RD->isLocalClass())
2828 return nullptr;
2829
2830 // Enumeration types referenced prior to definition may appear as a result of
2831 // error recovery.
2832 if (isa<EnumDecl>(D))
Serge Pavlov4c511742015-05-04 16:44:39 +00002833 return nullptr;
2834
Chris Lattnercab02a62011-02-17 20:34:02 +00002835 // If we didn't find the decl, then we either have a sema bug, or we have a
2836 // forward reference to a label declaration. Return null to indicate that
2837 // we have an uninstantiated label.
2838 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Craig Topperc3ec1492014-05-26 06:22:03 +00002839 return nullptr;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002840}
2841
John McCall19c1bfd2010-08-25 05:32:35 +00002842void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002843 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002844 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Richard Smith70b13042015-01-09 01:19:56 +00002845 if (Stored.isNull()) {
2846#ifndef NDEBUG
2847 // It should not be present in any surrounding scope either.
2848 LocalInstantiationScope *Current = this;
2849 while (Current->CombineWithOuterScope && Current->Outer) {
2850 Current = Current->Outer;
2851 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2852 "Instantiated local in inner and outer scopes");
2853 }
2854#endif
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002855 Stored = Inst;
Richard Smith70b13042015-01-09 01:19:56 +00002856 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
James Y Knight48fefa32015-09-30 14:04:23 +00002857 Pack->push_back(cast<ParmVarDecl>(Inst));
Richard Smith70b13042015-01-09 01:19:56 +00002858 } else {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002859 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Richard Smith70b13042015-01-09 01:19:56 +00002860 }
Douglas Gregor14cf7522010-04-30 18:55:50 +00002861}
Douglas Gregorf3010112011-01-07 16:43:16 +00002862
James Y Knight48fefa32015-09-30 14:04:23 +00002863void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2864 ParmVarDecl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002865 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002866 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2867 Pack->push_back(Inst);
2868}
2869
2870void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
Richard Smith70b13042015-01-09 01:19:56 +00002871#ifndef NDEBUG
2872 // This should be the first time we've been told about this decl.
2873 for (LocalInstantiationScope *Current = this;
2874 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2875 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2876 "Creating local pack after instantiation of local");
2877#endif
2878
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002879 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002880 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregorf3010112011-01-07 16:43:16 +00002881 DeclArgumentPack *Pack = new DeclArgumentPack;
2882 Stored = Pack;
2883 ArgumentPacks.push_back(Pack);
2884}
2885
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002886void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2887 const TemplateArgument *ExplicitArgs,
2888 unsigned NumExplicitArgs) {
2889 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2890 "Already have a partially-substituted pack");
2891 assert((!PartiallySubstitutedPack
2892 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2893 "Wrong number of arguments in partially-substituted pack");
2894 PartiallySubstitutedPack = Pack;
2895 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2896 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2897}
2898
2899NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2900 const TemplateArgument **ExplicitArgs,
2901 unsigned *NumExplicitArgs) const {
2902 if (ExplicitArgs)
Craig Topperc3ec1492014-05-26 06:22:03 +00002903 *ExplicitArgs = nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002904 if (NumExplicitArgs)
2905 *NumExplicitArgs = 0;
2906
2907 for (const LocalInstantiationScope *Current = this; Current;
2908 Current = Current->Outer) {
2909 if (Current->PartiallySubstitutedPack) {
2910 if (ExplicitArgs)
2911 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2912 if (NumExplicitArgs)
2913 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2914
2915 return Current->PartiallySubstitutedPack;
2916 }
2917
2918 if (!Current->CombineWithOuterScope)
2919 break;
2920 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002921
2922 return nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002923}