blob: fae1222aed8ee0983586eeb270cc50df9746ff6b [file] [log] [blame]
Douglas Gregor99ebf652009-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 McCall2d887082010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregor577f75a2009-08-04 16:50:30 +000014#include "TreeTransform.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
Faisal Valia3d311e2013-10-23 06:44:28 +000017#include "clang/AST/ASTLambda.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/Expr.h"
20#include "clang/Basic/LangOptions.h"
John McCall19510852010-08-20 18:27:03 +000021#include "clang/Sema/DeclSpec.h"
Richard Smith7a614d82011-06-11 17:19:42 +000022#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000023#include "clang/Sema/Lookup.h"
John McCall7cd088e2010-08-24 07:21:54 +000024#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000025#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000026
27using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000028using namespace sema;
Douglas Gregor99ebf652009-02-27 19:31:52 +000029
Douglas Gregoree1828a2009-03-10 18:03:33 +000030//===----------------------------------------------------------------------===/
31// Template Instantiation Support
32//===----------------------------------------------------------------------===/
33
Douglas Gregord6350ae2009-08-28 20:31:08 +000034/// \brief Retrieve the template argument list(s) that should be used to
35/// instantiate the definition of the given declaration.
Douglas Gregor0f8716b2009-11-09 19:17:50 +000036///
37/// \param D the declaration for which we are computing template instantiation
38/// arguments.
39///
40/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor525f96c2010-02-05 07:33:43 +000041///
42/// \param RelativeToPrimary true if we should get the template
43/// arguments relative to the primary template, even when we're
44/// dealing with a specialization. This is only relevant for function
45/// template specializations.
Douglas Gregore7089b02010-05-03 23:29:10 +000046///
47/// \param Pattern If non-NULL, indicates the pattern from which we will be
48/// instantiating the definition of the given declaration, \p D. This is
49/// used to determine the proper set of template instantiation arguments for
50/// friend function template specializations.
Douglas Gregord1102432009-08-28 17:37:35 +000051MultiLevelTemplateArgumentList
Douglas Gregor0f8716b2009-11-09 19:17:50 +000052Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor525f96c2010-02-05 07:33:43 +000053 const TemplateArgumentList *Innermost,
Douglas Gregore7089b02010-05-03 23:29:10 +000054 bool RelativeToPrimary,
55 const FunctionDecl *Pattern) {
Douglas Gregord1102432009-08-28 17:37:35 +000056 // Accumulate the set of template argument lists in this structure.
57 MultiLevelTemplateArgumentList Result;
Mike Stump1eb44332009-09-09 15:08:12 +000058
Douglas Gregor0f8716b2009-11-09 19:17:50 +000059 if (Innermost)
60 Result.addOuterTemplateArguments(Innermost);
61
Douglas Gregord1102432009-08-28 17:37:35 +000062 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregor93104c12011-05-22 00:21:10 +000063 if (!Ctx) {
Douglas Gregord1102432009-08-28 17:37:35 +000064 Ctx = D->getDeclContext();
Larisse Voufoef4579c2013-08-06 01:03:05 +000065
66 // Add template arguments from a variable template instantiation.
67 if (VarTemplateSpecializationDecl *Spec =
68 dyn_cast<VarTemplateSpecializationDecl>(D)) {
69 // We're done when we hit an explicit specialization.
70 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
71 !isa<VarTemplatePartialSpecializationDecl>(Spec))
72 return Result;
73
74 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
75
76 // If this variable template specialization was instantiated from a
77 // specialized member that is a variable template, we're done.
78 assert(Spec->getSpecializedTemplate() && "No variable template?");
Stephen Hines651f13c2014-04-23 16:59:28 -070079 llvm::PointerUnion<VarTemplateDecl*,
80 VarTemplatePartialSpecializationDecl*> Specialized
81 = Spec->getSpecializedTemplateOrPartial();
82 if (VarTemplatePartialSpecializationDecl *Partial =
83 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
84 if (Partial->isMemberSpecialization())
85 return Result;
86 } else {
87 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
88 if (Tmpl->isMemberSpecialization())
89 return Result;
90 }
Larisse Voufoef4579c2013-08-06 01:03:05 +000091 }
92
Douglas Gregor383041d2011-06-15 14:20:42 +000093 // If we have a template template parameter with translation unit context,
94 // then we're performing substitution into a default template argument of
95 // this template template parameter before we've constructed the template
96 // that will own this template template parameter. In this case, we
97 // use empty template parameter lists for all of the outer templates
98 // to avoid performing any substitutions.
99 if (Ctx->isTranslationUnit()) {
100 if (TemplateTemplateParmDecl *TTP
101 = dyn_cast<TemplateTemplateParmDecl>(D)) {
102 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
Richard Smith7a9f7c72013-05-17 03:04:50 +0000103 Result.addOuterTemplateArguments(None);
Douglas Gregor383041d2011-06-15 14:20:42 +0000104 return Result;
105 }
106 }
Douglas Gregor93104c12011-05-22 00:21:10 +0000107 }
108
John McCallf181d8a2009-08-29 03:16:09 +0000109 while (!Ctx->isFileContext()) {
Douglas Gregord1102432009-08-28 17:37:35 +0000110 // Add template arguments from a class template instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +0000111 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregord1102432009-08-28 17:37:35 +0000112 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
113 // We're done when we hit an explicit specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +0000114 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
115 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregord1102432009-08-28 17:37:35 +0000116 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000117
Douglas Gregord1102432009-08-28 17:37:35 +0000118 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000119
120 // If this class template specialization was instantiated from a
121 // specialized member that is a class template, we're done.
122 assert(Spec->getSpecializedTemplate() && "No class template?");
123 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
124 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000125 }
Douglas Gregord1102432009-08-28 17:37:35 +0000126 // Add template arguments from a function template specialization.
John McCallf181d8a2009-08-29 03:16:09 +0000127 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor525f96c2010-02-05 07:33:43 +0000128 if (!RelativeToPrimary &&
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000129 (Function->getTemplateSpecializationKind() ==
130 TSK_ExplicitSpecialization &&
131 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000132 break;
133
Douglas Gregord1102432009-08-28 17:37:35 +0000134 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000135 = Function->getTemplateSpecializationArgs()) {
136 // Add the template arguments for this specialization.
Douglas Gregord1102432009-08-28 17:37:35 +0000137 Result.addOuterTemplateArguments(TemplateArgs);
John McCallf181d8a2009-08-29 03:16:09 +0000138
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000139 // If this function was instantiated from a specialized member that is
140 // a function template, we're done.
141 assert(Function->getPrimaryTemplate() && "No function template?");
142 if (Function->getPrimaryTemplate()->isMemberSpecialization())
143 break;
Faisal Valia3d311e2013-10-23 06:44:28 +0000144
145 // If this function is a generic lambda specialization, we are done.
146 if (isGenericLambdaCallOperatorSpecialization(Function))
147 break;
148
Douglas Gregorc494f772011-03-05 17:54:25 +0000149 } else if (FunctionTemplateDecl *FunTmpl
150 = Function->getDescribedFunctionTemplate()) {
151 // Add the "injected" template arguments.
Richard Smith7a9f7c72013-05-17 03:04:50 +0000152 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000153 }
154
John McCallf181d8a2009-08-29 03:16:09 +0000155 // If this is a friend declaration and it declares an entity at
156 // namespace scope, take arguments from its lexical parent
Douglas Gregore7089b02010-05-03 23:29:10 +0000157 // instead of its semantic parent, unless of course the pattern we're
158 // instantiating actually comes from the file's context!
John McCallf181d8a2009-08-29 03:16:09 +0000159 if (Function->getFriendObjectKind() &&
Douglas Gregore7089b02010-05-03 23:29:10 +0000160 Function->getDeclContext()->isFileContext() &&
161 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCallf181d8a2009-08-29 03:16:09 +0000162 Ctx = Function->getLexicalDeclContext();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000163 RelativeToPrimary = false;
John McCallf181d8a2009-08-29 03:16:09 +0000164 continue;
165 }
Douglas Gregor24bae922010-07-08 18:37:38 +0000166 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
167 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
168 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith7a9f7c72013-05-17 03:04:50 +0000169 const TemplateSpecializationType *TST =
170 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
171 Result.addOuterTemplateArguments(
172 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor24bae922010-07-08 18:37:38 +0000173 if (ClassTemplate->isMemberSpecialization())
174 break;
175 }
Douglas Gregord1102432009-08-28 17:37:35 +0000176 }
John McCallf181d8a2009-08-29 03:16:09 +0000177
178 Ctx = Ctx->getParent();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000179 RelativeToPrimary = false;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000180 }
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Douglas Gregord1102432009-08-28 17:37:35 +0000182 return Result;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000183}
184
Douglas Gregorf35f8282009-11-11 21:54:23 +0000185bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
186 switch (Kind) {
187 case TemplateInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000188 case ExceptionSpecInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000189 case DefaultTemplateArgumentInstantiation:
190 case DefaultFunctionArgumentInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000191 case ExplicitTemplateArgumentSubstitution:
192 case DeducedTemplateArgumentSubstitution:
193 case PriorTemplateArgumentSubstitution:
Richard Smithab91ef12012-07-08 02:38:24 +0000194 return true;
195
Douglas Gregorf35f8282009-11-11 21:54:23 +0000196 case DefaultTemplateArgumentChecking:
197 return false;
198 }
David Blaikie7530c032012-01-17 06:56:22 +0000199
200 llvm_unreachable("Invalid InstantiationKind!");
Douglas Gregorf35f8282009-11-11 21:54:23 +0000201}
202
Stephen Hines651f13c2014-04-23 16:59:28 -0700203void Sema::InstantiatingTemplate::Initialize(
204 ActiveTemplateInstantiation::InstantiationKind Kind,
205 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
206 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
207 sema::TemplateDeductionInfo *DeductionInfo) {
208 SavedInNonInstantiationSFINAEContext =
209 SemaRef.InNonInstantiationSFINAEContext;
210 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
211 if (!Invalid) {
212 ActiveTemplateInstantiation Inst;
213 Inst.Kind = Kind;
214 Inst.PointOfInstantiation = PointOfInstantiation;
215 Inst.Entity = Entity;
216 Inst.Template = Template;
217 Inst.TemplateArgs = TemplateArgs.data();
218 Inst.NumTemplateArgs = TemplateArgs.size();
219 Inst.DeductionInfo = DeductionInfo;
220 Inst.InstantiationRange = InstantiationRange;
221 SemaRef.InNonInstantiationSFINAEContext = false;
222 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
223 if (!Inst.isInstantiationRecord())
224 ++SemaRef.NonInstantiationEntries;
225 }
226}
227
Douglas Gregor26dce442009-03-10 00:06:19 +0000228Sema::InstantiatingTemplate::
229InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000230 Decl *Entity,
Douglas Gregor26dce442009-03-10 00:06:19 +0000231 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700232 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000233{
Stephen Hines651f13c2014-04-23 16:59:28 -0700234 Initialize(ActiveTemplateInstantiation::TemplateInstantiation,
235 PointOfInstantiation, InstantiationRange, Entity);
Douglas Gregordf667e72009-03-10 20:44:00 +0000236}
237
Richard Smithe6975e92012-04-17 00:58:00 +0000238Sema::InstantiatingTemplate::
239InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
240 FunctionDecl *Entity, ExceptionSpecification,
241 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700242 : SemaRef(SemaRef)
Richard Smithe6975e92012-04-17 00:58:00 +0000243{
Stephen Hines651f13c2014-04-23 16:59:28 -0700244 Initialize(ActiveTemplateInstantiation::ExceptionSpecInstantiation,
245 PointOfInstantiation, InstantiationRange, Entity);
Richard Smithe6975e92012-04-17 00:58:00 +0000246}
247
Richard Smith7e54fb52012-07-16 01:09:10 +0000248Sema::InstantiatingTemplate::
249InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
250 TemplateDecl *Template,
251 ArrayRef<TemplateArgument> TemplateArgs,
252 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700253 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000254{
Stephen Hines651f13c2014-04-23 16:59:28 -0700255 Initialize(ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation,
256 PointOfInstantiation, InstantiationRange,
257 Template, nullptr, TemplateArgs);
Douglas Gregor26dce442009-03-10 00:06:19 +0000258}
259
Richard Smith7e54fb52012-07-16 01:09:10 +0000260Sema::InstantiatingTemplate::
261InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
262 FunctionTemplateDecl *FunctionTemplate,
263 ArrayRef<TemplateArgument> TemplateArgs,
264 ActiveTemplateInstantiation::InstantiationKind Kind,
265 sema::TemplateDeductionInfo &DeductionInfo,
266 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700267 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000268{
Stephen Hines651f13c2014-04-23 16:59:28 -0700269 Initialize(Kind, PointOfInstantiation, InstantiationRange,
270 FunctionTemplate, nullptr, TemplateArgs, &DeductionInfo);
Douglas Gregorcca9e962009-07-01 22:01:06 +0000271}
272
Richard Smith7e54fb52012-07-16 01:09:10 +0000273Sema::InstantiatingTemplate::
274InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
275 ClassTemplatePartialSpecializationDecl *PartialSpec,
276 ArrayRef<TemplateArgument> TemplateArgs,
277 sema::TemplateDeductionInfo &DeductionInfo,
278 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700279 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000280{
Stephen Hines651f13c2014-04-23 16:59:28 -0700281 Initialize(ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
282 PointOfInstantiation, InstantiationRange,
283 PartialSpec, nullptr, TemplateArgs, &DeductionInfo);
Douglas Gregor637a4092009-06-10 23:47:09 +0000284}
285
Larisse Voufoef4579c2013-08-06 01:03:05 +0000286Sema::InstantiatingTemplate::InstantiatingTemplate(
287 Sema &SemaRef, SourceLocation PointOfInstantiation,
288 VarTemplatePartialSpecializationDecl *PartialSpec,
289 ArrayRef<TemplateArgument> TemplateArgs,
290 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700291 : SemaRef(SemaRef)
292{
293 Initialize(ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
294 PointOfInstantiation, InstantiationRange,
295 PartialSpec, nullptr, TemplateArgs, &DeductionInfo);
Larisse Voufoef4579c2013-08-06 01:03:05 +0000296}
297
Richard Smith7e54fb52012-07-16 01:09:10 +0000298Sema::InstantiatingTemplate::
299InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
300 ParmVarDecl *Param,
301 ArrayRef<TemplateArgument> TemplateArgs,
302 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700303 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000304{
Stephen Hines651f13c2014-04-23 16:59:28 -0700305 Initialize(ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation,
306 PointOfInstantiation, InstantiationRange,
307 Param, nullptr, TemplateArgs);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000308}
309
Stephen Hines651f13c2014-04-23 16:59:28 -0700310
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000311Sema::InstantiatingTemplate::
312InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000313 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
314 ArrayRef<TemplateArgument> TemplateArgs,
315 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700316 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000317{
Stephen Hines651f13c2014-04-23 16:59:28 -0700318 Initialize(ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
319 PointOfInstantiation, InstantiationRange,
320 Param, Template, TemplateArgs);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000321}
322
323Sema::InstantiatingTemplate::
324InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000325 NamedDecl *Template, TemplateTemplateParmDecl *Param,
326 ArrayRef<TemplateArgument> TemplateArgs,
327 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700328 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000329{
Stephen Hines651f13c2014-04-23 16:59:28 -0700330 Initialize(ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
331 PointOfInstantiation, InstantiationRange,
332 Param, Template, TemplateArgs);
Douglas Gregorf35f8282009-11-11 21:54:23 +0000333}
334
335Sema::InstantiatingTemplate::
336InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000337 TemplateDecl *Template, NamedDecl *Param,
338 ArrayRef<TemplateArgument> TemplateArgs,
339 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700340 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000341{
Stephen Hines651f13c2014-04-23 16:59:28 -0700342 Initialize(ActiveTemplateInstantiation::DefaultTemplateArgumentChecking,
343 PointOfInstantiation, InstantiationRange,
344 Param, Template, TemplateArgs);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000345}
346
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000347void Sema::InstantiatingTemplate::Clear() {
348 if (!Invalid) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000349 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
350 assert(SemaRef.NonInstantiationEntries > 0);
351 --SemaRef.NonInstantiationEntries;
352 }
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000353 SemaRef.InNonInstantiationSFINAEContext
354 = SavedInNonInstantiationSFINAEContext;
Richard Smithb7751002013-07-25 23:08:39 +0000355
356 // Name lookup no longer looks in this template's defining module.
357 assert(SemaRef.ActiveTemplateInstantiations.size() >=
358 SemaRef.ActiveTemplateInstantiationLookupModules.size() &&
359 "forgot to remove a lookup module for a template instantiation");
360 if (SemaRef.ActiveTemplateInstantiations.size() ==
361 SemaRef.ActiveTemplateInstantiationLookupModules.size()) {
362 if (Module *M = SemaRef.ActiveTemplateInstantiationLookupModules.back())
363 SemaRef.LookupModulesCache.erase(M);
364 SemaRef.ActiveTemplateInstantiationLookupModules.pop_back();
365 }
366
Douglas Gregor26dce442009-03-10 00:06:19 +0000367 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000368 Invalid = true;
369 }
Douglas Gregor26dce442009-03-10 00:06:19 +0000370}
371
Douglas Gregordf667e72009-03-10 20:44:00 +0000372bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
373 SourceLocation PointOfInstantiation,
374 SourceRange InstantiationRange) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000375 assert(SemaRef.NonInstantiationEntries <=
376 SemaRef.ActiveTemplateInstantiations.size());
377 if ((SemaRef.ActiveTemplateInstantiations.size() -
378 SemaRef.NonInstantiationEntries)
David Blaikie4e4d0842012-03-11 07:00:24 +0000379 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregordf667e72009-03-10 20:44:00 +0000380 return false;
381
Mike Stump1eb44332009-09-09 15:08:12 +0000382 SemaRef.Diag(PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000383 diag::err_template_recursion_depth_exceeded)
David Blaikie4e4d0842012-03-11 07:00:24 +0000384 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregordf667e72009-03-10 20:44:00 +0000385 << InstantiationRange;
386 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikie4e4d0842012-03-11 07:00:24 +0000387 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregordf667e72009-03-10 20:44:00 +0000388 return true;
389}
390
Douglas Gregoree1828a2009-03-10 18:03:33 +0000391/// \brief Prints the current instantiation stack through a series of
392/// notes.
393void Sema::PrintInstantiationStack() {
Douglas Gregor575cf372010-04-20 07:18:24 +0000394 // Determine which template instantiations to skip, if any.
395 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
396 unsigned Limit = Diags.getTemplateBacktraceLimit();
397 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
398 SkipStart = Limit / 2 + Limit % 2;
399 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
400 }
401
Douglas Gregorcca9e962009-07-01 22:01:06 +0000402 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregor575cf372010-04-20 07:18:24 +0000403 unsigned InstantiationIdx = 0;
Craig Topper09d19ef2013-07-04 03:08:24 +0000404 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
Douglas Gregoree1828a2009-03-10 18:03:33 +0000405 Active = ActiveTemplateInstantiations.rbegin(),
406 ActiveEnd = ActiveTemplateInstantiations.rend();
407 Active != ActiveEnd;
Douglas Gregor575cf372010-04-20 07:18:24 +0000408 ++Active, ++InstantiationIdx) {
409 // Skip this instantiation?
410 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
411 if (InstantiationIdx == SkipStart) {
412 // Note that we're skipping instantiations.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000413 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor575cf372010-04-20 07:18:24 +0000414 diag::note_instantiation_contexts_suppressed)
415 << unsigned(ActiveTemplateInstantiations.size() - Limit);
416 }
417 continue;
418 }
419
Douglas Gregordf667e72009-03-10 20:44:00 +0000420 switch (Active->Kind) {
421 case ActiveTemplateInstantiation::TemplateInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000422 Decl *D = Active->Entity;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000423 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
424 unsigned DiagID = diag::note_template_member_class_here;
425 if (isa<ClassTemplateSpecializationDecl>(Record))
426 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000427 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000428 << Context.getTypeDeclType(Record)
429 << Active->InstantiationRange;
Douglas Gregor7caa6822009-07-24 20:34:43 +0000430 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1637be72009-06-26 00:10:03 +0000431 unsigned DiagID;
432 if (Function->getPrimaryTemplate())
433 DiagID = diag::note_function_template_spec_here;
434 else
435 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000436 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000437 << Function
438 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000439 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000440 Diags.Report(Active->PointOfInstantiation,
Larisse Voufo933c66b2013-08-14 20:15:02 +0000441 VD->isStaticDataMember()?
442 diag::note_template_static_data_member_def_here
443 : diag::note_template_variable_def_here)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000444 << VD
445 << Active->InstantiationRange;
Richard Smithf1c66b42012-03-14 23:13:10 +0000446 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
447 Diags.Report(Active->PointOfInstantiation,
448 diag::note_template_enum_def_here)
449 << ED
450 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000451 } else {
452 Diags.Report(Active->PointOfInstantiation,
453 diag::note_template_type_alias_instantiation_here)
454 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregor7caa6822009-07-24 20:34:43 +0000455 << Active->InstantiationRange;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000456 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000457 break;
458 }
459
460 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000461 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
Benjamin Kramer5eada842013-02-22 15:46:01 +0000462 SmallVector<char, 128> TemplateArgsStr;
463 llvm::raw_svector_ostream OS(TemplateArgsStr);
464 Template->printName(OS);
465 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000466 Active->TemplateArgs,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000467 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000468 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000469 Diags.Report(Active->PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000470 diag::note_default_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000471 << OS.str()
Douglas Gregordf667e72009-03-10 20:44:00 +0000472 << Active->InstantiationRange;
473 break;
474 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000475
Douglas Gregorcca9e962009-07-01 22:01:06 +0000476 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000477 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000478 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000479 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000480 << FnTmpl
481 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
482 Active->TemplateArgs,
483 Active->NumTemplateArgs)
484 << Active->InstantiationRange;
Douglas Gregor637a4092009-06-10 23:47:09 +0000485 break;
486 }
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Douglas Gregorcca9e962009-07-01 22:01:06 +0000488 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000489 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
490 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000491 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000492 diag::note_partial_spec_deduct_instantiation_here)
493 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor5e402912010-03-30 20:35:20 +0000494 << getTemplateArgumentBindingsText(
495 PartialSpec->getTemplateParameters(),
496 Active->TemplateArgs,
497 Active->NumTemplateArgs)
Douglas Gregorcca9e962009-07-01 22:01:06 +0000498 << Active->InstantiationRange;
499 } else {
500 FunctionTemplateDecl *FnTmpl
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000501 = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000502 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000503 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000504 << FnTmpl
505 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
506 Active->TemplateArgs,
507 Active->NumTemplateArgs)
508 << Active->InstantiationRange;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000509 }
510 break;
Douglas Gregor637a4092009-06-10 23:47:09 +0000511
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000512 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000513 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000514 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Benjamin Kramer5eada842013-02-22 15:46:01 +0000516 SmallVector<char, 128> TemplateArgsStr;
517 llvm::raw_svector_ostream OS(TemplateArgsStr);
518 FD->printName(OS);
519 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000520 Active->TemplateArgs,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000521 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000522 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000523 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000524 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000525 << OS.str()
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000526 << Active->InstantiationRange;
527 break;
528 }
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000530 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000531 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000532 std::string Name;
533 if (!Parm->getName().empty())
534 Name = std::string(" '") + Parm->getName().str() + "'";
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700535
536 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000537 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
538 TemplateParams = Template->getTemplateParameters();
539 else
540 TemplateParams =
541 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
542 ->getTemplateParameters();
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000543 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000544 diag::note_prior_template_arg_substitution)
545 << isa<TemplateTemplateParmDecl>(Parm)
546 << Name
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000547 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000548 Active->TemplateArgs,
549 Active->NumTemplateArgs)
550 << Active->InstantiationRange;
551 break;
552 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000553
554 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700555 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000556 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
557 TemplateParams = Template->getTemplateParameters();
558 else
559 TemplateParams =
560 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
561 ->getTemplateParameters();
562
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000563 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000564 diag::note_template_default_arg_checking)
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000565 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000566 Active->TemplateArgs,
567 Active->NumTemplateArgs)
568 << Active->InstantiationRange;
569 break;
570 }
Richard Smithe6975e92012-04-17 00:58:00 +0000571
572 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
573 Diags.Report(Active->PointOfInstantiation,
574 diag::note_template_exception_spec_instantiation_here)
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000575 << cast<FunctionDecl>(Active->Entity)
Richard Smithe6975e92012-04-17 00:58:00 +0000576 << Active->InstantiationRange;
577 break;
Douglas Gregordf667e72009-03-10 20:44:00 +0000578 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000579 }
580}
581
David Blaikiedc84cd52013-02-20 22:23:23 +0000582Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000583 if (InNonInstantiationSFINAEContext)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700584 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000585
Craig Topper09d19ef2013-07-04 03:08:24 +0000586 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000587 Active = ActiveTemplateInstantiations.rbegin(),
588 ActiveEnd = ActiveTemplateInstantiations.rend();
589 Active != ActiveEnd;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000590 ++Active)
591 {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000592 switch(Active->Kind) {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000593 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smitha43ea642012-04-26 07:24:08 +0000594 // An instantiation of an alias template may or may not be a SFINAE
595 // context, depending on what else is on the stack.
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000596 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smitha43ea642012-04-26 07:24:08 +0000597 break;
598 // Fall through.
599 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000600 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorcca9e962009-07-01 22:01:06 +0000601 // This is a template instantiation, so there is no SFINAE.
David Blaikie66874fb2013-02-21 01:47:18 +0000602 return None;
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000604 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000605 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000606 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000607 // A default template argument instantiation and substitution into
608 // template parameters with arguments for prior parameters may or may
609 // not be a SFINAE context; look further up the stack.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000610 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000611
Douglas Gregorcca9e962009-07-01 22:01:06 +0000612 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
613 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
614 // We're either substitution explicitly-specified template arguments
615 // or deduced template arguments, so SFINAE applies.
Douglas Gregor9b623632010-10-12 23:32:35 +0000616 assert(Active->DeductionInfo && "Missing deduction info pointer");
617 return Active->DeductionInfo;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000618 }
619 }
620
David Blaikie66874fb2013-02-21 01:47:18 +0000621 return None;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000622}
623
Douglas Gregord3731192011-01-10 07:32:04 +0000624/// \brief Retrieve the depth and index of a parameter pack.
625static std::pair<unsigned, unsigned>
626getDepthAndIndex(NamedDecl *ND) {
627 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
628 return std::make_pair(TTP->getDepth(), TTP->getIndex());
629
630 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
631 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
632
633 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
634 return std::make_pair(TTP->getDepth(), TTP->getIndex());
635}
636
Douglas Gregor99ebf652009-02-27 19:31:52 +0000637//===----------------------------------------------------------------------===/
638// Template Instantiation for Types
639//===----------------------------------------------------------------------===/
Douglas Gregorcd281c32009-02-28 00:25:32 +0000640namespace {
Douglas Gregor895162d2010-04-30 18:55:50 +0000641 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000642 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000643 SourceLocation Loc;
644 DeclarationName Entity;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000645
Douglas Gregorcd281c32009-02-28 00:25:32 +0000646 public:
Douglas Gregor43959a92009-08-20 07:17:43 +0000647 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump1eb44332009-09-09 15:08:12 +0000648
649 TemplateInstantiator(Sema &SemaRef,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000650 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor577f75a2009-08-04 16:50:30 +0000651 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000652 DeclarationName Entity)
653 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregor43959a92009-08-20 07:17:43 +0000654 Entity(Entity) { }
Douglas Gregorcd281c32009-02-28 00:25:32 +0000655
Mike Stump1eb44332009-09-09 15:08:12 +0000656 /// \brief Determine whether the given type \p T has already been
Douglas Gregor577f75a2009-08-04 16:50:30 +0000657 /// transformed.
658 ///
659 /// For the purposes of template instantiation, a type has already been
660 /// transformed if it is NULL or if it is not dependent.
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000661 bool AlreadyTransformed(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Douglas Gregor577f75a2009-08-04 16:50:30 +0000663 /// \brief Returns the location of the entity being instantiated, if known.
664 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +0000665
Douglas Gregor577f75a2009-08-04 16:50:30 +0000666 /// \brief Returns the name of the entity being instantiated, if any.
667 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Douglas Gregor972e6ce2009-10-27 06:26:26 +0000669 /// \brief Sets the "base" location and entity when that
670 /// information is known based on another transformation.
671 void setBase(SourceLocation Loc, DeclarationName Entity) {
672 this->Loc = Loc;
673 this->Entity = Entity;
674 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000675
676 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
677 SourceRange PatternRange,
Robert Wilhelm834c0582013-08-09 18:02:13 +0000678 ArrayRef<UnexpandedParameterPack> Unexpanded,
679 bool &ShouldExpand, bool &RetainExpansion,
David Blaikiedc84cd52013-02-20 22:23:23 +0000680 Optional<unsigned> &NumExpansions) {
Douglas Gregorb99268b2010-12-21 00:52:54 +0000681 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
682 PatternRange, Unexpanded,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000683 TemplateArgs,
684 ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000685 RetainExpansion,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000686 NumExpansions);
687 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000688
Douglas Gregor12c9c002011-01-07 16:43:16 +0000689 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
690 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
691 }
692
Douglas Gregord3731192011-01-10 07:32:04 +0000693 TemplateArgument ForgetPartiallySubstitutedPack() {
694 TemplateArgument Result;
695 if (NamedDecl *PartialPack
696 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
697 MultiLevelTemplateArgumentList &TemplateArgs
698 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
699 unsigned Depth, Index;
Stephen Hines651f13c2014-04-23 16:59:28 -0700700 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregord3731192011-01-10 07:32:04 +0000701 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
702 Result = TemplateArgs(Depth, Index);
703 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
704 }
705 }
706
707 return Result;
708 }
709
710 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
711 if (Arg.isNull())
712 return;
713
714 if (NamedDecl *PartialPack
715 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
716 MultiLevelTemplateArgumentList &TemplateArgs
717 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
718 unsigned Depth, Index;
Stephen Hines651f13c2014-04-23 16:59:28 -0700719 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregord3731192011-01-10 07:32:04 +0000720 TemplateArgs.setArgument(Depth, Index, Arg);
721 }
722 }
723
Douglas Gregor577f75a2009-08-04 16:50:30 +0000724 /// \brief Transform the given declaration by instantiating a reference to
725 /// this declaration.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000726 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregorb98b1992009-08-11 05:31:07 +0000727
Douglas Gregordfca6f52012-02-13 22:00:16 +0000728 void transformAttrs(Decl *Old, Decl *New) {
729 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
730 }
731
732 void transformedLocalDecl(Decl *Old, Decl *New) {
733 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
734 }
735
Mike Stump1eb44332009-09-09 15:08:12 +0000736 /// \brief Transform the definition of the given declaration by
Douglas Gregor43959a92009-08-20 07:17:43 +0000737 /// instantiating it.
Douglas Gregoraac571c2010-03-01 17:25:41 +0000738 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Dmitri Gribenkoe23fb902012-09-12 17:01:48 +0000740 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregor6cd21982009-10-20 05:58:46 +0000741 /// declaration.
742 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
743
Douglas Gregor43959a92009-08-20 07:17:43 +0000744 /// \brief Rebuild the exception declaration and register the declaration
745 /// as an instantiated local.
Douglas Gregor83cb9422010-09-09 17:09:21 +0000746 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000747 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000748 SourceLocation StartLoc,
749 SourceLocation NameLoc,
750 IdentifierInfo *Name);
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Douglas Gregorbe270a02010-04-26 17:57:08 +0000752 /// \brief Rebuild the Objective-C exception declaration and register the
753 /// declaration as an instantiated local.
754 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
755 TypeSourceInfo *TSInfo, QualType T);
756
John McCallc4e70192009-09-11 04:59:25 +0000757 /// \brief Check for tag mismatches when instantiating an
758 /// elaborated type.
John McCall21e413f2010-11-04 19:04:38 +0000759 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
760 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000761 NestedNameSpecifierLoc QualifierLoc,
762 QualType T);
John McCallc4e70192009-09-11 04:59:25 +0000763
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700764 TemplateName
765 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
766 SourceLocation NameLoc,
767 QualType ObjectType = QualType(),
768 NamedDecl *FirstQualifierInScope = nullptr);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000769
John McCall60d7b3a2010-08-24 06:29:42 +0000770 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
771 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
772 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000773
John McCall60d7b3a2010-08-24 06:29:42 +0000774 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor56bc9832010-12-24 00:15:10 +0000775 NonTypeTemplateParmDecl *D);
Douglas Gregorc7793c72011-01-15 01:15:58 +0000776 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
777 SubstNonTypeTemplateParmPackExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000778
779 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
780 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
781
782 /// \brief Transform a reference to a function parameter pack.
783 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
784 ParmVarDecl *PD);
785
786 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
787 /// expand a function parameter pack reference which refers to an expanded
788 /// pack.
789 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
790
Douglas Gregor895162d2010-04-30 18:55:50 +0000791 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000792 FunctionProtoTypeLoc TL);
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000793 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
794 FunctionProtoTypeLoc TL,
795 CXXRecordDecl *ThisContext,
796 unsigned ThisTypeQuals);
797
Douglas Gregor6a24bfd2011-01-14 22:40:04 +0000798 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +0000799 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +0000800 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +0000801 bool ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +0000802
Mike Stump1eb44332009-09-09 15:08:12 +0000803 /// \brief Transforms a template type parameter type by performing
Douglas Gregor577f75a2009-08-04 16:50:30 +0000804 /// substitution of the corresponding template type argument.
John McCalla2becad2009-10-21 00:40:46 +0000805 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000806 TemplateTypeParmTypeLoc TL);
Nick Lewycky03d98c52010-07-06 19:51:49 +0000807
Douglas Gregorc3069d62011-01-14 02:55:32 +0000808 /// \brief Transforms an already-substituted template type parameter pack
809 /// into either itself (if we aren't substituting into its pack expansion)
810 /// or the appropriate substituted argument.
811 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
812 SubstTemplateTypeParmPackTypeLoc TL);
813
John McCall60d7b3a2010-08-24 06:29:42 +0000814 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewycky03d98c52010-07-06 19:51:49 +0000815 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCall60d7b3a2010-08-24 06:29:42 +0000816 ExprResult Result =
Nick Lewycky03d98c52010-07-06 19:51:49 +0000817 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
818 getSema().CallsUndergoingInstantiation.pop_back();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000819 return Result;
Nick Lewycky03d98c52010-07-06 19:51:49 +0000820 }
John McCall91a57552011-07-15 05:09:51 +0000821
Richard Smith612409e2012-07-25 03:56:55 +0000822 ExprResult TransformLambdaExpr(LambdaExpr *E) {
823 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
824 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
825 }
826
827 ExprResult TransformLambdaScope(LambdaExpr *E,
Bill Wendling2434dcf2013-12-05 05:25:04 +0000828 CXXMethodDecl *NewCallOperator,
829 ArrayRef<InitCaptureInfoTy> InitCaptureExprsAndTypes) {
Faisal Valia3d311e2013-10-23 06:44:28 +0000830 CXXMethodDecl *const OldCallOperator = E->getCallOperator();
831 // In the generic lambda case, we set the NewTemplate to be considered
832 // an "instantiation" of the OldTemplate.
833 if (FunctionTemplateDecl *const NewCallOperatorTemplate =
834 NewCallOperator->getDescribedFunctionTemplate()) {
835
836 FunctionTemplateDecl *const OldCallOperatorTemplate =
837 OldCallOperator->getDescribedFunctionTemplate();
838 NewCallOperatorTemplate->setInstantiatedFromMemberTemplate(
839 OldCallOperatorTemplate);
Faisal Valia3d311e2013-10-23 06:44:28 +0000840 } else
841 // For a non-generic lambda we set the NewCallOperator to
842 // be an instantiation of the OldCallOperator.
843 NewCallOperator->setInstantiationOfMemberFunction(OldCallOperator,
844 TSK_ImplicitInstantiation);
845
Bill Wendling2434dcf2013-12-05 05:25:04 +0000846 return inherited::TransformLambdaScope(E, NewCallOperator,
847 InitCaptureExprsAndTypes);
Rafael Espindolaf003acd2013-10-04 14:28:51 +0000848 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700849 TemplateParameterList *TransformTemplateParameterList(
Faisal Valia3d311e2013-10-23 06:44:28 +0000850 TemplateParameterList *OrigTPL) {
851 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
852
853 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
854 TemplateDeclInstantiator DeclInstantiator(getSema(),
855 /* DeclContext *Owner */ Owner, TemplateArgs);
856 return DeclInstantiator.SubstTemplateParams(OrigTPL);
857 }
John McCall91a57552011-07-15 05:09:51 +0000858 private:
859 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
860 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +0000861 TemplateArgument arg);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000862 };
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000863}
864
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000865bool TemplateInstantiator::AlreadyTransformed(QualType T) {
866 if (T.isNull())
867 return true;
868
Douglas Gregor561f8122011-07-01 01:22:09 +0000869 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000870 return false;
871
872 getSema().MarkDeclarationsReferencedInType(Loc, T);
873 return true;
874}
875
Eli Friedman10ec0e42013-07-19 19:40:38 +0000876static TemplateArgument
877getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
878 assert(S.ArgumentPackSubstitutionIndex >= 0);
879 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
880 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
881 if (Arg.isPackExpansion())
882 Arg = Arg.getPackExpansionPattern();
883 return Arg;
884}
885
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000886Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregorc68afe22009-09-03 21:38:09 +0000887 if (!D)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700888 return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Douglas Gregorc68afe22009-09-03 21:38:09 +0000890 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000891 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor6d3e6272010-02-05 19:54:12 +0000892 // If the corresponding template argument is NULL or non-existent, it's
893 // because we are performing instantiation from explicitly-specified
894 // template arguments in a function template, but there were some
895 // arguments left unspecified.
896 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
897 TTP->getPosition()))
898 return D;
899
Douglas Gregor61c4d282011-01-05 15:48:55 +0000900 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
901
902 if (TTP->isParameterPack()) {
903 assert(Arg.getKind() == TemplateArgument::Pack &&
904 "Missing argument pack");
Eli Friedman10ec0e42013-07-19 19:40:38 +0000905 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000906 }
907
908 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor788cd062009-11-11 01:00:40 +0000909 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregord6350ae2009-08-28 20:31:08 +0000910 "Wrong kind of template template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000911 return Template.getAsTemplateDecl();
Douglas Gregord6350ae2009-08-28 20:31:08 +0000912 }
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Douglas Gregor788cd062009-11-11 01:00:40 +0000914 // Fall through to find the instantiated declaration for this template
915 // template parameter.
Douglas Gregord1067e52009-08-06 06:41:21 +0000916 }
Mike Stump1eb44332009-09-09 15:08:12 +0000917
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000918 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000919}
920
Douglas Gregoraac571c2010-03-01 17:25:41 +0000921Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000922 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregor43959a92009-08-20 07:17:43 +0000923 if (!Inst)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700924 return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Douglas Gregor43959a92009-08-20 07:17:43 +0000926 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
927 return Inst;
928}
929
Douglas Gregor6cd21982009-10-20 05:58:46 +0000930NamedDecl *
931TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
932 SourceLocation Loc) {
933 // If the first part of the nested-name-specifier was a template type
934 // parameter, instantiate that type parameter down to a tag type.
935 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
936 const TemplateTypeParmType *TTP
937 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor984a58b2010-12-20 22:48:17 +0000938
Douglas Gregor6cd21982009-10-20 05:58:46 +0000939 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor984a58b2010-12-20 22:48:17 +0000940 // FIXME: This needs testing w/ member access expressions.
941 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
942
943 if (TTP->isParameterPack()) {
944 assert(Arg.getKind() == TemplateArgument::Pack &&
945 "Missing argument pack");
946
Douglas Gregor2be29f42011-01-14 23:41:42 +0000947 if (getSema().ArgumentPackSubstitutionIndex == -1)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700948 return nullptr;
949
Eli Friedman10ec0e42013-07-19 19:40:38 +0000950 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor984a58b2010-12-20 22:48:17 +0000951 }
952
953 QualType T = Arg.getAsType();
Douglas Gregor6cd21982009-10-20 05:58:46 +0000954 if (T.isNull())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000955 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000956
957 if (const TagType *Tag = T->getAs<TagType>())
958 return Tag->getDecl();
959
960 // The resulting type is not a tag; complain.
961 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700962 return nullptr;
Douglas Gregor6cd21982009-10-20 05:58:46 +0000963 }
964 }
965
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000966 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000967}
968
Douglas Gregor43959a92009-08-20 07:17:43 +0000969VarDecl *
970TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000971 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000972 SourceLocation StartLoc,
973 SourceLocation NameLoc,
974 IdentifierInfo *Name) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000975 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000976 StartLoc, NameLoc, Name);
Douglas Gregorbe270a02010-04-26 17:57:08 +0000977 if (Var)
978 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
979 return Var;
980}
981
982VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
983 TypeSourceInfo *TSInfo,
984 QualType T) {
985 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
986 if (Var)
Douglas Gregor43959a92009-08-20 07:17:43 +0000987 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
988 return Var;
989}
990
John McCallc4e70192009-09-11 04:59:25 +0000991QualType
John McCall21e413f2010-11-04 19:04:38 +0000992TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
993 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000994 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000995 QualType T) {
John McCallc4e70192009-09-11 04:59:25 +0000996 if (const TagType *TT = T->getAs<TagType>()) {
997 TagDecl* TD = TT->getDecl();
998
John McCall21e413f2010-11-04 19:04:38 +0000999 SourceLocation TagLocation = KeywordLoc;
John McCallc4e70192009-09-11 04:59:25 +00001000
John McCallc4e70192009-09-11 04:59:25 +00001001 IdentifierInfo *Id = TD->getIdentifier();
1002
1003 // TODO: should we even warn on struct/class mismatches for this? Seems
1004 // like it's likely to produce a lot of spurious errors.
Richard Smithcbf97c52012-08-17 00:12:27 +00001005 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001006 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieubbf34c02011-06-10 03:11:26 +00001007 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1008 TagLocation, *Id)) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001009 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1010 << Id
1011 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1012 TD->getKindName());
1013 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1014 }
John McCallc4e70192009-09-11 04:59:25 +00001015 }
1016 }
1017
John McCall21e413f2010-11-04 19:04:38 +00001018 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1019 Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +00001020 QualifierLoc,
1021 T);
John McCallc4e70192009-09-11 04:59:25 +00001022}
1023
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001024TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1025 TemplateName Name,
1026 SourceLocation NameLoc,
1027 QualType ObjectType,
1028 NamedDecl *FirstQualifierInScope) {
1029 if (TemplateTemplateParmDecl *TTP
1030 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1031 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1032 // If the corresponding template argument is NULL or non-existent, it's
1033 // because we are performing instantiation from explicitly-specified
1034 // template arguments in a function template, but there were some
1035 // arguments left unspecified.
1036 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1037 TTP->getPosition()))
1038 return Name;
1039
1040 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1041
1042 if (TTP->isParameterPack()) {
1043 assert(Arg.getKind() == TemplateArgument::Pack &&
1044 "Missing argument pack");
1045
1046 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1047 // We have the template argument pack to substitute, but we're not
1048 // actually expanding the enclosing pack expansion yet. So, just
1049 // keep the entire argument pack.
1050 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1051 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001052
1053 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001054 }
1055
1056 TemplateName Template = Arg.getAsTemplate();
Richard Smith3e4c6c42011-05-05 21:57:07 +00001057 assert(!Template.isNull() && "Null template template argument");
John McCall14606042011-06-30 08:33:18 +00001058
Douglas Gregor58750382011-03-05 20:06:51 +00001059 // We don't ever want to substitute for a qualified template name, since
1060 // the qualifier is handled separately. So, look through the qualified
1061 // template name to its underlying declaration.
1062 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1063 Template = TemplateName(QTN->getTemplateDecl());
John McCall14606042011-06-30 08:33:18 +00001064
1065 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001066 return Template;
1067 }
1068 }
1069
1070 if (SubstTemplateTemplateParmPackStorage *SubstPack
1071 = Name.getAsSubstTemplateTemplateParmPack()) {
1072 if (getSema().ArgumentPackSubstitutionIndex == -1)
1073 return Name;
1074
Eli Friedman10ec0e42013-07-19 19:40:38 +00001075 TemplateArgument Arg = SubstPack->getArgumentPack();
1076 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1077 return Arg.getAsTemplate();
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001078 }
1079
1080 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1081 FirstQualifierInScope);
1082}
1083
John McCall60d7b3a2010-08-24 06:29:42 +00001084ExprResult
John McCall454feb92009-12-08 09:21:05 +00001085TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson773f3972009-09-11 01:22:35 +00001086 if (!E->isTypeDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00001087 return SemaRef.Owned(E);
Anders Carlsson773f3972009-09-11 01:22:35 +00001088
Wei Pan33129332013-09-16 13:57:27 +00001089 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
Anders Carlsson773f3972009-09-11 01:22:35 +00001090}
1091
John McCall60d7b3a2010-08-24 06:29:42 +00001092ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001093TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregordcee9802010-02-08 23:41:45 +00001094 NonTypeTemplateParmDecl *NTTP) {
John McCallb8fc0532010-02-06 08:42:39 +00001095 // If the corresponding template argument is NULL or non-existent, it's
1096 // because we are performing instantiation from explicitly-specified
1097 // template arguments in a function template, but there were some
1098 // arguments left unspecified.
1099 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1100 NTTP->getPosition()))
John McCall3fa5cae2010-10-26 07:05:15 +00001101 return SemaRef.Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001102
Douglas Gregor56bc9832010-12-24 00:15:10 +00001103 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1104 if (NTTP->isParameterPack()) {
1105 assert(Arg.getKind() == TemplateArgument::Pack &&
1106 "Missing argument pack");
1107
1108 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc7793c72011-01-15 01:15:58 +00001109 // We have an argument pack, but we can't select a particular argument
1110 // out of it yet. Therefore, we'll build an expression to hold on to that
1111 // argument pack.
1112 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1113 E->getLocation(),
1114 NTTP->getDeclName());
1115 if (TargetType.isNull())
1116 return ExprError();
1117
1118 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1119 NTTP,
1120 E->getLocation(),
1121 Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001122 }
1123
Eli Friedman10ec0e42013-07-19 19:40:38 +00001124 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001125 }
Mike Stump1eb44332009-09-09 15:08:12 +00001126
John McCall91a57552011-07-15 05:09:51 +00001127 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1128}
1129
1130ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1131 NonTypeTemplateParmDecl *parm,
1132 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +00001133 TemplateArgument arg) {
John McCall91a57552011-07-15 05:09:51 +00001134 ExprResult result;
1135 QualType type;
1136
John McCallb8fc0532010-02-06 08:42:39 +00001137 // The template argument itself might be an expression, in which
1138 // case we just return that expression.
John McCall91a57552011-07-15 05:09:51 +00001139 if (arg.getKind() == TemplateArgument::Expression) {
1140 Expr *argExpr = arg.getAsExpr();
1141 result = SemaRef.Owned(argExpr);
1142 type = argExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Eli Friedmand7a6b162012-09-26 02:36:12 +00001144 } else if (arg.getKind() == TemplateArgument::Declaration ||
1145 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregord2008e22012-04-06 22:40:38 +00001146 ValueDecl *VD;
Eli Friedmand7a6b162012-09-26 02:36:12 +00001147 if (arg.getKind() == TemplateArgument::Declaration) {
1148 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Douglas Gregord2008e22012-04-06 22:40:38 +00001150 // Find the instantiation of the template argument. This is
1151 // required for nested templates.
1152 VD = cast_or_null<ValueDecl>(
1153 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1154 if (!VD)
1155 return ExprError();
1156 } else {
1157 // Propagate NULL template argument.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001158 VD = nullptr;
Douglas Gregord2008e22012-04-06 22:40:38 +00001159 }
1160
John McCall645cf442010-02-06 10:23:53 +00001161 // Derive the type we want the substituted decl to have. This had
1162 // better be non-dependent, or these checks will have serious problems.
John McCall91a57552011-07-15 05:09:51 +00001163 if (parm->isExpandedParameterPack()) {
1164 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1165 } else if (parm->isParameterPack() &&
1166 isa<PackExpansionType>(parm->getType())) {
1167 type = SemaRef.SubstType(
1168 cast<PackExpansionType>(parm->getType())->getPattern(),
1169 TemplateArgs, loc, parm->getDeclName());
1170 } else {
1171 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1172 loc, parm->getDeclName());
1173 }
1174 assert(!type.isNull() && "type substitution failed for param type");
1175 assert(!type->isDependentType() && "param type still dependent");
1176 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCallb8fc0532010-02-06 08:42:39 +00001177
John McCall91a57552011-07-15 05:09:51 +00001178 if (!result.isInvalid()) type = result.get()->getType();
1179 } else {
1180 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1181
1182 // Note that this type can be different from the type of 'result',
1183 // e.g. if it's an enum type.
1184 type = arg.getIntegralType();
1185 }
1186 if (result.isInvalid()) return ExprError();
1187
1188 Expr *resultExpr = result.take();
1189 return SemaRef.Owned(new (SemaRef.Context)
1190 SubstNonTypeTemplateParmExpr(type,
1191 resultExpr->getValueKind(),
1192 loc, parm, resultExpr));
John McCallb8fc0532010-02-06 08:42:39 +00001193}
1194
Douglas Gregorc7793c72011-01-15 01:15:58 +00001195ExprResult
1196TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1197 SubstNonTypeTemplateParmPackExpr *E) {
1198 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1199 // We aren't expanding the parameter pack, so just return ourselves.
1200 return getSema().Owned(E);
1201 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001202
1203 TemplateArgument Arg = E->getArgumentPack();
1204 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall91a57552011-07-15 05:09:51 +00001205 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1206 E->getParameterPackLocation(),
1207 Arg);
Douglas Gregorc7793c72011-01-15 01:15:58 +00001208}
John McCallb8fc0532010-02-06 08:42:39 +00001209
John McCall60d7b3a2010-08-24 06:29:42 +00001210ExprResult
Richard Smith9a4db032012-09-12 00:56:43 +00001211TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1212 SourceLocation Loc) {
1213 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1214 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1215}
1216
1217ExprResult
1218TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1219 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1220 // We can expand this parameter pack now.
1221 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1222 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1223 if (!VD)
1224 return ExprError();
1225 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1226 }
1227
1228 QualType T = TransformType(E->getType());
1229 if (T.isNull())
1230 return ExprError();
1231
1232 // Transform each of the parameter expansions into the corresponding
1233 // parameters in the instantiation of the function decl.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001234 SmallVector<Decl *, 8> Parms;
Richard Smith9a4db032012-09-12 00:56:43 +00001235 Parms.reserve(E->getNumExpansions());
1236 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1237 I != End; ++I) {
1238 ParmVarDecl *D =
1239 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1240 if (!D)
1241 return ExprError();
1242 Parms.push_back(D);
1243 }
1244
1245 return FunctionParmPackExpr::Create(getSema().Context, T,
1246 E->getParameterPack(),
1247 E->getParameterPackLocation(), Parms);
1248}
1249
1250ExprResult
1251TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1252 ParmVarDecl *PD) {
1253 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1254 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1255 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1256 assert(Found && "no instantiation for parameter pack");
1257
1258 Decl *TransformedDecl;
1259 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1260 // If this is a reference to a function parameter pack which we can substitute
1261 // but can't yet expand, build a FunctionParmPackExpr for it.
1262 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1263 QualType T = TransformType(E->getType());
1264 if (T.isNull())
1265 return ExprError();
1266 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1267 E->getExprLoc(), *Pack);
1268 }
1269
1270 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1271 } else {
1272 TransformedDecl = Found->get<Decl*>();
1273 }
1274
1275 // We have either an unexpanded pack or a specific expansion.
1276 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1277 E->getExprLoc());
1278}
1279
1280ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001281TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1282 NamedDecl *D = E->getDecl();
Richard Smith9a4db032012-09-12 00:56:43 +00001283
1284 // Handle references to non-type template parameters and non-type template
1285 // parameter packs.
John McCallb8fc0532010-02-06 08:42:39 +00001286 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1287 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1288 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001289
1290 // We have a non-type template parameter that isn't fully substituted;
1291 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregorb98b1992009-08-11 05:31:07 +00001292 }
Mike Stump1eb44332009-09-09 15:08:12 +00001293
Richard Smith9a4db032012-09-12 00:56:43 +00001294 // Handle references to function parameter packs.
1295 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1296 if (PD->isParameterPack())
1297 return TransformFunctionParmPackRefExpr(E, PD);
1298
John McCall454feb92009-12-08 09:21:05 +00001299 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregorb98b1992009-08-11 05:31:07 +00001300}
1301
John McCall60d7b3a2010-08-24 06:29:42 +00001302ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall454feb92009-12-08 09:21:05 +00001303 CXXDefaultArgExpr *E) {
Sebastian Redla29e51b2009-11-08 13:56:19 +00001304 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1305 getDescribedFunctionTemplate() &&
1306 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor036aed12009-12-23 23:03:06 +00001307 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1308 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1309 E->getParam());
Sebastian Redla29e51b2009-11-08 13:56:19 +00001310}
1311
Douglas Gregor895162d2010-04-30 18:55:50 +00001312QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001313 FunctionProtoTypeLoc TL) {
Douglas Gregor895162d2010-04-30 18:55:50 +00001314 // We need a local instantiation scope for this function prototype.
John McCall2a7fb272010-08-25 05:32:35 +00001315 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
John McCall43fed0d2010-11-12 08:19:04 +00001316 return inherited::TransformFunctionProtoType(TLB, TL);
John McCall21ef0fa2010-03-11 09:03:00 +00001317}
1318
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001319QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1320 FunctionProtoTypeLoc TL,
1321 CXXRecordDecl *ThisContext,
1322 unsigned ThisTypeQuals) {
1323 // We need a local instantiation scope for this function prototype.
1324 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1325 return inherited::TransformFunctionProtoType(TLB, TL, ThisContext,
1326 ThisTypeQuals);
1327}
1328
John McCall21ef0fa2010-03-11 09:03:00 +00001329ParmVarDecl *
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001330TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +00001331 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001332 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001333 bool ExpectParameterPack) {
John McCallfb44de92011-05-01 22:35:37 +00001334 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001335 NumExpansions, ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +00001336}
1337
Mike Stump1eb44332009-09-09 15:08:12 +00001338QualType
John McCalla2becad2009-10-21 00:40:46 +00001339TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001340 TemplateTypeParmTypeLoc TL) {
John McCallf4c73712011-01-19 06:33:43 +00001341 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001342 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor99ebf652009-02-27 19:31:52 +00001343 // Replace the template type parameter with its corresponding
1344 // template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00001345
1346 // If the corresponding template argument is NULL or doesn't exist, it's
1347 // because we are performing instantiation from explicitly-specified
1348 // template arguments in a function template class, but there were some
Douglas Gregor16134c62009-07-01 00:28:38 +00001349 // arguments left unspecified.
John McCalla2becad2009-10-21 00:40:46 +00001350 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1351 TemplateTypeParmTypeLoc NewTL
1352 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1353 NewTL.setNameLoc(TL.getNameLoc());
1354 return TL.getType();
1355 }
Mike Stump1eb44332009-09-09 15:08:12 +00001356
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001357 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1358
1359 if (T->isParameterPack()) {
1360 assert(Arg.getKind() == TemplateArgument::Pack &&
1361 "Missing argument pack");
1362
1363 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc3069d62011-01-14 02:55:32 +00001364 // We have the template argument pack, but we're not expanding the
1365 // enclosing pack expansion yet. Just save the template argument
1366 // pack for later substitution.
1367 QualType Result
1368 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1369 SubstTemplateTypeParmPackTypeLoc NewTL
1370 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1371 NewTL.setNameLoc(TL.getNameLoc());
1372 return Result;
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001373 }
1374
Eli Friedman10ec0e42013-07-19 19:40:38 +00001375 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001376 }
1377
1378 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregor99ebf652009-02-27 19:31:52 +00001379 "Template argument kind mismatch");
Douglas Gregord6350ae2009-08-28 20:31:08 +00001380
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001381 QualType Replacement = Arg.getAsType();
John McCall49a832b2009-10-18 09:09:24 +00001382
1383 // TODO: only do this uniquing once, at the start of instantiation.
John McCalla2becad2009-10-21 00:40:46 +00001384 QualType Result
1385 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1386 SubstTemplateTypeParmTypeLoc NewTL
1387 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1388 NewTL.setNameLoc(TL.getNameLoc());
1389 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001390 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001391
1392 // The template type parameter comes from an inner template (e.g.,
1393 // the template parameter list of a member template inside the
1394 // template we are instantiating). Create a new template type
1395 // parameter with the template "level" reduced by one.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001396 TemplateTypeParmDecl *NewTTPDecl = nullptr;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001397 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1398 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1399 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1400
John McCalla2becad2009-10-21 00:40:46 +00001401 QualType Result
1402 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1403 - TemplateArgs.getNumLevels(),
1404 T->getIndex(),
1405 T->isParameterPack(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001406 NewTTPDecl);
John McCalla2becad2009-10-21 00:40:46 +00001407 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1408 NewTL.setNameLoc(TL.getNameLoc());
1409 return Result;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001410}
Douglas Gregor99ebf652009-02-27 19:31:52 +00001411
Douglas Gregorc3069d62011-01-14 02:55:32 +00001412QualType
1413TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1414 TypeLocBuilder &TLB,
1415 SubstTemplateTypeParmPackTypeLoc TL) {
1416 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1417 // We aren't expanding the parameter pack, so just return ourselves.
1418 SubstTemplateTypeParmPackTypeLoc NewTL
1419 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1420 NewTL.setNameLoc(TL.getNameLoc());
1421 return TL.getType();
1422 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001423
1424 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1425 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1426 QualType Result = Arg.getAsType();
1427
Douglas Gregorc3069d62011-01-14 02:55:32 +00001428 Result = getSema().Context.getSubstTemplateTypeParmType(
1429 TL.getTypePtr()->getReplacedParameter(),
1430 Result);
1431 SubstTemplateTypeParmTypeLoc NewTL
1432 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1433 NewTL.setNameLoc(TL.getNameLoc());
1434 return Result;
1435}
1436
John McCallce3ff2b2009-08-25 22:02:44 +00001437/// \brief Perform substitution on the type T with a given set of template
1438/// arguments.
Douglas Gregor99ebf652009-02-27 19:31:52 +00001439///
1440/// This routine substitutes the given template arguments into the
1441/// type T and produces the instantiated type.
1442///
1443/// \param T the type into which the template arguments will be
1444/// substituted. If this type is not dependent, it will be returned
1445/// immediately.
1446///
James Dennett1dfbd922012-06-14 21:40:34 +00001447/// \param Args the template arguments that will be
Douglas Gregor99ebf652009-02-27 19:31:52 +00001448/// substituted for the top-level template parameters within T.
1449///
Douglas Gregor99ebf652009-02-27 19:31:52 +00001450/// \param Loc the location in the source code where this substitution
1451/// is being performed. It will typically be the location of the
1452/// declarator (if we're instantiating the type of some declaration)
1453/// or the location of the type in the source code (if, e.g., we're
1454/// instantiating the type of a cast expression).
1455///
1456/// \param Entity the name of the entity associated with a declaration
1457/// being instantiated (if any). May be empty to indicate that there
1458/// is no such entity (if, e.g., this is a type that occurs as part of
1459/// a cast expression) or that the entity has no name (e.g., an
1460/// unnamed function parameter).
1461///
1462/// \returns If the instantiation succeeds, the instantiated
1463/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCalla93c9342009-12-07 02:54:59 +00001464TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCallcd7ba1c2009-10-21 00:58:09 +00001465 const MultiLevelTemplateArgumentList &Args,
1466 SourceLocation Loc,
1467 DeclarationName Entity) {
1468 assert(!ActiveTemplateInstantiations.empty() &&
1469 "Cannot perform an instantiation without some context on the "
1470 "instantiation stack");
1471
Douglas Gregor561f8122011-07-01 01:22:09 +00001472 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor836adf62010-05-24 17:22:01 +00001473 !T->getType()->isVariablyModifiedType())
John McCallcd7ba1c2009-10-21 00:58:09 +00001474 return T;
1475
1476 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1477 return Instantiator.TransformType(T);
1478}
1479
Douglas Gregor603cfb42011-01-05 23:12:31 +00001480TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1481 const MultiLevelTemplateArgumentList &Args,
1482 SourceLocation Loc,
1483 DeclarationName Entity) {
1484 assert(!ActiveTemplateInstantiations.empty() &&
1485 "Cannot perform an instantiation without some context on the "
1486 "instantiation stack");
1487
1488 if (TL.getType().isNull())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001489 return nullptr;
Douglas Gregor603cfb42011-01-05 23:12:31 +00001490
Douglas Gregor561f8122011-07-01 01:22:09 +00001491 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor603cfb42011-01-05 23:12:31 +00001492 !TL.getType()->isVariablyModifiedType()) {
1493 // FIXME: Make a copy of the TypeLoc data here, so that we can
1494 // return a new TypeSourceInfo. Inefficient!
1495 TypeLocBuilder TLB;
1496 TLB.pushFullCopy(TL);
1497 return TLB.getTypeSourceInfo(Context, TL.getType());
1498 }
1499
1500 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1501 TypeLocBuilder TLB;
1502 TLB.reserve(TL.getFullDataSize());
1503 QualType Result = Instantiator.TransformType(TLB, TL);
1504 if (Result.isNull())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001505 return nullptr;
Douglas Gregor603cfb42011-01-05 23:12:31 +00001506
1507 return TLB.getTypeSourceInfo(Context, Result);
1508}
1509
John McCallcd7ba1c2009-10-21 00:58:09 +00001510/// Deprecated form of the above.
Mike Stump1eb44332009-09-09 15:08:12 +00001511QualType Sema::SubstType(QualType T,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001512 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallce3ff2b2009-08-25 22:02:44 +00001513 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregordf667e72009-03-10 20:44:00 +00001514 assert(!ActiveTemplateInstantiations.empty() &&
1515 "Cannot perform an instantiation without some context on the "
1516 "instantiation stack");
1517
Douglas Gregor836adf62010-05-24 17:22:01 +00001518 // If T is not a dependent type or a variably-modified type, there
1519 // is nothing to do.
Douglas Gregor561f8122011-07-01 01:22:09 +00001520 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregor99ebf652009-02-27 19:31:52 +00001521 return T;
1522
Douglas Gregor577f75a2009-08-04 16:50:30 +00001523 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1524 return Instantiator.TransformType(T);
Douglas Gregor99ebf652009-02-27 19:31:52 +00001525}
Douglas Gregor2943aed2009-03-03 04:44:36 +00001526
John McCall6cd3b9f2010-04-09 17:38:44 +00001527static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor561f8122011-07-01 01:22:09 +00001528 if (T->getType()->isInstantiationDependentType() ||
1529 T->getType()->isVariablyModifiedType())
John McCall6cd3b9f2010-04-09 17:38:44 +00001530 return true;
1531
Abramo Bagnara723df242010-12-14 22:11:44 +00001532 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00001533 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCall6cd3b9f2010-04-09 17:38:44 +00001534 return false;
1535
David Blaikie39e6ab42013-02-18 22:06:02 +00001536 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Stephen Hines651f13c2014-04-23 16:59:28 -07001537 for (unsigned I = 0, E = FP.getNumParams(); I != E; ++I) {
1538 ParmVarDecl *P = FP.getParam(I);
John McCall6cd3b9f2010-04-09 17:38:44 +00001539
Reid Klecknerc66e7e92013-07-31 21:00:18 +00001540 // This must be synthesized from a typedef.
1541 if (!P) continue;
1542
Douglas Gregorc056c172011-05-09 20:45:16 +00001543 // The parameter's type as written might be dependent even if the
1544 // decayed type was not dependent.
1545 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
Douglas Gregor561f8122011-07-01 01:22:09 +00001546 if (TSInfo->getType()->isInstantiationDependentType())
Douglas Gregorc056c172011-05-09 20:45:16 +00001547 return true;
1548
John McCall6cd3b9f2010-04-09 17:38:44 +00001549 // TODO: currently we always rebuild expressions. When we
1550 // properly get lazier about this, we should use the same
1551 // logic to avoid rebuilding prototypes here.
Douglas Gregor7b1cf302011-01-05 21:14:17 +00001552 if (P->hasDefaultArg())
John McCall6cd3b9f2010-04-09 17:38:44 +00001553 return true;
1554 }
1555
1556 return false;
1557}
1558
1559/// A form of SubstType intended specifically for instantiating the
1560/// type of a FunctionDecl. Its purpose is solely to force the
1561/// instantiation of default-argument expressions.
1562TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1563 const MultiLevelTemplateArgumentList &Args,
1564 SourceLocation Loc,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001565 DeclarationName Entity,
1566 CXXRecordDecl *ThisContext,
1567 unsigned ThisTypeQuals) {
John McCall6cd3b9f2010-04-09 17:38:44 +00001568 assert(!ActiveTemplateInstantiations.empty() &&
1569 "Cannot perform an instantiation without some context on the "
1570 "instantiation stack");
1571
1572 if (!NeedsInstantiationAsFunctionType(T))
1573 return T;
1574
1575 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1576
1577 TypeLocBuilder TLB;
1578
1579 TypeLoc TL = T->getTypeLoc();
1580 TLB.reserve(TL.getFullDataSize());
1581
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001582 QualType Result;
David Blaikie39e6ab42013-02-18 22:06:02 +00001583
1584 if (FunctionProtoTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
1585 Result = Instantiator.TransformFunctionProtoType(TLB, Proto, ThisContext,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001586 ThisTypeQuals);
1587 } else {
1588 Result = Instantiator.TransformType(TLB, TL);
1589 }
John McCall6cd3b9f2010-04-09 17:38:44 +00001590 if (Result.isNull())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001591 return nullptr;
John McCall6cd3b9f2010-04-09 17:38:44 +00001592
1593 return TLB.getTypeSourceInfo(Context, Result);
1594}
1595
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001596ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001597 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallfb44de92011-05-01 22:35:37 +00001598 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001599 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001600 bool ExpectParameterPack) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001601 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001602 TypeSourceInfo *NewDI = nullptr;
1603
Douglas Gregor603cfb42011-01-05 23:12:31 +00001604 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00001605 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1606
Douglas Gregor603cfb42011-01-05 23:12:31 +00001607 // We have a function parameter pack. Substitute into the pattern of the
1608 // expansion.
1609 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1610 OldParm->getLocation(), OldParm->getDeclName());
1611 if (!NewDI)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001612 return nullptr;
1613
Douglas Gregor603cfb42011-01-05 23:12:31 +00001614 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1615 // We still have unexpanded parameter packs, which means that
1616 // our function parameter is still a function parameter pack.
1617 // Therefore, make its type a pack expansion type.
Douglas Gregorcded4f62011-01-14 17:04:44 +00001618 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001619 NumExpansions);
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001620 } else if (ExpectParameterPack) {
1621 // We expected to get a parameter pack but didn't (because the type
1622 // itself is not a pack expansion type), so complain. This can occur when
1623 // the substitution goes through an alias template that "loses" the
1624 // pack expansion.
1625 Diag(OldParm->getLocation(),
1626 diag::err_function_parameter_pack_without_parameter_packs)
1627 << NewDI->getType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001628 return nullptr;
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001629 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001630 } else {
1631 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1632 OldParm->getDeclName());
1633 }
1634
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001635 if (!NewDI)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001636 return nullptr;
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001637
1638 if (NewDI->getType()->isVoidType()) {
1639 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001640 return nullptr;
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001641 }
1642
1643 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001644 OldParm->getInnerLocStart(),
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001645 OldParm->getLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001646 OldParm->getIdentifier(),
1647 NewDI->getType(), NewDI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001648 OldParm->getStorageClass());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001649 if (!NewParm)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001650 return nullptr;
1651
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001652 // Mark the (new) default argument as uninstantiated (if any).
1653 if (OldParm->hasUninstantiatedDefaultArg()) {
1654 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1655 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor8cfb7a32010-10-12 18:23:32 +00001656 } else if (OldParm->hasUnparsedDefaultArg()) {
1657 NewParm->setUnparsedDefaultArg();
1658 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
David Blaikie57296722012-05-01 06:05:57 +00001659 } else if (Expr *Arg = OldParm->getDefaultArg())
1660 // FIXME: if we non-lazily instantiated non-dependent default args for
1661 // non-dependent parameter types we could remove a bunch of duplicate
1662 // conversion warnings for such arguments.
1663 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001664
1665 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001666
Douglas Gregor12c9c002011-01-07 16:43:16 +00001667 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smithc0536c82012-01-25 02:14:59 +00001668 // Add the new parameter to the instantiated parameter pack.
Douglas Gregor12c9c002011-01-07 16:43:16 +00001669 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1670 } else {
1671 // Introduce an Old -> New mapping
Douglas Gregor603cfb42011-01-05 23:12:31 +00001672 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregor12c9c002011-01-07 16:43:16 +00001673 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001674
Argyrios Kyrtzidise3041be2010-07-19 10:14:41 +00001675 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1676 // can be anything, is this right ?
Fariborz Jahanian55a17c02010-07-13 21:05:02 +00001677 NewParm->setDeclContext(CurContext);
John McCallfb44de92011-05-01 22:35:37 +00001678
1679 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1680 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rose09189892013-03-08 22:25:36 +00001681
1682 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1683
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001684 return NewParm;
1685}
1686
Douglas Gregora009b592011-01-07 00:20:55 +00001687/// \brief Substitute the given template arguments into the given set of
1688/// parameters, producing the set of parameter types that would be generated
1689/// from such a substitution.
1690bool Sema::SubstParmTypes(SourceLocation Loc,
1691 ParmVarDecl **Params, unsigned NumParams,
1692 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001693 SmallVectorImpl<QualType> &ParamTypes,
1694 SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregora009b592011-01-07 00:20:55 +00001695 assert(!ActiveTemplateInstantiations.empty() &&
1696 "Cannot perform an instantiation without some context on the "
1697 "instantiation stack");
1698
1699 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1700 DeclarationName());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001701 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams,
1702 nullptr, ParamTypes,
1703 OutParams);
Douglas Gregora009b592011-01-07 00:20:55 +00001704}
1705
John McCallce3ff2b2009-08-25 22:02:44 +00001706/// \brief Perform substitution on the base class specifiers of the
1707/// given class template specialization.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001708///
1709/// Produces a diagnostic and returns true on error, returns false and
1710/// attaches the instantiated base classes to the class template
1711/// specialization if successful.
Mike Stump1eb44332009-09-09 15:08:12 +00001712bool
John McCallce3ff2b2009-08-25 22:02:44 +00001713Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1714 CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001715 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001716 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001717 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Stephen Hines651f13c2014-04-23 16:59:28 -07001718 for (const auto Base : Pattern->bases()) {
1719 if (!Base.getType()->isDependentType()) {
1720 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay538fccb2013-06-21 18:58:32 +00001721 if (RD->isInvalidDecl())
1722 Instantiation->setInvalidDecl();
1723 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001724 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor2943aed2009-03-03 04:44:36 +00001725 continue;
1726 }
1727
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001728 SourceLocation EllipsisLoc;
Douglas Gregor406f98f2011-03-02 02:04:06 +00001729 TypeSourceInfo *BaseTypeLoc;
Stephen Hines651f13c2014-04-23 16:59:28 -07001730 if (Base.isPackExpansion()) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001731 // This is a pack expansion. See whether we should expand it now, or
1732 // wait until later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001733 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Stephen Hines651f13c2014-04-23 16:59:28 -07001734 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001735 Unexpanded);
1736 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00001737 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001738 Optional<unsigned> NumExpansions;
Stephen Hines651f13c2014-04-23 16:59:28 -07001739 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1740 Base.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001741 Unexpanded,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001742 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00001743 RetainExpansion,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001744 NumExpansions)) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001745 Invalid = true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001746 continue;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001747 }
1748
1749 // If we should expand this pack expansion now, do so.
1750 if (ShouldExpand) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00001751 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001752 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1753
Stephen Hines651f13c2014-04-23 16:59:28 -07001754 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001755 TemplateArgs,
Stephen Hines651f13c2014-04-23 16:59:28 -07001756 Base.getSourceRange().getBegin(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001757 DeclarationName());
1758 if (!BaseTypeLoc) {
1759 Invalid = true;
1760 continue;
1761 }
1762
1763 if (CXXBaseSpecifier *InstantiatedBase
1764 = CheckBaseSpecifier(Instantiation,
Stephen Hines651f13c2014-04-23 16:59:28 -07001765 Base.getSourceRange(),
1766 Base.isVirtual(),
1767 Base.getAccessSpecifierAsWritten(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001768 BaseTypeLoc,
1769 SourceLocation()))
1770 InstantiatedBases.push_back(InstantiatedBase);
1771 else
1772 Invalid = true;
1773 }
1774
1775 continue;
1776 }
1777
1778 // The resulting base specifier will (still) be a pack expansion.
Stephen Hines651f13c2014-04-23 16:59:28 -07001779 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregor406f98f2011-03-02 02:04:06 +00001780 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Stephen Hines651f13c2014-04-23 16:59:28 -07001781 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor406f98f2011-03-02 02:04:06 +00001782 TemplateArgs,
Stephen Hines651f13c2014-04-23 16:59:28 -07001783 Base.getSourceRange().getBegin(),
Douglas Gregor406f98f2011-03-02 02:04:06 +00001784 DeclarationName());
1785 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -07001786 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor406f98f2011-03-02 02:04:06 +00001787 TemplateArgs,
Stephen Hines651f13c2014-04-23 16:59:28 -07001788 Base.getSourceRange().getBegin(),
Douglas Gregor406f98f2011-03-02 02:04:06 +00001789 DeclarationName());
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001790 }
1791
Nick Lewycky56062202010-07-26 16:56:01 +00001792 if (!BaseTypeLoc) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001793 Invalid = true;
1794 continue;
1795 }
1796
1797 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregord475b8d2009-03-25 21:17:03 +00001798 = CheckBaseSpecifier(Instantiation,
Stephen Hines651f13c2014-04-23 16:59:28 -07001799 Base.getSourceRange(),
1800 Base.isVirtual(),
1801 Base.getAccessSpecifierAsWritten(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001802 BaseTypeLoc,
1803 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001804 InstantiatedBases.push_back(InstantiatedBase);
1805 else
1806 Invalid = true;
1807 }
1808
Douglas Gregor27b152f2009-03-10 18:52:44 +00001809 if (!Invalid &&
Jay Foadbeaaccd2009-05-21 09:52:38 +00001810 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001811 InstantiatedBases.size()))
1812 Invalid = true;
1813
1814 return Invalid;
1815}
1816
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001817// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramer5bbc3852012-02-06 11:13:08 +00001818namespace clang {
1819 namespace sema {
1820 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1821 const MultiLevelTemplateArgumentList &TemplateArgs);
1822 }
1823}
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001824
Richard Smithf1c66b42012-03-14 23:13:10 +00001825/// Determine whether we would be unable to instantiate this template (because
1826/// it either has no definition, or is in the process of being instantiated).
1827static bool DiagnoseUninstantiableTemplate(Sema &S,
1828 SourceLocation PointOfInstantiation,
1829 TagDecl *Instantiation,
1830 bool InstantiatedFromMember,
1831 TagDecl *Pattern,
1832 TagDecl *PatternDef,
1833 TemplateSpecializationKind TSK,
1834 bool Complain = true) {
1835 if (PatternDef && !PatternDef->isBeingDefined())
1836 return false;
1837
1838 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1839 // Say nothing
1840 } else if (PatternDef) {
1841 assert(PatternDef->isBeingDefined());
1842 S.Diag(PointOfInstantiation,
1843 diag::err_template_instantiate_within_definition)
1844 << (TSK != TSK_ImplicitInstantiation)
1845 << S.Context.getTypeDeclType(Instantiation);
1846 // Not much point in noting the template declaration here, since
1847 // we're lexically inside it.
1848 Instantiation->setInvalidDecl();
1849 } else if (InstantiatedFromMember) {
1850 S.Diag(PointOfInstantiation,
1851 diag::err_implicit_instantiate_member_undefined)
1852 << S.Context.getTypeDeclType(Instantiation);
1853 S.Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1854 } else {
1855 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1856 << (TSK != TSK_ImplicitInstantiation)
1857 << S.Context.getTypeDeclType(Instantiation);
1858 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1859 }
1860
1861 // In general, Instantiation isn't marked invalid to get more than one
1862 // error for multiple undefined instantiations. But the code that does
1863 // explicit declaration -> explicit definition conversion can't handle
1864 // invalid declarations, so mark as invalid in that case.
1865 if (TSK == TSK_ExplicitInstantiationDeclaration)
1866 Instantiation->setInvalidDecl();
1867 return true;
1868}
1869
Douglas Gregord475b8d2009-03-25 21:17:03 +00001870/// \brief Instantiate the definition of a class from a given pattern.
1871///
1872/// \param PointOfInstantiation The point of instantiation within the
1873/// source code.
1874///
1875/// \param Instantiation is the declaration whose definition is being
1876/// instantiated. This will be either a class template specialization
1877/// or a member class of a class template specialization.
1878///
1879/// \param Pattern is the pattern from which the instantiation
1880/// occurs. This will be either the declaration of a class template or
1881/// the declaration of a member class of a class template.
1882///
1883/// \param TemplateArgs The template arguments to be substituted into
1884/// the pattern.
1885///
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001886/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor5842ba92009-08-24 15:23:48 +00001887///
1888/// \param Complain whether to complain if the class cannot be instantiated due
1889/// to the lack of a definition.
1890///
Douglas Gregord475b8d2009-03-25 21:17:03 +00001891/// \returns true if an error occurred, false otherwise.
1892bool
1893Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1894 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001895 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001896 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00001897 bool Complain) {
Mike Stump1eb44332009-09-09 15:08:12 +00001898 CXXRecordDecl *PatternDef
Douglas Gregor952b0172010-02-11 01:04:33 +00001899 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Richard Smithf1c66b42012-03-14 23:13:10 +00001900 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1901 Instantiation->getInstantiatedFromMemberClass(),
1902 Pattern, PatternDef, TSK, Complain))
Douglas Gregord475b8d2009-03-25 21:17:03 +00001903 return true;
Douglas Gregord475b8d2009-03-25 21:17:03 +00001904 Pattern = PatternDef;
1905
Douglas Gregor454885e2009-10-15 15:54:05 +00001906 // \brief Record the point of instantiation.
1907 if (MemberSpecializationInfo *MSInfo
1908 = Instantiation->getMemberSpecializationInfo()) {
1909 MSInfo->setTemplateSpecializationKind(TSK);
1910 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001911 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weberc7feca02011-12-20 20:32:49 +00001912 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001913 Spec->setTemplateSpecializationKind(TSK);
1914 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00001915 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001916
Douglas Gregord048bb72009-03-25 21:23:52 +00001917 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd69f37b2013-10-08 08:09:04 +00001918 if (Inst.isInvalid())
Douglas Gregord475b8d2009-03-25 21:17:03 +00001919 return true;
1920
1921 // Enter the scope of this instantiation. We don't use
1922 // PushDeclContext because we don't have a scope.
John McCallf5813822010-04-29 00:35:03 +00001923 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor9679caf2010-05-12 17:27:19 +00001924 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00001925 Sema::PotentiallyEvaluated);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001926
Douglas Gregor05030bb2010-03-24 01:33:17 +00001927 // If this is an instantiation of a local class, merge this local
1928 // instantiation scope with the enclosing scope. Otherwise, every
1929 // instantiation of a class has its own local instantiation scope.
1930 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall2a7fb272010-08-25 05:32:35 +00001931 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor05030bb2010-03-24 01:33:17 +00001932
John McCall1d8d1cc2010-08-01 02:01:53 +00001933 // Pull attributes from the pattern onto the instantiation.
1934 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1935
Douglas Gregord475b8d2009-03-25 21:17:03 +00001936 // Start the definition of this instantiation.
1937 Instantiation->startDefinition();
Stephen Hines651f13c2014-04-23 16:59:28 -07001938
1939 // The instantiation is visible here, even if it was first declared in an
1940 // unimported module.
1941 Instantiation->setHidden(false);
1942
1943 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregor13c85772010-05-06 00:28:52 +00001944 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001945
John McCallce3ff2b2009-08-25 22:02:44 +00001946 // Do substitution on the base class specifiers.
1947 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001948 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00001949
Douglas Gregord65587f2010-11-10 19:44:59 +00001950 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001951 SmallVector<Decl*, 4> Fields;
1952 SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
Richard Smith7a614d82011-06-11 17:19:42 +00001953 FieldsWithMemberInitializers;
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001954 // Delay instantiation of late parsed attributes.
1955 LateInstantiatedAttrVec LateAttrs;
1956 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1957
Stephen Hines651f13c2014-04-23 16:59:28 -07001958 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidisbb5e4312010-11-04 03:18:57 +00001959 // Don't instantiate members not belonging in this semantic context.
1960 // e.g. for:
1961 // @code
1962 // template <int i> class A {
1963 // class B *g;
1964 // };
1965 // @endcode
1966 // 'class B' has the template as lexical context but semantically it is
1967 // introduced in namespace scope.
Stephen Hines651f13c2014-04-23 16:59:28 -07001968 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidisbb5e4312010-11-04 03:18:57 +00001969 continue;
1970
Stephen Hines651f13c2014-04-23 16:59:28 -07001971 if (Member->isInvalidDecl()) {
Richard Smithe3f470a2012-07-11 22:37:56 +00001972 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00001973 continue;
1974 }
1975
Stephen Hines651f13c2014-04-23 16:59:28 -07001976 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001977 if (NewMember) {
Richard Smith7a614d82011-06-11 17:19:42 +00001978 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCalld226f652010-08-21 09:40:31 +00001979 Fields.push_back(Field);
Stephen Hines651f13c2014-04-23 16:59:28 -07001980 FieldDecl *OldField = cast<FieldDecl>(Member);
Richard Smith7a614d82011-06-11 17:19:42 +00001981 if (OldField->getInClassInitializer())
1982 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
1983 Field));
Richard Smith1af83c42012-03-23 03:33:32 +00001984 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
1985 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1986 // specialization causes the implicit instantiation of the definitions
1987 // of unscoped member enumerations.
1988 // Record a point of instantiation for this implicit instantiation.
Richard Smith3343fad2012-03-23 23:09:08 +00001989 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
1990 Enum->isCompleteDefinition()) {
Richard Smith1af83c42012-03-23 03:33:32 +00001991 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
1992 assert(MSInfo && "no spec info for member enum specialization");
1993 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
1994 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1995 }
Richard Smithe3f470a2012-07-11 22:37:56 +00001996 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
1997 if (SA->isFailed()) {
1998 // A static_assert failed. Bail out; instantiating this
1999 // class is probably not meaningful.
2000 Instantiation->setInvalidDecl();
2001 break;
2002 }
Richard Smith1af83c42012-03-23 03:33:32 +00002003 }
2004
2005 if (NewMember->isInvalidDecl())
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002006 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002007 } else {
2008 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002009 // instantiations was a semantic disaster, and we'll want to mark the
2010 // declaration invalid.
2011 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregord475b8d2009-03-25 21:17:03 +00002012 }
2013 }
2014
2015 // Finish checking fields.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002016 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2017 SourceLocation(), SourceLocation(), nullptr);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002018 CheckCompletedCXXClass(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002019
2020 // Attach any in-class member initializers now the class is complete.
Richard Smithd5be2b52012-12-08 02:13:02 +00002021 // FIXME: We are supposed to defer instantiating these until they are needed.
Benjamin Kramer268efba2012-05-17 12:01:52 +00002022 if (!FieldsWithMemberInitializers.empty()) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002023 // C++11 [expr.prim.general]p4:
2024 // Otherwise, if a member-declarator declares a non-static data member
2025 // (9.2) of a class X, the expression this is a prvalue of type "pointer
2026 // to X" within the optional brace-or-equal-initializer. It shall not
2027 // appear elsewhere in the member-declarator.
2028 CXXThisScopeRAII ThisScope(*this, Instantiation, (unsigned)0);
2029
2030 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
2031 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
2032 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
2033 Expr *OldInit = OldField->getInClassInitializer();
Richard Smith7a614d82011-06-11 17:19:42 +00002034
Stephen Hines651f13c2014-04-23 16:59:28 -07002035 ActOnStartCXXInClassMemberInitializer();
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002036 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2037 /*CXXDirectInit=*/false);
Stephen Hines651f13c2014-04-23 16:59:28 -07002038 Expr *Init = NewInit.take();
2039 assert((!Init || !isa<ParenListExpr>(Init)) &&
2040 "call-style init in class");
2041 ActOnFinishCXXInClassMemberInitializer(NewField, Init->getLocStart(),
2042 Init);
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002043 }
Richard Smith7a614d82011-06-11 17:19:42 +00002044 }
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002045 // Instantiate late parsed attributes, and attach them to their decls.
2046 // See Sema::InstantiateAttrs
2047 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2048 E = LateAttrs.end(); I != E; ++I) {
2049 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2050 CurrentInstantiationScope = I->Scope;
Richard Smithcafeb942013-06-07 02:33:37 +00002051
2052 // Allow 'this' within late-parsed attributes.
2053 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2054 CXXRecordDecl *ThisContext =
2055 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2056 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2057 ND && ND->isCXXInstanceMember());
2058
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002059 Attr *NewAttr =
2060 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2061 I->NewDecl->addAttr(NewAttr);
2062 LocalInstantiationScope::deleteScopes(I->Scope,
2063 Instantiator.getStartingScope());
2064 }
2065 Instantiator.disableLateAttributeInstantiation();
2066 LateAttrs.clear();
2067
Richard Smithb9d0b762012-07-27 04:22:15 +00002068 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002069
Stephen Hines651f13c2014-04-23 16:59:28 -07002070 // FIXME: We should do something similar for explicit instantiations so they
2071 // end up in the right module.
Abramo Bagnarae9946242011-11-18 08:08:52 +00002072 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis734bd6e2012-02-11 01:59:57 +00002073 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002074 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnara09d82122011-10-03 20:34:03 +00002075 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002076 }
Abramo Bagnara09d82122011-10-03 20:34:03 +00002077
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002078 if (!Instantiation->isInvalidDecl()) {
John McCall1f2e1a92012-08-10 03:15:35 +00002079 // Perform any dependent diagnostics from the pattern.
2080 PerformDependentDiagnostics(Pattern, TemplateArgs);
2081
Douglas Gregord65587f2010-11-10 19:44:59 +00002082 // Instantiate any out-of-line class template partial
2083 // specializations now.
Richard Smithe688ddf2013-09-26 03:49:48 +00002084 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregord65587f2010-11-10 19:44:59 +00002085 P = Instantiator.delayed_partial_spec_begin(),
2086 PEnd = Instantiator.delayed_partial_spec_end();
2087 P != PEnd; ++P) {
2088 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smithe688ddf2013-09-26 03:49:48 +00002089 P->first, P->second)) {
2090 Instantiation->setInvalidDecl();
2091 break;
2092 }
2093 }
2094
2095 // Instantiate any out-of-line variable template partial
2096 // specializations now.
2097 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2098 P = Instantiator.delayed_var_partial_spec_begin(),
2099 PEnd = Instantiator.delayed_var_partial_spec_end();
2100 P != PEnd; ++P) {
2101 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2102 P->first, P->second)) {
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002103 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00002104 break;
2105 }
2106 }
2107 }
2108
Douglas Gregord475b8d2009-03-25 21:17:03 +00002109 // Exit the scope of this instantiation.
John McCallf5813822010-04-29 00:35:03 +00002110 SavedContext.pop();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002111
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002112 if (!Instantiation->isInvalidDecl()) {
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002113 Consumer.HandleTagDeclDefinition(Instantiation);
2114
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002115 // Always emit the vtable for an explicit instantiation definition
2116 // of a polymorphic class template specialization.
2117 if (TSK == TSK_ExplicitInstantiationDefinition)
2118 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2119 }
2120
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002121 return Instantiation->isInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002122}
2123
Richard Smithf1c66b42012-03-14 23:13:10 +00002124/// \brief Instantiate the definition of an enum from a given pattern.
2125///
2126/// \param PointOfInstantiation The point of instantiation within the
2127/// source code.
2128/// \param Instantiation is the declaration whose definition is being
2129/// instantiated. This will be a member enumeration of a class
2130/// temploid specialization, or a local enumeration within a
2131/// function temploid specialization.
2132/// \param Pattern The templated declaration from which the instantiation
2133/// occurs.
2134/// \param TemplateArgs The template arguments to be substituted into
2135/// the pattern.
2136/// \param TSK The kind of implicit or explicit instantiation to perform.
2137///
2138/// \return \c true if an error occurred, \c false otherwise.
2139bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2140 EnumDecl *Instantiation, EnumDecl *Pattern,
2141 const MultiLevelTemplateArgumentList &TemplateArgs,
2142 TemplateSpecializationKind TSK) {
2143 EnumDecl *PatternDef = Pattern->getDefinition();
2144 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2145 Instantiation->getInstantiatedFromMemberEnum(),
2146 Pattern, PatternDef, TSK,/*Complain*/true))
2147 return true;
2148 Pattern = PatternDef;
2149
2150 // Record the point of instantiation.
2151 if (MemberSpecializationInfo *MSInfo
2152 = Instantiation->getMemberSpecializationInfo()) {
2153 MSInfo->setTemplateSpecializationKind(TSK);
2154 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2155 }
2156
2157 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd69f37b2013-10-08 08:09:04 +00002158 if (Inst.isInvalid())
Richard Smithf1c66b42012-03-14 23:13:10 +00002159 return true;
2160
Stephen Hines651f13c2014-04-23 16:59:28 -07002161 // The instantiation is visible here, even if it was first declared in an
2162 // unimported module.
2163 Instantiation->setHidden(false);
2164
Richard Smithf1c66b42012-03-14 23:13:10 +00002165 // Enter the scope of this instantiation. We don't use
2166 // PushDeclContext because we don't have a scope.
2167 ContextRAII SavedContext(*this, Instantiation);
2168 EnterExpressionEvaluationContext EvalContext(*this,
2169 Sema::PotentiallyEvaluated);
2170
2171 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2172
2173 // Pull attributes from the pattern onto the instantiation.
2174 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2175
2176 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2177 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2178
2179 // Exit the scope of this instantiation.
2180 SavedContext.pop();
2181
2182 return Instantiation->isInvalidDecl();
2183}
2184
Douglas Gregor9b623632010-10-12 23:32:35 +00002185namespace {
2186 /// \brief A partial specialization whose template arguments have matched
2187 /// a given template-id.
2188 struct PartialSpecMatchResult {
2189 ClassTemplatePartialSpecializationDecl *Partial;
2190 TemplateArgumentList *Args;
Douglas Gregor9b623632010-10-12 23:32:35 +00002191 };
2192}
2193
Larisse Voufo567f9172013-08-22 00:59:14 +00002194bool Sema::InstantiateClassTemplateSpecialization(
2195 SourceLocation PointOfInstantiation,
2196 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2197 TemplateSpecializationKind TSK, bool Complain) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00002198 // Perform the actual instantiation on the canonical declaration.
2199 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002200 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor2943aed2009-03-03 04:44:36 +00002201
Douglas Gregor52604ab2009-09-11 21:19:12 +00002202 // Check whether we have already instantiated or specialized this class
2203 // template specialization.
2204 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2205 if (ClassTemplateSpec->getSpecializationKind() ==
2206 TSK_ExplicitInstantiationDeclaration &&
2207 TSK == TSK_ExplicitInstantiationDefinition) {
2208 // An explicit instantiation definition follows an explicit instantiation
2209 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2210 // explicit instantiation.
2211 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002212
2213 // If this is an explicit instantiation definition, mark the
2214 // vtable as used.
Nico Weberc7feca02011-12-20 20:32:49 +00002215 if (TSK == TSK_ExplicitInstantiationDefinition &&
2216 !ClassTemplateSpec->isInvalidDecl())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002217 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2218
Douglas Gregor52604ab2009-09-11 21:19:12 +00002219 return false;
2220 }
2221
2222 // We can only instantiate something that hasn't already been
2223 // instantiated or specialized. Fail without any diagnostics: our
2224 // caller will provide an error message.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002225 return true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00002226 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002227
Douglas Gregor9eea08b2009-09-15 16:51:42 +00002228 if (ClassTemplateSpec->isInvalidDecl())
2229 return true;
2230
Douglas Gregor2943aed2009-03-03 04:44:36 +00002231 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002232 CXXRecordDecl *Pattern = nullptr;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002233
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002234 // C++ [temp.class.spec.match]p1:
2235 // When a class template is used in a context that requires an
2236 // instantiation of the class, it is necessary to determine
2237 // whether the instantiation is to be generated using the primary
2238 // template or one of the partial specializations. This is done by
2239 // matching the template arguments of the class template
2240 // specialization with the template argument lists of the partial
2241 // specializations.
Douglas Gregor9b623632010-10-12 23:32:35 +00002242 typedef PartialSpecMatchResult MatchResult;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002243 SmallVector<MatchResult, 4> Matched;
2244 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002245 Template->getPartialSpecializations(PartialSpecs);
Larisse Voufo43847122013-07-19 23:00:19 +00002246 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002247 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2248 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo43847122013-07-19 23:00:19 +00002249 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorf67875d2009-06-12 18:26:56 +00002250 if (TemplateDeductionResult Result
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002251 = DeduceTemplateArguments(Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00002252 ClassTemplateSpec->getTemplateArgs(),
2253 Info)) {
Larisse Voufo43847122013-07-19 23:00:19 +00002254 // Store the failed-deduction information for use in diagnostics, later.
2255 // TODO: Actually use the failed-deduction info?
2256 FailedCandidates.addCandidate()
2257 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorf67875d2009-06-12 18:26:56 +00002258 (void)Result;
2259 } else {
Douglas Gregor9b623632010-10-12 23:32:35 +00002260 Matched.push_back(PartialSpecMatchResult());
2261 Matched.back().Partial = Partial;
2262 Matched.back().Args = Info.take();
Douglas Gregorf67875d2009-06-12 18:26:56 +00002263 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002264 }
2265
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002266 // If we're dealing with a member template where the template parameters
2267 // have been instantiated, this provides the original template parameters
2268 // from which the member template's parameters were instantiated.
Stephen Hines651f13c2014-04-23 16:59:28 -07002269
Douglas Gregored9c0f92009-10-29 00:04:11 +00002270 if (Matched.size() >= 1) {
Craig Topper09d19ef2013-07-04 03:08:24 +00002271 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002272 if (Matched.size() == 1) {
2273 // -- If exactly one matching specialization is found, the
2274 // instantiation is generated from that specialization.
2275 // We don't need to do anything for this.
2276 } else {
2277 // -- If more than one matching specialization is found, the
2278 // partial order rules (14.5.4.2) are used to determine
2279 // whether one of the specializations is more specialized
2280 // than the others. If none of the specializations is more
2281 // specialized than all of the other matching
2282 // specializations, then the use of the class template is
2283 // ambiguous and the program is ill-formed.
Craig Topper09d19ef2013-07-04 03:08:24 +00002284 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2285 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002286 P != PEnd; ++P) {
Douglas Gregor9b623632010-10-12 23:32:35 +00002287 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002288 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002289 == P->Partial)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002290 Best = P;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002291 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002292
Douglas Gregored9c0f92009-10-29 00:04:11 +00002293 // Determine if the best partial specialization is more specialized than
2294 // the others.
2295 bool Ambiguous = false;
Craig Topper09d19ef2013-07-04 03:08:24 +00002296 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2297 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002298 P != PEnd; ++P) {
2299 if (P != Best &&
Douglas Gregor9b623632010-10-12 23:32:35 +00002300 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002301 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002302 != Best->Partial) {
Douglas Gregored9c0f92009-10-29 00:04:11 +00002303 Ambiguous = true;
2304 break;
2305 }
2306 }
2307
2308 if (Ambiguous) {
2309 // Partial ordering did not produce a clear winner. Complain.
2310 ClassTemplateSpec->setInvalidDecl();
2311 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2312 << ClassTemplateSpec;
2313
2314 // Print the matching partial specializations.
Craig Topper09d19ef2013-07-04 03:08:24 +00002315 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2316 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002317 P != PEnd; ++P)
Douglas Gregor9b623632010-10-12 23:32:35 +00002318 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2319 << getTemplateArgumentBindingsText(
2320 P->Partial->getTemplateParameters(),
2321 *P->Args);
Douglas Gregord6350ae2009-08-28 20:31:08 +00002322
Douglas Gregored9c0f92009-10-29 00:04:11 +00002323 return true;
2324 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002325 }
2326
2327 // Instantiate using the best class template partial specialization.
Douglas Gregor9b623632010-10-12 23:32:35 +00002328 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002329 while (OrigPartialSpec->getInstantiatedFromMember()) {
2330 // If we've found an explicit specialization of this class template,
2331 // stop here and use that as the pattern.
2332 if (OrigPartialSpec->isMemberSpecialization())
2333 break;
2334
2335 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2336 }
2337
2338 Pattern = OrigPartialSpec;
Douglas Gregor9b623632010-10-12 23:32:35 +00002339 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002340 } else {
2341 // -- If no matches are found, the instantiation is generated
2342 // from the primary template.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002343 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002344 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2345 // If we've found an explicit specialization of this class template,
2346 // stop here and use that as the pattern.
2347 if (OrigTemplate->isMemberSpecialization())
2348 break;
2349
Douglas Gregord6350ae2009-08-28 20:31:08 +00002350 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002351 }
2352
Douglas Gregord6350ae2009-08-28 20:31:08 +00002353 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002354 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002355
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002356 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2357 Pattern,
2358 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002359 TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002360 Complain);
Mike Stump1eb44332009-09-09 15:08:12 +00002361
Douglas Gregor199d9912009-06-05 00:53:49 +00002362 return Result;
Douglas Gregor2943aed2009-03-03 04:44:36 +00002363}
Douglas Gregor5953d8b2009-03-19 17:26:29 +00002364
John McCallce3ff2b2009-08-25 22:02:44 +00002365/// \brief Instantiates the definitions of all of the member
2366/// of the given class, which is an instantiation of a class template
2367/// or a member class of a template.
Douglas Gregora58861f2009-05-13 20:28:22 +00002368void
2369Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002370 CXXRecordDecl *Instantiation,
2371 const MultiLevelTemplateArgumentList &TemplateArgs,
2372 TemplateSpecializationKind TSK) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002373 // FIXME: We need to notify the ASTMutationListener that we did all of these
2374 // things, in case we have an explicit instantiation definition in a PCM, a
2375 // module, or preamble, and the declaration is in an imported AST.
Bill Wendling57907e52013-11-28 00:34:08 +00002376 assert(
2377 (TSK == TSK_ExplicitInstantiationDefinition ||
2378 TSK == TSK_ExplicitInstantiationDeclaration ||
2379 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2380 "Unexpected template specialization kind!");
Stephen Hines651f13c2014-04-23 16:59:28 -07002381 for (auto *D : Instantiation->decls()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002382 bool SuppressNew = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07002383 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002384 if (FunctionDecl *Pattern
2385 = Function->getInstantiatedFromMemberFunction()) {
2386 MemberSpecializationInfo *MSInfo
2387 = Function->getMemberSpecializationInfo();
2388 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002389 if (MSInfo->getTemplateSpecializationKind()
2390 == TSK_ExplicitSpecialization)
2391 continue;
2392
Douglas Gregor0d035142009-10-27 18:42:08 +00002393 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2394 Function,
2395 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002396 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002397 SuppressNew) ||
2398 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002399 continue;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002400
2401 // C++11 [temp.explicit]p8:
2402 // An explicit instantiation definition that names a class template
2403 // specialization explicitly instantiates the class template
2404 // specialization and is only an explicit instantiation definition
2405 // of members whose definition is visible at the point of
2406 // instantiation.
2407 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002408 continue;
2409
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002410 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2411
2412 if (Function->isDefined()) {
2413 // Let the ASTConsumer know that this function has been explicitly
2414 // instantiated now, and its linkage might have changed.
2415 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2416 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002417 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002418 } else if (TSK == TSK_ImplicitInstantiation) {
2419 PendingLocalImplicitInstantiations.push_back(
2420 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor0d035142009-10-27 18:42:08 +00002421 }
Douglas Gregorf6b11852009-10-08 15:14:33 +00002422 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002423 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smithd0629eb2013-09-27 20:14:12 +00002424 if (isa<VarTemplateSpecializationDecl>(Var))
2425 continue;
2426
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002427 if (Var->isStaticDataMember()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002428 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2429 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002430 if (MSInfo->getTemplateSpecializationKind()
2431 == TSK_ExplicitSpecialization)
2432 continue;
2433
Douglas Gregor0d035142009-10-27 18:42:08 +00002434 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2435 Var,
2436 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002437 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002438 SuppressNew) ||
2439 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002440 continue;
2441
Douglas Gregor0d035142009-10-27 18:42:08 +00002442 if (TSK == TSK_ExplicitInstantiationDefinition) {
2443 // C++0x [temp.explicit]p8:
2444 // An explicit instantiation definition that names a class template
2445 // specialization explicitly instantiates the class template
2446 // specialization and is only an explicit instantiation definition
2447 // of members whose definition is visible at the point of
2448 // instantiation.
2449 if (!Var->getInstantiatedFromStaticDataMember()
2450 ->getOutOfLineDefinition())
2451 continue;
2452
2453 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002454 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor0d035142009-10-27 18:42:08 +00002455 } else {
2456 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2457 }
2458 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002459 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Douglas Gregora77eaa92010-04-18 18:11:38 +00002460 // Always skip the injected-class-name, along with any
2461 // redeclarations of nested classes, since both would cause us
2462 // to try to instantiate the members of a class twice.
Douglas Gregoref96ee02012-01-14 16:38:05 +00002463 if (Record->isInjectedClassName() || Record->getPreviousDecl())
Douglas Gregor2db32322009-10-07 23:56:10 +00002464 continue;
2465
Douglas Gregor0d035142009-10-27 18:42:08 +00002466 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2467 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002468
2469 if (MSInfo->getTemplateSpecializationKind()
2470 == TSK_ExplicitSpecialization)
2471 continue;
Nico Weberc956b6e2010-09-27 21:02:09 +00002472
Douglas Gregor0d035142009-10-27 18:42:08 +00002473 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2474 Record,
2475 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002476 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002477 SuppressNew) ||
2478 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002479 continue;
2480
Douglas Gregor0d035142009-10-27 18:42:08 +00002481 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2482 assert(Pattern && "Missing instantiated-from-template information");
2483
Douglas Gregor952b0172010-02-11 01:04:33 +00002484 if (!Record->getDefinition()) {
2485 if (!Pattern->getDefinition()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002486 // C++0x [temp.explicit]p8:
2487 // An explicit instantiation definition that names a class template
2488 // specialization explicitly instantiates the class template
2489 // specialization and is only an explicit instantiation definition
2490 // of members whose definition is visible at the point of
2491 // instantiation.
2492 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2493 MSInfo->setTemplateSpecializationKind(TSK);
2494 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2495 }
2496
2497 continue;
2498 }
2499
2500 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002501 TemplateArgs,
2502 TSK);
Nico Weberc956b6e2010-09-27 21:02:09 +00002503 } else {
2504 if (TSK == TSK_ExplicitInstantiationDefinition &&
2505 Record->getTemplateSpecializationKind() ==
2506 TSK_ExplicitInstantiationDeclaration) {
2507 Record->setTemplateSpecializationKind(TSK);
2508 MarkVTableUsed(PointOfInstantiation, Record, true);
2509 }
Douglas Gregor0d035142009-10-27 18:42:08 +00002510 }
Douglas Gregore9374d52009-10-08 01:19:17 +00002511
Douglas Gregor952b0172010-02-11 01:04:33 +00002512 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00002513 if (Pattern)
2514 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2515 TSK);
Stephen Hines651f13c2014-04-23 16:59:28 -07002516 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smithf1c66b42012-03-14 23:13:10 +00002517 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2518 assert(MSInfo && "No member specialization information?");
2519
2520 if (MSInfo->getTemplateSpecializationKind()
2521 == TSK_ExplicitSpecialization)
2522 continue;
2523
2524 if (CheckSpecializationInstantiationRedecl(
2525 PointOfInstantiation, TSK, Enum,
2526 MSInfo->getTemplateSpecializationKind(),
2527 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2528 SuppressNew)
2529 continue;
2530
2531 if (Enum->getDefinition())
2532 continue;
2533
2534 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2535 assert(Pattern && "Missing instantiated-from-template information");
2536
2537 if (TSK == TSK_ExplicitInstantiationDefinition) {
2538 if (!Pattern->getDefinition())
2539 continue;
2540
2541 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2542 } else {
2543 MSInfo->setTemplateSpecializationKind(TSK);
2544 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2545 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002546 }
2547 }
2548}
2549
2550/// \brief Instantiate the definitions of all of the members of the
2551/// given class template specialization, which was named as part of an
2552/// explicit instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +00002553void
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002554Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregora58861f2009-05-13 20:28:22 +00002555 SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002556 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2557 TemplateSpecializationKind TSK) {
Douglas Gregora58861f2009-05-13 20:28:22 +00002558 // C++0x [temp.explicit]p7:
2559 // An explicit instantiation that names a class template
2560 // specialization is an explicit instantion of the same kind
2561 // (declaration or definition) of each of its members (not
2562 // including members inherited from base classes) that has not
2563 // been previously explicitly specialized in the translation unit
2564 // containing the explicit instantiation, except as described
2565 // below.
2566 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002567 getTemplateInstantiationArgs(ClassTemplateSpec),
2568 TSK);
Douglas Gregora58861f2009-05-13 20:28:22 +00002569}
2570
John McCall60d7b3a2010-08-24 06:29:42 +00002571StmtResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002572Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor43959a92009-08-20 07:17:43 +00002573 if (!S)
2574 return Owned(S);
2575
2576 TemplateInstantiator Instantiator(*this, TemplateArgs,
2577 SourceLocation(),
2578 DeclarationName());
2579 return Instantiator.TransformStmt(S);
2580}
2581
John McCall60d7b3a2010-08-24 06:29:42 +00002582ExprResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002583Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorb98b1992009-08-11 05:31:07 +00002584 if (!E)
2585 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002586
Douglas Gregorb98b1992009-08-11 05:31:07 +00002587 TemplateInstantiator Instantiator(*this, TemplateArgs,
2588 SourceLocation(),
2589 DeclarationName());
2590 return Instantiator.TransformExpr(E);
2591}
2592
Richard Smithc83c2302012-12-19 01:39:02 +00002593ExprResult Sema::SubstInitializer(Expr *Init,
2594 const MultiLevelTemplateArgumentList &TemplateArgs,
2595 bool CXXDirectInit) {
2596 TemplateInstantiator Instantiator(*this, TemplateArgs,
2597 SourceLocation(),
2598 DeclarationName());
2599 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2600}
2601
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002602bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2603 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002604 SmallVectorImpl<Expr *> &Outputs) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002605 if (NumExprs == 0)
2606 return false;
Richard Smithc83c2302012-12-19 01:39:02 +00002607
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002608 TemplateInstantiator Instantiator(*this, TemplateArgs,
2609 SourceLocation(),
2610 DeclarationName());
2611 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2612}
2613
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002614NestedNameSpecifierLoc
2615Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2616 const MultiLevelTemplateArgumentList &TemplateArgs) {
2617 if (!NNS)
2618 return NestedNameSpecifierLoc();
2619
2620 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2621 DeclarationName());
2622 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2623}
2624
Abramo Bagnara25777432010-08-11 22:01:17 +00002625/// \brief Do template substitution on declaration name info.
2626DeclarationNameInfo
2627Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2628 const MultiLevelTemplateArgumentList &TemplateArgs) {
2629 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2630 NameInfo.getName());
2631 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2632}
2633
Douglas Gregorde650ae2009-03-31 18:38:02 +00002634TemplateName
Douglas Gregor1d752d72011-03-02 18:46:51 +00002635Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2636 TemplateName Name, SourceLocation Loc,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002637 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord1067e52009-08-06 06:41:21 +00002638 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2639 DeclarationName());
Douglas Gregor1d752d72011-03-02 18:46:51 +00002640 CXXScopeSpec SS;
2641 SS.Adopt(QualifierLoc);
2642 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregorde650ae2009-03-31 18:38:02 +00002643}
Douglas Gregor91333002009-06-11 00:06:24 +00002644
Douglas Gregore02e2622010-12-22 21:19:48 +00002645bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2646 TemplateArgumentListInfo &Result,
John McCall833ca992009-10-29 08:12:44 +00002647 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor670444e2009-08-04 22:27:00 +00002648 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2649 DeclarationName());
Douglas Gregore02e2622010-12-22 21:19:48 +00002650
2651 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregor91333002009-06-11 00:06:24 +00002652}
Douglas Gregor895162d2010-04-30 18:55:50 +00002653
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002654
2655static const Decl* getCanonicalParmVarDecl(const Decl *D) {
2656 // When storing ParmVarDecls in the local instantiation scope, we always
2657 // want to use the ParmVarDecl from the canonical function declaration,
2658 // since the map is then valid for any redeclaration or definition of that
2659 // function.
2660 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2661 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2662 unsigned i = PV->getFunctionScopeIndex();
2663 return FD->getCanonicalDecl()->getParamDecl(i);
2664 }
2665 }
2666 return D;
2667}
2668
2669
Douglas Gregor12c9c002011-01-07 16:43:16 +00002670llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2671LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002672 D = getCanonicalParmVarDecl(D);
Chris Lattner57ad3782011-02-17 20:34:02 +00002673 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor895162d2010-04-30 18:55:50 +00002674 Current = Current->Outer) {
Chris Lattner57ad3782011-02-17 20:34:02 +00002675
Douglas Gregor895162d2010-04-30 18:55:50 +00002676 // Check if we found something within this scope.
Douglas Gregorebb1c562010-12-21 21:22:51 +00002677 const Decl *CheckD = D;
2678 do {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002679 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregorebb1c562010-12-21 21:22:51 +00002680 if (Found != Current->LocalDecls.end())
Douglas Gregor12c9c002011-01-07 16:43:16 +00002681 return &Found->second;
Douglas Gregorebb1c562010-12-21 21:22:51 +00002682
2683 // If this is a tag declaration, it's possible that we need to look for
2684 // a previous declaration.
2685 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregoref96ee02012-01-14 16:38:05 +00002686 CheckD = Tag->getPreviousDecl();
Douglas Gregorebb1c562010-12-21 21:22:51 +00002687 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002688 CheckD = nullptr;
Douglas Gregorebb1c562010-12-21 21:22:51 +00002689 } while (CheckD);
2690
Douglas Gregor895162d2010-04-30 18:55:50 +00002691 // If we aren't combined with our outer scope, we're done.
2692 if (!Current->CombineWithOuterScope)
2693 break;
2694 }
Chris Lattner57ad3782011-02-17 20:34:02 +00002695
Serge Pavlovdc49d522013-07-15 06:14:07 +00002696 // If we're performing a partial substitution during template argument
2697 // deduction, we may not have values for template parameters yet.
2698 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2699 isa<TemplateTemplateParmDecl>(D))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002700 return nullptr;
Serge Pavlovdc49d522013-07-15 06:14:07 +00002701
Chris Lattner57ad3782011-02-17 20:34:02 +00002702 // If we didn't find the decl, then we either have a sema bug, or we have a
2703 // forward reference to a label declaration. Return null to indicate that
2704 // we have an uninstantiated label.
2705 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002706 return nullptr;
Douglas Gregor895162d2010-04-30 18:55:50 +00002707}
2708
John McCall2a7fb272010-08-25 05:32:35 +00002709void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002710 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002711 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregord3731192011-01-10 07:32:04 +00002712 if (Stored.isNull())
2713 Stored = Inst;
Benjamin Kramer3bbffd52013-04-12 15:22:25 +00002714 else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>())
2715 Pack->push_back(Inst);
2716 else
Douglas Gregord3731192011-01-10 07:32:04 +00002717 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Douglas Gregor895162d2010-04-30 18:55:50 +00002718}
Douglas Gregor12c9c002011-01-07 16:43:16 +00002719
2720void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2721 Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002722 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002723 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2724 Pack->push_back(Inst);
2725}
2726
2727void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002728 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002729 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2730 assert(Stored.isNull() && "Already instantiated this local");
2731 DeclArgumentPack *Pack = new DeclArgumentPack;
2732 Stored = Pack;
2733 ArgumentPacks.push_back(Pack);
2734}
2735
Douglas Gregord3731192011-01-10 07:32:04 +00002736void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2737 const TemplateArgument *ExplicitArgs,
2738 unsigned NumExplicitArgs) {
2739 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2740 "Already have a partially-substituted pack");
2741 assert((!PartiallySubstitutedPack
2742 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2743 "Wrong number of arguments in partially-substituted pack");
2744 PartiallySubstitutedPack = Pack;
2745 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2746 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2747}
2748
2749NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2750 const TemplateArgument **ExplicitArgs,
2751 unsigned *NumExplicitArgs) const {
2752 if (ExplicitArgs)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002753 *ExplicitArgs = nullptr;
Douglas Gregord3731192011-01-10 07:32:04 +00002754 if (NumExplicitArgs)
2755 *NumExplicitArgs = 0;
2756
2757 for (const LocalInstantiationScope *Current = this; Current;
2758 Current = Current->Outer) {
2759 if (Current->PartiallySubstitutedPack) {
2760 if (ExplicitArgs)
2761 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2762 if (NumExplicitArgs)
2763 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2764
2765 return Current->PartiallySubstitutedPack;
2766 }
2767
2768 if (!Current->CombineWithOuterScope)
2769 break;
2770 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002771
2772 return nullptr;
Douglas Gregord3731192011-01-10 07:32:04 +00002773}