blob: 29481d6c63bc8f29f5af5aa461c65b617741aba9 [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 Vali618c2852013-10-03 06:29:33 +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?");
79 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
80 return Result;
81 }
82
Douglas Gregor383041d2011-06-15 14:20:42 +000083 // If we have a template template parameter with translation unit context,
84 // then we're performing substitution into a default template argument of
85 // this template template parameter before we've constructed the template
86 // that will own this template template parameter. In this case, we
87 // use empty template parameter lists for all of the outer templates
88 // to avoid performing any substitutions.
89 if (Ctx->isTranslationUnit()) {
90 if (TemplateTemplateParmDecl *TTP
91 = dyn_cast<TemplateTemplateParmDecl>(D)) {
92 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
Richard Smith7a9f7c72013-05-17 03:04:50 +000093 Result.addOuterTemplateArguments(None);
Douglas Gregor383041d2011-06-15 14:20:42 +000094 return Result;
95 }
96 }
Douglas Gregor93104c12011-05-22 00:21:10 +000097 }
98
John McCallf181d8a2009-08-29 03:16:09 +000099 while (!Ctx->isFileContext()) {
Douglas Gregord1102432009-08-28 17:37:35 +0000100 // Add template arguments from a class template instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +0000101 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregord1102432009-08-28 17:37:35 +0000102 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
103 // We're done when we hit an explicit specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +0000104 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
105 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregord1102432009-08-28 17:37:35 +0000106 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Douglas Gregord1102432009-08-28 17:37:35 +0000108 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000109
110 // If this class template specialization was instantiated from a
111 // specialized member that is a class template, we're done.
112 assert(Spec->getSpecializedTemplate() && "No class template?");
113 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
114 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000115 }
Douglas Gregord1102432009-08-28 17:37:35 +0000116 // Add template arguments from a function template specialization.
John McCallf181d8a2009-08-29 03:16:09 +0000117 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor525f96c2010-02-05 07:33:43 +0000118 if (!RelativeToPrimary &&
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000119 (Function->getTemplateSpecializationKind() ==
120 TSK_ExplicitSpecialization &&
121 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000122 break;
123
Douglas Gregord1102432009-08-28 17:37:35 +0000124 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000125 = Function->getTemplateSpecializationArgs()) {
126 // Add the template arguments for this specialization.
Douglas Gregord1102432009-08-28 17:37:35 +0000127 Result.addOuterTemplateArguments(TemplateArgs);
John McCallf181d8a2009-08-29 03:16:09 +0000128
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000129 // If this function was instantiated from a specialized member that is
130 // a function template, we're done.
131 assert(Function->getPrimaryTemplate() && "No function template?");
132 if (Function->getPrimaryTemplate()->isMemberSpecialization())
133 break;
Faisal Vali618c2852013-10-03 06:29:33 +0000134
135 // If this function is a generic lambda specialization, we are done.
136 if (isGenericLambdaCallOperatorSpecialization(Function))
137 break;
138
Douglas Gregorc494f772011-03-05 17:54:25 +0000139 } else if (FunctionTemplateDecl *FunTmpl
140 = Function->getDescribedFunctionTemplate()) {
141 // Add the "injected" template arguments.
Richard Smith7a9f7c72013-05-17 03:04:50 +0000142 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000143 }
144
John McCallf181d8a2009-08-29 03:16:09 +0000145 // If this is a friend declaration and it declares an entity at
146 // namespace scope, take arguments from its lexical parent
Douglas Gregore7089b02010-05-03 23:29:10 +0000147 // instead of its semantic parent, unless of course the pattern we're
148 // instantiating actually comes from the file's context!
John McCallf181d8a2009-08-29 03:16:09 +0000149 if (Function->getFriendObjectKind() &&
Douglas Gregore7089b02010-05-03 23:29:10 +0000150 Function->getDeclContext()->isFileContext() &&
151 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCallf181d8a2009-08-29 03:16:09 +0000152 Ctx = Function->getLexicalDeclContext();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000153 RelativeToPrimary = false;
John McCallf181d8a2009-08-29 03:16:09 +0000154 continue;
155 }
Douglas Gregor24bae922010-07-08 18:37:38 +0000156 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
157 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
158 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith7a9f7c72013-05-17 03:04:50 +0000159 const TemplateSpecializationType *TST =
160 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
161 Result.addOuterTemplateArguments(
162 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor24bae922010-07-08 18:37:38 +0000163 if (ClassTemplate->isMemberSpecialization())
164 break;
165 }
Douglas Gregord1102432009-08-28 17:37:35 +0000166 }
John McCallf181d8a2009-08-29 03:16:09 +0000167
168 Ctx = Ctx->getParent();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000169 RelativeToPrimary = false;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000170 }
Mike Stump1eb44332009-09-09 15:08:12 +0000171
Douglas Gregord1102432009-08-28 17:37:35 +0000172 return Result;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000173}
174
Douglas Gregorf35f8282009-11-11 21:54:23 +0000175bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
176 switch (Kind) {
177 case TemplateInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000178 case ExceptionSpecInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000179 case DefaultTemplateArgumentInstantiation:
180 case DefaultFunctionArgumentInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000181 case ExplicitTemplateArgumentSubstitution:
182 case DeducedTemplateArgumentSubstitution:
183 case PriorTemplateArgumentSubstitution:
Richard Smithab91ef12012-07-08 02:38:24 +0000184 return true;
185
Douglas Gregorf35f8282009-11-11 21:54:23 +0000186 case DefaultTemplateArgumentChecking:
187 return false;
188 }
David Blaikie7530c032012-01-17 06:56:22 +0000189
190 llvm_unreachable("Invalid InstantiationKind!");
Douglas Gregorf35f8282009-11-11 21:54:23 +0000191}
192
Douglas Gregor26dce442009-03-10 00:06:19 +0000193Sema::InstantiatingTemplate::
194InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000195 Decl *Entity,
Douglas Gregor26dce442009-03-10 00:06:19 +0000196 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000197 : SemaRef(SemaRef),
198 SavedInNonInstantiationSFINAEContext(
199 SemaRef.InNonInstantiationSFINAEContext)
200{
Douglas Gregordf667e72009-03-10 20:44:00 +0000201 Invalid = CheckInstantiationDepth(PointOfInstantiation,
202 InstantiationRange);
203 if (!Invalid) {
Douglas Gregor26dce442009-03-10 00:06:19 +0000204 ActiveTemplateInstantiation Inst;
Douglas Gregordf667e72009-03-10 20:44:00 +0000205 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
Douglas Gregor26dce442009-03-10 00:06:19 +0000206 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000207 Inst.Entity = Entity;
Douglas Gregor313a81d2009-03-12 18:36:18 +0000208 Inst.TemplateArgs = 0;
209 Inst.NumTemplateArgs = 0;
Douglas Gregordf667e72009-03-10 20:44:00 +0000210 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000211 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregordf667e72009-03-10 20:44:00 +0000212 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregordf667e72009-03-10 20:44:00 +0000213 }
214}
215
Richard Smithe6975e92012-04-17 00:58:00 +0000216Sema::InstantiatingTemplate::
217InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
218 FunctionDecl *Entity, ExceptionSpecification,
219 SourceRange InstantiationRange)
220 : SemaRef(SemaRef),
221 SavedInNonInstantiationSFINAEContext(
222 SemaRef.InNonInstantiationSFINAEContext)
223{
224 Invalid = CheckInstantiationDepth(PointOfInstantiation,
225 InstantiationRange);
226 if (!Invalid) {
227 ActiveTemplateInstantiation Inst;
228 Inst.Kind = ActiveTemplateInstantiation::ExceptionSpecInstantiation;
229 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000230 Inst.Entity = Entity;
Richard Smithe6975e92012-04-17 00:58:00 +0000231 Inst.TemplateArgs = 0;
232 Inst.NumTemplateArgs = 0;
233 Inst.InstantiationRange = InstantiationRange;
234 SemaRef.InNonInstantiationSFINAEContext = false;
235 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
236 }
237}
238
Richard Smith7e54fb52012-07-16 01:09:10 +0000239Sema::InstantiatingTemplate::
240InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
241 TemplateDecl *Template,
242 ArrayRef<TemplateArgument> TemplateArgs,
243 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000244 : SemaRef(SemaRef),
245 SavedInNonInstantiationSFINAEContext(
246 SemaRef.InNonInstantiationSFINAEContext)
247{
Douglas Gregordf667e72009-03-10 20:44:00 +0000248 Invalid = CheckInstantiationDepth(PointOfInstantiation,
249 InstantiationRange);
250 if (!Invalid) {
251 ActiveTemplateInstantiation Inst;
Mike Stump1eb44332009-09-09 15:08:12 +0000252 Inst.Kind
Douglas Gregordf667e72009-03-10 20:44:00 +0000253 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
254 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000255 Inst.Entity = Template;
Richard Smith7e54fb52012-07-16 01:09:10 +0000256 Inst.TemplateArgs = TemplateArgs.data();
257 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregor26dce442009-03-10 00:06:19 +0000258 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000259 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor26dce442009-03-10 00:06:19 +0000260 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor26dce442009-03-10 00:06:19 +0000261 }
262}
263
Richard Smith7e54fb52012-07-16 01:09:10 +0000264Sema::InstantiatingTemplate::
265InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
266 FunctionTemplateDecl *FunctionTemplate,
267 ArrayRef<TemplateArgument> TemplateArgs,
268 ActiveTemplateInstantiation::InstantiationKind Kind,
269 sema::TemplateDeductionInfo &DeductionInfo,
270 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000271 : SemaRef(SemaRef),
272 SavedInNonInstantiationSFINAEContext(
273 SemaRef.InNonInstantiationSFINAEContext)
274{
Richard Smithab91ef12012-07-08 02:38:24 +0000275 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Douglas Gregorcca9e962009-07-01 22:01:06 +0000276 if (!Invalid) {
277 ActiveTemplateInstantiation Inst;
278 Inst.Kind = Kind;
279 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000280 Inst.Entity = FunctionTemplate;
Richard Smith7e54fb52012-07-16 01:09:10 +0000281 Inst.TemplateArgs = TemplateArgs.data();
282 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregor9b623632010-10-12 23:32:35 +0000283 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000284 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000285 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000286 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregorf35f8282009-11-11 21:54:23 +0000287
288 if (!Inst.isInstantiationRecord())
289 ++SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000290 }
291}
292
Richard Smith7e54fb52012-07-16 01:09:10 +0000293Sema::InstantiatingTemplate::
294InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
295 ClassTemplatePartialSpecializationDecl *PartialSpec,
296 ArrayRef<TemplateArgument> TemplateArgs,
297 sema::TemplateDeductionInfo &DeductionInfo,
298 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000299 : SemaRef(SemaRef),
300 SavedInNonInstantiationSFINAEContext(
301 SemaRef.InNonInstantiationSFINAEContext)
302{
Richard Smithab91ef12012-07-08 02:38:24 +0000303 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
304 if (!Invalid) {
305 ActiveTemplateInstantiation Inst;
306 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
307 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000308 Inst.Entity = PartialSpec;
Richard Smith7e54fb52012-07-16 01:09:10 +0000309 Inst.TemplateArgs = TemplateArgs.data();
310 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000311 Inst.DeductionInfo = &DeductionInfo;
312 Inst.InstantiationRange = InstantiationRange;
313 SemaRef.InNonInstantiationSFINAEContext = false;
314 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
315 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000316}
317
Larisse Voufoef4579c2013-08-06 01:03:05 +0000318Sema::InstantiatingTemplate::InstantiatingTemplate(
319 Sema &SemaRef, SourceLocation PointOfInstantiation,
320 VarTemplatePartialSpecializationDecl *PartialSpec,
321 ArrayRef<TemplateArgument> TemplateArgs,
322 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
323 : SemaRef(SemaRef), SavedInNonInstantiationSFINAEContext(
324 SemaRef.InNonInstantiationSFINAEContext) {
325 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
326 if (!Invalid) {
327 ActiveTemplateInstantiation Inst;
328 Inst.Kind =
329 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
330 Inst.PointOfInstantiation = PointOfInstantiation;
331 Inst.Entity = PartialSpec;
332 Inst.TemplateArgs = TemplateArgs.data();
333 Inst.NumTemplateArgs = TemplateArgs.size();
334 Inst.DeductionInfo = &DeductionInfo;
335 Inst.InstantiationRange = InstantiationRange;
336 SemaRef.InNonInstantiationSFINAEContext = false;
337 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
338 }
339}
340
Richard Smith7e54fb52012-07-16 01:09:10 +0000341Sema::InstantiatingTemplate::
342InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
343 ParmVarDecl *Param,
344 ArrayRef<TemplateArgument> TemplateArgs,
345 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000346 : SemaRef(SemaRef),
347 SavedInNonInstantiationSFINAEContext(
348 SemaRef.InNonInstantiationSFINAEContext)
349{
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000350 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000351 if (!Invalid) {
352 ActiveTemplateInstantiation Inst;
353 Inst.Kind
354 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000355 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000356 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000357 Inst.TemplateArgs = TemplateArgs.data();
358 Inst.NumTemplateArgs = TemplateArgs.size();
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000359 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000360 SemaRef.InNonInstantiationSFINAEContext = false;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000361 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000362 }
363}
364
365Sema::InstantiatingTemplate::
366InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000367 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
368 ArrayRef<TemplateArgument> TemplateArgs,
369 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000370 : SemaRef(SemaRef),
371 SavedInNonInstantiationSFINAEContext(
372 SemaRef.InNonInstantiationSFINAEContext)
373{
Richard Smithab91ef12012-07-08 02:38:24 +0000374 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
375 if (!Invalid) {
376 ActiveTemplateInstantiation Inst;
377 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
378 Inst.PointOfInstantiation = PointOfInstantiation;
379 Inst.Template = Template;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000380 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000381 Inst.TemplateArgs = TemplateArgs.data();
382 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000383 Inst.InstantiationRange = InstantiationRange;
384 SemaRef.InNonInstantiationSFINAEContext = false;
385 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
386 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000387}
388
389Sema::InstantiatingTemplate::
390InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000391 NamedDecl *Template, TemplateTemplateParmDecl *Param,
392 ArrayRef<TemplateArgument> TemplateArgs,
393 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000394 : SemaRef(SemaRef),
395 SavedInNonInstantiationSFINAEContext(
396 SemaRef.InNonInstantiationSFINAEContext)
397{
Richard Smithab91ef12012-07-08 02:38:24 +0000398 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
399 if (!Invalid) {
400 ActiveTemplateInstantiation Inst;
401 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
402 Inst.PointOfInstantiation = PointOfInstantiation;
403 Inst.Template = Template;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000404 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000405 Inst.TemplateArgs = TemplateArgs.data();
406 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000407 Inst.InstantiationRange = InstantiationRange;
408 SemaRef.InNonInstantiationSFINAEContext = false;
409 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
410 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000411}
412
413Sema::InstantiatingTemplate::
414InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000415 TemplateDecl *Template, NamedDecl *Param,
416 ArrayRef<TemplateArgument> TemplateArgs,
417 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000418 : SemaRef(SemaRef),
419 SavedInNonInstantiationSFINAEContext(
420 SemaRef.InNonInstantiationSFINAEContext)
421{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000422 Invalid = false;
423
424 ActiveTemplateInstantiation Inst;
425 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
426 Inst.PointOfInstantiation = PointOfInstantiation;
427 Inst.Template = Template;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000428 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000429 Inst.TemplateArgs = TemplateArgs.data();
430 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregorf35f8282009-11-11 21:54:23 +0000431 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000432 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000433 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
434
435 assert(!Inst.isInstantiationRecord());
436 ++SemaRef.NonInstantiationEntries;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000437}
438
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000439void Sema::InstantiatingTemplate::Clear() {
440 if (!Invalid) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000441 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
442 assert(SemaRef.NonInstantiationEntries > 0);
443 --SemaRef.NonInstantiationEntries;
444 }
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000445 SemaRef.InNonInstantiationSFINAEContext
446 = SavedInNonInstantiationSFINAEContext;
Richard Smithb7751002013-07-25 23:08:39 +0000447
448 // Name lookup no longer looks in this template's defining module.
449 assert(SemaRef.ActiveTemplateInstantiations.size() >=
450 SemaRef.ActiveTemplateInstantiationLookupModules.size() &&
451 "forgot to remove a lookup module for a template instantiation");
452 if (SemaRef.ActiveTemplateInstantiations.size() ==
453 SemaRef.ActiveTemplateInstantiationLookupModules.size()) {
454 if (Module *M = SemaRef.ActiveTemplateInstantiationLookupModules.back())
455 SemaRef.LookupModulesCache.erase(M);
456 SemaRef.ActiveTemplateInstantiationLookupModules.pop_back();
457 }
458
Douglas Gregor26dce442009-03-10 00:06:19 +0000459 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000460 Invalid = true;
461 }
Douglas Gregor26dce442009-03-10 00:06:19 +0000462}
463
Douglas Gregordf667e72009-03-10 20:44:00 +0000464bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
465 SourceLocation PointOfInstantiation,
466 SourceRange InstantiationRange) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000467 assert(SemaRef.NonInstantiationEntries <=
468 SemaRef.ActiveTemplateInstantiations.size());
469 if ((SemaRef.ActiveTemplateInstantiations.size() -
470 SemaRef.NonInstantiationEntries)
David Blaikie4e4d0842012-03-11 07:00:24 +0000471 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregordf667e72009-03-10 20:44:00 +0000472 return false;
473
Mike Stump1eb44332009-09-09 15:08:12 +0000474 SemaRef.Diag(PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000475 diag::err_template_recursion_depth_exceeded)
David Blaikie4e4d0842012-03-11 07:00:24 +0000476 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregordf667e72009-03-10 20:44:00 +0000477 << InstantiationRange;
478 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikie4e4d0842012-03-11 07:00:24 +0000479 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregordf667e72009-03-10 20:44:00 +0000480 return true;
481}
482
Douglas Gregoree1828a2009-03-10 18:03:33 +0000483/// \brief Prints the current instantiation stack through a series of
484/// notes.
485void Sema::PrintInstantiationStack() {
Douglas Gregor575cf372010-04-20 07:18:24 +0000486 // Determine which template instantiations to skip, if any.
487 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
488 unsigned Limit = Diags.getTemplateBacktraceLimit();
489 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
490 SkipStart = Limit / 2 + Limit % 2;
491 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
492 }
493
Douglas Gregorcca9e962009-07-01 22:01:06 +0000494 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregor575cf372010-04-20 07:18:24 +0000495 unsigned InstantiationIdx = 0;
Craig Topper09d19ef2013-07-04 03:08:24 +0000496 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
Douglas Gregoree1828a2009-03-10 18:03:33 +0000497 Active = ActiveTemplateInstantiations.rbegin(),
498 ActiveEnd = ActiveTemplateInstantiations.rend();
499 Active != ActiveEnd;
Douglas Gregor575cf372010-04-20 07:18:24 +0000500 ++Active, ++InstantiationIdx) {
501 // Skip this instantiation?
502 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
503 if (InstantiationIdx == SkipStart) {
504 // Note that we're skipping instantiations.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000505 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor575cf372010-04-20 07:18:24 +0000506 diag::note_instantiation_contexts_suppressed)
507 << unsigned(ActiveTemplateInstantiations.size() - Limit);
508 }
509 continue;
510 }
511
Douglas Gregordf667e72009-03-10 20:44:00 +0000512 switch (Active->Kind) {
513 case ActiveTemplateInstantiation::TemplateInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000514 Decl *D = Active->Entity;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000515 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
516 unsigned DiagID = diag::note_template_member_class_here;
517 if (isa<ClassTemplateSpecializationDecl>(Record))
518 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000519 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000520 << Context.getTypeDeclType(Record)
521 << Active->InstantiationRange;
Douglas Gregor7caa6822009-07-24 20:34:43 +0000522 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1637be72009-06-26 00:10:03 +0000523 unsigned DiagID;
524 if (Function->getPrimaryTemplate())
525 DiagID = diag::note_function_template_spec_here;
526 else
527 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000528 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000529 << Function
530 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000531 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000532 Diags.Report(Active->PointOfInstantiation,
Larisse Voufo933c66b2013-08-14 20:15:02 +0000533 VD->isStaticDataMember()?
534 diag::note_template_static_data_member_def_here
535 : diag::note_template_variable_def_here)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000536 << VD
537 << Active->InstantiationRange;
Richard Smithf1c66b42012-03-14 23:13:10 +0000538 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
539 Diags.Report(Active->PointOfInstantiation,
540 diag::note_template_enum_def_here)
541 << ED
542 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000543 } else {
544 Diags.Report(Active->PointOfInstantiation,
545 diag::note_template_type_alias_instantiation_here)
546 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregor7caa6822009-07-24 20:34:43 +0000547 << Active->InstantiationRange;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000548 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000549 break;
550 }
551
552 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000553 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
Benjamin Kramer5eada842013-02-22 15:46:01 +0000554 SmallVector<char, 128> TemplateArgsStr;
555 llvm::raw_svector_ostream OS(TemplateArgsStr);
556 Template->printName(OS);
557 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000558 Active->TemplateArgs,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000559 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000560 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000561 Diags.Report(Active->PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000562 diag::note_default_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000563 << OS.str()
Douglas Gregordf667e72009-03-10 20:44:00 +0000564 << Active->InstantiationRange;
565 break;
566 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000567
Douglas Gregorcca9e962009-07-01 22:01:06 +0000568 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000569 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000570 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000571 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000572 << FnTmpl
573 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
574 Active->TemplateArgs,
575 Active->NumTemplateArgs)
576 << Active->InstantiationRange;
Douglas Gregor637a4092009-06-10 23:47:09 +0000577 break;
578 }
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Douglas Gregorcca9e962009-07-01 22:01:06 +0000580 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000581 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
582 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000583 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000584 diag::note_partial_spec_deduct_instantiation_here)
585 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor5e402912010-03-30 20:35:20 +0000586 << getTemplateArgumentBindingsText(
587 PartialSpec->getTemplateParameters(),
588 Active->TemplateArgs,
589 Active->NumTemplateArgs)
Douglas Gregorcca9e962009-07-01 22:01:06 +0000590 << Active->InstantiationRange;
591 } else {
592 FunctionTemplateDecl *FnTmpl
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000593 = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000594 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000595 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000596 << FnTmpl
597 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
598 Active->TemplateArgs,
599 Active->NumTemplateArgs)
600 << Active->InstantiationRange;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000601 }
602 break;
Douglas Gregor637a4092009-06-10 23:47:09 +0000603
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000604 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000605 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000606 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Benjamin Kramer5eada842013-02-22 15:46:01 +0000608 SmallVector<char, 128> TemplateArgsStr;
609 llvm::raw_svector_ostream OS(TemplateArgsStr);
610 FD->printName(OS);
611 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000612 Active->TemplateArgs,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000613 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000614 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000615 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000616 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000617 << OS.str()
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000618 << Active->InstantiationRange;
619 break;
620 }
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000622 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000623 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000624 std::string Name;
625 if (!Parm->getName().empty())
626 Name = std::string(" '") + Parm->getName().str() + "'";
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000627
628 TemplateParameterList *TemplateParams = 0;
629 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
630 TemplateParams = Template->getTemplateParameters();
631 else
632 TemplateParams =
633 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
634 ->getTemplateParameters();
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000635 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000636 diag::note_prior_template_arg_substitution)
637 << isa<TemplateTemplateParmDecl>(Parm)
638 << Name
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000639 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000640 Active->TemplateArgs,
641 Active->NumTemplateArgs)
642 << Active->InstantiationRange;
643 break;
644 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000645
646 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000647 TemplateParameterList *TemplateParams = 0;
648 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
649 TemplateParams = Template->getTemplateParameters();
650 else
651 TemplateParams =
652 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
653 ->getTemplateParameters();
654
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000655 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000656 diag::note_template_default_arg_checking)
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000657 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000658 Active->TemplateArgs,
659 Active->NumTemplateArgs)
660 << Active->InstantiationRange;
661 break;
662 }
Richard Smithe6975e92012-04-17 00:58:00 +0000663
664 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
665 Diags.Report(Active->PointOfInstantiation,
666 diag::note_template_exception_spec_instantiation_here)
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000667 << cast<FunctionDecl>(Active->Entity)
Richard Smithe6975e92012-04-17 00:58:00 +0000668 << Active->InstantiationRange;
669 break;
Douglas Gregordf667e72009-03-10 20:44:00 +0000670 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000671 }
672}
673
David Blaikiedc84cd52013-02-20 22:23:23 +0000674Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000675 if (InNonInstantiationSFINAEContext)
David Blaikiedc84cd52013-02-20 22:23:23 +0000676 return Optional<TemplateDeductionInfo *>(0);
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000677
Craig Topper09d19ef2013-07-04 03:08:24 +0000678 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000679 Active = ActiveTemplateInstantiations.rbegin(),
680 ActiveEnd = ActiveTemplateInstantiations.rend();
681 Active != ActiveEnd;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000682 ++Active)
683 {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000684 switch(Active->Kind) {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000685 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smitha43ea642012-04-26 07:24:08 +0000686 // An instantiation of an alias template may or may not be a SFINAE
687 // context, depending on what else is on the stack.
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000688 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smitha43ea642012-04-26 07:24:08 +0000689 break;
690 // Fall through.
691 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000692 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorcca9e962009-07-01 22:01:06 +0000693 // This is a template instantiation, so there is no SFINAE.
David Blaikie66874fb2013-02-21 01:47:18 +0000694 return None;
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000696 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000697 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000698 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000699 // A default template argument instantiation and substitution into
700 // template parameters with arguments for prior parameters may or may
701 // not be a SFINAE context; look further up the stack.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000702 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000703
Douglas Gregorcca9e962009-07-01 22:01:06 +0000704 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
705 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
706 // We're either substitution explicitly-specified template arguments
707 // or deduced template arguments, so SFINAE applies.
Douglas Gregor9b623632010-10-12 23:32:35 +0000708 assert(Active->DeductionInfo && "Missing deduction info pointer");
709 return Active->DeductionInfo;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000710 }
711 }
712
David Blaikie66874fb2013-02-21 01:47:18 +0000713 return None;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000714}
715
Douglas Gregord3731192011-01-10 07:32:04 +0000716/// \brief Retrieve the depth and index of a parameter pack.
717static std::pair<unsigned, unsigned>
718getDepthAndIndex(NamedDecl *ND) {
719 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
720 return std::make_pair(TTP->getDepth(), TTP->getIndex());
721
722 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
723 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
724
725 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
726 return std::make_pair(TTP->getDepth(), TTP->getIndex());
727}
728
Douglas Gregor99ebf652009-02-27 19:31:52 +0000729//===----------------------------------------------------------------------===/
730// Template Instantiation for Types
731//===----------------------------------------------------------------------===/
Douglas Gregorcd281c32009-02-28 00:25:32 +0000732namespace {
Douglas Gregor895162d2010-04-30 18:55:50 +0000733 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000734 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000735 SourceLocation Loc;
736 DeclarationName Entity;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000737
Douglas Gregorcd281c32009-02-28 00:25:32 +0000738 public:
Douglas Gregor43959a92009-08-20 07:17:43 +0000739 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump1eb44332009-09-09 15:08:12 +0000740
741 TemplateInstantiator(Sema &SemaRef,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000742 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor577f75a2009-08-04 16:50:30 +0000743 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000744 DeclarationName Entity)
745 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregor43959a92009-08-20 07:17:43 +0000746 Entity(Entity) { }
Douglas Gregorcd281c32009-02-28 00:25:32 +0000747
Mike Stump1eb44332009-09-09 15:08:12 +0000748 /// \brief Determine whether the given type \p T has already been
Douglas Gregor577f75a2009-08-04 16:50:30 +0000749 /// transformed.
750 ///
751 /// For the purposes of template instantiation, a type has already been
752 /// transformed if it is NULL or if it is not dependent.
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000753 bool AlreadyTransformed(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Douglas Gregor577f75a2009-08-04 16:50:30 +0000755 /// \brief Returns the location of the entity being instantiated, if known.
756 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Douglas Gregor577f75a2009-08-04 16:50:30 +0000758 /// \brief Returns the name of the entity being instantiated, if any.
759 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Douglas Gregor972e6ce2009-10-27 06:26:26 +0000761 /// \brief Sets the "base" location and entity when that
762 /// information is known based on another transformation.
763 void setBase(SourceLocation Loc, DeclarationName Entity) {
764 this->Loc = Loc;
765 this->Entity = Entity;
766 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000767
768 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
769 SourceRange PatternRange,
Robert Wilhelm834c0582013-08-09 18:02:13 +0000770 ArrayRef<UnexpandedParameterPack> Unexpanded,
771 bool &ShouldExpand, bool &RetainExpansion,
David Blaikiedc84cd52013-02-20 22:23:23 +0000772 Optional<unsigned> &NumExpansions) {
Douglas Gregorb99268b2010-12-21 00:52:54 +0000773 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
774 PatternRange, Unexpanded,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000775 TemplateArgs,
776 ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000777 RetainExpansion,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000778 NumExpansions);
779 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000780
Douglas Gregor12c9c002011-01-07 16:43:16 +0000781 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
782 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
783 }
784
Douglas Gregord3731192011-01-10 07:32:04 +0000785 TemplateArgument ForgetPartiallySubstitutedPack() {
786 TemplateArgument Result;
787 if (NamedDecl *PartialPack
788 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
789 MultiLevelTemplateArgumentList &TemplateArgs
790 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
791 unsigned Depth, Index;
792 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
793 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
794 Result = TemplateArgs(Depth, Index);
795 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
796 }
797 }
798
799 return Result;
800 }
801
802 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
803 if (Arg.isNull())
804 return;
805
806 if (NamedDecl *PartialPack
807 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
808 MultiLevelTemplateArgumentList &TemplateArgs
809 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
810 unsigned Depth, Index;
811 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
812 TemplateArgs.setArgument(Depth, Index, Arg);
813 }
814 }
815
Douglas Gregor577f75a2009-08-04 16:50:30 +0000816 /// \brief Transform the given declaration by instantiating a reference to
817 /// this declaration.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000818 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregorb98b1992009-08-11 05:31:07 +0000819
Douglas Gregordfca6f52012-02-13 22:00:16 +0000820 void transformAttrs(Decl *Old, Decl *New) {
821 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
822 }
823
824 void transformedLocalDecl(Decl *Old, Decl *New) {
825 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
826 }
827
Mike Stump1eb44332009-09-09 15:08:12 +0000828 /// \brief Transform the definition of the given declaration by
Douglas Gregor43959a92009-08-20 07:17:43 +0000829 /// instantiating it.
Douglas Gregoraac571c2010-03-01 17:25:41 +0000830 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Dmitri Gribenkoe23fb902012-09-12 17:01:48 +0000832 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregor6cd21982009-10-20 05:58:46 +0000833 /// declaration.
834 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
835
Douglas Gregor43959a92009-08-20 07:17:43 +0000836 /// \brief Rebuild the exception declaration and register the declaration
837 /// as an instantiated local.
Douglas Gregor83cb9422010-09-09 17:09:21 +0000838 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000839 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000840 SourceLocation StartLoc,
841 SourceLocation NameLoc,
842 IdentifierInfo *Name);
Mike Stump1eb44332009-09-09 15:08:12 +0000843
Douglas Gregorbe270a02010-04-26 17:57:08 +0000844 /// \brief Rebuild the Objective-C exception declaration and register the
845 /// declaration as an instantiated local.
846 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
847 TypeSourceInfo *TSInfo, QualType T);
848
John McCallc4e70192009-09-11 04:59:25 +0000849 /// \brief Check for tag mismatches when instantiating an
850 /// elaborated type.
John McCall21e413f2010-11-04 19:04:38 +0000851 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
852 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000853 NestedNameSpecifierLoc QualifierLoc,
854 QualType T);
John McCallc4e70192009-09-11 04:59:25 +0000855
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000856 TemplateName TransformTemplateName(CXXScopeSpec &SS,
857 TemplateName Name,
858 SourceLocation NameLoc,
859 QualType ObjectType = QualType(),
860 NamedDecl *FirstQualifierInScope = 0);
861
John McCall60d7b3a2010-08-24 06:29:42 +0000862 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
863 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
864 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000865
John McCall60d7b3a2010-08-24 06:29:42 +0000866 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor56bc9832010-12-24 00:15:10 +0000867 NonTypeTemplateParmDecl *D);
Douglas Gregorc7793c72011-01-15 01:15:58 +0000868 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
869 SubstNonTypeTemplateParmPackExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000870
871 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
872 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
873
874 /// \brief Transform a reference to a function parameter pack.
875 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
876 ParmVarDecl *PD);
877
878 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
879 /// expand a function parameter pack reference which refers to an expanded
880 /// pack.
881 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
882
Douglas Gregor895162d2010-04-30 18:55:50 +0000883 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000884 FunctionProtoTypeLoc TL);
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000885 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
886 FunctionProtoTypeLoc TL,
887 CXXRecordDecl *ThisContext,
888 unsigned ThisTypeQuals);
889
Douglas Gregor6a24bfd2011-01-14 22:40:04 +0000890 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +0000891 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +0000892 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +0000893 bool ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +0000894
Mike Stump1eb44332009-09-09 15:08:12 +0000895 /// \brief Transforms a template type parameter type by performing
Douglas Gregor577f75a2009-08-04 16:50:30 +0000896 /// substitution of the corresponding template type argument.
John McCalla2becad2009-10-21 00:40:46 +0000897 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000898 TemplateTypeParmTypeLoc TL);
Nick Lewycky03d98c52010-07-06 19:51:49 +0000899
Douglas Gregorc3069d62011-01-14 02:55:32 +0000900 /// \brief Transforms an already-substituted template type parameter pack
901 /// into either itself (if we aren't substituting into its pack expansion)
902 /// or the appropriate substituted argument.
903 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
904 SubstTemplateTypeParmPackTypeLoc TL);
905
John McCall60d7b3a2010-08-24 06:29:42 +0000906 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewycky03d98c52010-07-06 19:51:49 +0000907 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCall60d7b3a2010-08-24 06:29:42 +0000908 ExprResult Result =
Nick Lewycky03d98c52010-07-06 19:51:49 +0000909 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
910 getSema().CallsUndergoingInstantiation.pop_back();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000911 return Result;
Nick Lewycky03d98c52010-07-06 19:51:49 +0000912 }
John McCall91a57552011-07-15 05:09:51 +0000913
Richard Smith612409e2012-07-25 03:56:55 +0000914 ExprResult TransformLambdaExpr(LambdaExpr *E) {
915 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
916 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
917 }
918
919 ExprResult TransformLambdaScope(LambdaExpr *E,
Faisal Vali618c2852013-10-03 06:29:33 +0000920 CXXMethodDecl *NewCallOperator) {
921 // If a lambda is undergoing transformation for instance in the
922 // call to foo('a') below:
923 // template<class T> void foo(T t) {
924 // auto L1 = [](T a) { return a; };
925 // auto L2 = [](char b) { return b; };
926 // auto L3 = [](auto c) { return c; };
927 // }
928 // The AST nodes of the OldCallOperators within the primary template foo
929 // are connected to the NewCallOperators within the specialization of foo.
930 // - In the case of L1 and L2 we set the NewCallOperator to be considered
931 // an instantiation of the OldCallOperator.
932 // - In the generic lambda case, we set the NewTemplate to be considered
933 // an "instantiation" of the OldTemplate.
934 // See the documentation and use of get/setInstantiationOfMemberFunction
935 // and get/setInstantiatedFromMemberTemplate to appreciate the relevance
936 // of creating these links.
937 // And so it goes on and on with nested generic lambdas.
938 CXXMethodDecl *const OldCallOperator = E->getCallOperator();
939 FunctionTemplateDecl *const NewCallOperatorTemplate =
940 NewCallOperator->getDescribedFunctionTemplate();
941 FunctionTemplateDecl *const OldCallOperatorTemplate =
942 OldCallOperator->getDescribedFunctionTemplate();
Richard Smith612409e2012-07-25 03:56:55 +0000943
Faisal Vali618c2852013-10-03 06:29:33 +0000944 if (!NewCallOperatorTemplate)
945 NewCallOperator->setInstantiationOfMemberFunction(OldCallOperator,
946 TSK_ImplicitInstantiation);
947 else {
948 NewCallOperatorTemplate->setInstantiatedFromMemberTemplate(
949 OldCallOperatorTemplate);
950 // Set this as a specialization so we don't go digging into the
951 // OldCallOperatorTemplate when retrieving the
952 // 'FunctionDecl::getTemplateInstantiationPattern()'
953 NewCallOperatorTemplate->setMemberSpecialization();
954 }
955 return inherited::TransformLambdaScope(E, NewCallOperator);
956 }
957 TemplateParameterList *TransformTemplateParameterList(
958 TemplateParameterList *OrigTPL) {
959 TemplateParameterList *NewTPL = 0;
960 if (OrigTPL) {
961 if (!OrigTPL->size()) return OrigTPL; // size 0, do nothing
962
963 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
964 TemplateDeclInstantiator DeclInstantiator(getSema(),
965 /* DeclContext *Owner */ Owner, TemplateArgs);
966 NewTPL = DeclInstantiator.SubstTemplateParams(OrigTPL);
967 }
968 return NewTPL;
969 }
John McCall91a57552011-07-15 05:09:51 +0000970 private:
971 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
972 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +0000973 TemplateArgument arg);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000974 };
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000975}
976
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000977bool TemplateInstantiator::AlreadyTransformed(QualType T) {
978 if (T.isNull())
979 return true;
980
Douglas Gregor561f8122011-07-01 01:22:09 +0000981 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000982 return false;
983
984 getSema().MarkDeclarationsReferencedInType(Loc, T);
985 return true;
986}
987
Eli Friedman10ec0e42013-07-19 19:40:38 +0000988static TemplateArgument
989getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
990 assert(S.ArgumentPackSubstitutionIndex >= 0);
991 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
992 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
993 if (Arg.isPackExpansion())
994 Arg = Arg.getPackExpansionPattern();
995 return Arg;
996}
997
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000998Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregorc68afe22009-09-03 21:38:09 +0000999 if (!D)
1000 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Douglas Gregorc68afe22009-09-03 21:38:09 +00001002 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregord6350ae2009-08-28 20:31:08 +00001003 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor6d3e6272010-02-05 19:54:12 +00001004 // If the corresponding template argument is NULL or non-existent, it's
1005 // because we are performing instantiation from explicitly-specified
1006 // template arguments in a function template, but there were some
1007 // arguments left unspecified.
1008 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1009 TTP->getPosition()))
1010 return D;
1011
Douglas Gregor61c4d282011-01-05 15:48:55 +00001012 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1013
1014 if (TTP->isParameterPack()) {
1015 assert(Arg.getKind() == TemplateArgument::Pack &&
1016 "Missing argument pack");
Eli Friedman10ec0e42013-07-19 19:40:38 +00001017 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor61c4d282011-01-05 15:48:55 +00001018 }
1019
1020 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor788cd062009-11-11 01:00:40 +00001021 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregord6350ae2009-08-28 20:31:08 +00001022 "Wrong kind of template template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +00001023 return Template.getAsTemplateDecl();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001024 }
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Douglas Gregor788cd062009-11-11 01:00:40 +00001026 // Fall through to find the instantiated declaration for this template
1027 // template parameter.
Douglas Gregord1067e52009-08-06 06:41:21 +00001028 }
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001030 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregor577f75a2009-08-04 16:50:30 +00001031}
1032
Douglas Gregoraac571c2010-03-01 17:25:41 +00001033Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +00001034 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregor43959a92009-08-20 07:17:43 +00001035 if (!Inst)
1036 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Douglas Gregor43959a92009-08-20 07:17:43 +00001038 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1039 return Inst;
1040}
1041
Douglas Gregor6cd21982009-10-20 05:58:46 +00001042NamedDecl *
1043TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1044 SourceLocation Loc) {
1045 // If the first part of the nested-name-specifier was a template type
1046 // parameter, instantiate that type parameter down to a tag type.
1047 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1048 const TemplateTypeParmType *TTP
1049 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor984a58b2010-12-20 22:48:17 +00001050
Douglas Gregor6cd21982009-10-20 05:58:46 +00001051 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor984a58b2010-12-20 22:48:17 +00001052 // FIXME: This needs testing w/ member access expressions.
1053 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1054
1055 if (TTP->isParameterPack()) {
1056 assert(Arg.getKind() == TemplateArgument::Pack &&
1057 "Missing argument pack");
1058
Douglas Gregor2be29f42011-01-14 23:41:42 +00001059 if (getSema().ArgumentPackSubstitutionIndex == -1)
Douglas Gregor984a58b2010-12-20 22:48:17 +00001060 return 0;
Douglas Gregor984a58b2010-12-20 22:48:17 +00001061
Eli Friedman10ec0e42013-07-19 19:40:38 +00001062 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor984a58b2010-12-20 22:48:17 +00001063 }
1064
1065 QualType T = Arg.getAsType();
Douglas Gregor6cd21982009-10-20 05:58:46 +00001066 if (T.isNull())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001067 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +00001068
1069 if (const TagType *Tag = T->getAs<TagType>())
1070 return Tag->getDecl();
1071
1072 // The resulting type is not a tag; complain.
1073 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1074 return 0;
1075 }
1076 }
1077
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001078 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +00001079}
1080
Douglas Gregor43959a92009-08-20 07:17:43 +00001081VarDecl *
1082TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +00001083 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001084 SourceLocation StartLoc,
1085 SourceLocation NameLoc,
1086 IdentifierInfo *Name) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00001087 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001088 StartLoc, NameLoc, Name);
Douglas Gregorbe270a02010-04-26 17:57:08 +00001089 if (Var)
1090 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1091 return Var;
1092}
1093
1094VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1095 TypeSourceInfo *TSInfo,
1096 QualType T) {
1097 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1098 if (Var)
Douglas Gregor43959a92009-08-20 07:17:43 +00001099 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1100 return Var;
1101}
1102
John McCallc4e70192009-09-11 04:59:25 +00001103QualType
John McCall21e413f2010-11-04 19:04:38 +00001104TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1105 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +00001106 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001107 QualType T) {
John McCallc4e70192009-09-11 04:59:25 +00001108 if (const TagType *TT = T->getAs<TagType>()) {
1109 TagDecl* TD = TT->getDecl();
1110
John McCall21e413f2010-11-04 19:04:38 +00001111 SourceLocation TagLocation = KeywordLoc;
John McCallc4e70192009-09-11 04:59:25 +00001112
John McCallc4e70192009-09-11 04:59:25 +00001113 IdentifierInfo *Id = TD->getIdentifier();
1114
1115 // TODO: should we even warn on struct/class mismatches for this? Seems
1116 // like it's likely to produce a lot of spurious errors.
Richard Smithcbf97c52012-08-17 00:12:27 +00001117 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001118 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieubbf34c02011-06-10 03:11:26 +00001119 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1120 TagLocation, *Id)) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001121 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1122 << Id
1123 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1124 TD->getKindName());
1125 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1126 }
John McCallc4e70192009-09-11 04:59:25 +00001127 }
1128 }
1129
John McCall21e413f2010-11-04 19:04:38 +00001130 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1131 Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +00001132 QualifierLoc,
1133 T);
John McCallc4e70192009-09-11 04:59:25 +00001134}
1135
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001136TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1137 TemplateName Name,
1138 SourceLocation NameLoc,
1139 QualType ObjectType,
1140 NamedDecl *FirstQualifierInScope) {
1141 if (TemplateTemplateParmDecl *TTP
1142 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1143 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1144 // If the corresponding template argument is NULL or non-existent, it's
1145 // because we are performing instantiation from explicitly-specified
1146 // template arguments in a function template, but there were some
1147 // arguments left unspecified.
1148 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1149 TTP->getPosition()))
1150 return Name;
1151
1152 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1153
1154 if (TTP->isParameterPack()) {
1155 assert(Arg.getKind() == TemplateArgument::Pack &&
1156 "Missing argument pack");
1157
1158 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1159 // We have the template argument pack to substitute, but we're not
1160 // actually expanding the enclosing pack expansion yet. So, just
1161 // keep the entire argument pack.
1162 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1163 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001164
1165 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001166 }
1167
1168 TemplateName Template = Arg.getAsTemplate();
Richard Smith3e4c6c42011-05-05 21:57:07 +00001169 assert(!Template.isNull() && "Null template template argument");
John McCall14606042011-06-30 08:33:18 +00001170
Douglas Gregor58750382011-03-05 20:06:51 +00001171 // We don't ever want to substitute for a qualified template name, since
1172 // the qualifier is handled separately. So, look through the qualified
1173 // template name to its underlying declaration.
1174 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1175 Template = TemplateName(QTN->getTemplateDecl());
John McCall14606042011-06-30 08:33:18 +00001176
1177 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001178 return Template;
1179 }
1180 }
1181
1182 if (SubstTemplateTemplateParmPackStorage *SubstPack
1183 = Name.getAsSubstTemplateTemplateParmPack()) {
1184 if (getSema().ArgumentPackSubstitutionIndex == -1)
1185 return Name;
1186
Eli Friedman10ec0e42013-07-19 19:40:38 +00001187 TemplateArgument Arg = SubstPack->getArgumentPack();
1188 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1189 return Arg.getAsTemplate();
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001190 }
1191
1192 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1193 FirstQualifierInScope);
1194}
1195
John McCall60d7b3a2010-08-24 06:29:42 +00001196ExprResult
John McCall454feb92009-12-08 09:21:05 +00001197TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson773f3972009-09-11 01:22:35 +00001198 if (!E->isTypeDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00001199 return SemaRef.Owned(E);
Anders Carlsson773f3972009-09-11 01:22:35 +00001200
Wei Pan33129332013-09-16 13:57:27 +00001201 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
Anders Carlsson773f3972009-09-11 01:22:35 +00001202}
1203
John McCall60d7b3a2010-08-24 06:29:42 +00001204ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001205TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregordcee9802010-02-08 23:41:45 +00001206 NonTypeTemplateParmDecl *NTTP) {
John McCallb8fc0532010-02-06 08:42:39 +00001207 // If the corresponding template argument is NULL or non-existent, it's
1208 // because we are performing instantiation from explicitly-specified
1209 // template arguments in a function template, but there were some
1210 // arguments left unspecified.
1211 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1212 NTTP->getPosition()))
John McCall3fa5cae2010-10-26 07:05:15 +00001213 return SemaRef.Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Douglas Gregor56bc9832010-12-24 00:15:10 +00001215 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1216 if (NTTP->isParameterPack()) {
1217 assert(Arg.getKind() == TemplateArgument::Pack &&
1218 "Missing argument pack");
1219
1220 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc7793c72011-01-15 01:15:58 +00001221 // We have an argument pack, but we can't select a particular argument
1222 // out of it yet. Therefore, we'll build an expression to hold on to that
1223 // argument pack.
1224 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1225 E->getLocation(),
1226 NTTP->getDeclName());
1227 if (TargetType.isNull())
1228 return ExprError();
1229
1230 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1231 NTTP,
1232 E->getLocation(),
1233 Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001234 }
1235
Eli Friedman10ec0e42013-07-19 19:40:38 +00001236 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001237 }
Mike Stump1eb44332009-09-09 15:08:12 +00001238
John McCall91a57552011-07-15 05:09:51 +00001239 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1240}
1241
1242ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1243 NonTypeTemplateParmDecl *parm,
1244 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +00001245 TemplateArgument arg) {
John McCall91a57552011-07-15 05:09:51 +00001246 ExprResult result;
1247 QualType type;
1248
John McCallb8fc0532010-02-06 08:42:39 +00001249 // The template argument itself might be an expression, in which
1250 // case we just return that expression.
John McCall91a57552011-07-15 05:09:51 +00001251 if (arg.getKind() == TemplateArgument::Expression) {
1252 Expr *argExpr = arg.getAsExpr();
1253 result = SemaRef.Owned(argExpr);
1254 type = argExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001255
Eli Friedmand7a6b162012-09-26 02:36:12 +00001256 } else if (arg.getKind() == TemplateArgument::Declaration ||
1257 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregord2008e22012-04-06 22:40:38 +00001258 ValueDecl *VD;
Eli Friedmand7a6b162012-09-26 02:36:12 +00001259 if (arg.getKind() == TemplateArgument::Declaration) {
1260 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001261
Douglas Gregord2008e22012-04-06 22:40:38 +00001262 // Find the instantiation of the template argument. This is
1263 // required for nested templates.
1264 VD = cast_or_null<ValueDecl>(
1265 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1266 if (!VD)
1267 return ExprError();
1268 } else {
1269 // Propagate NULL template argument.
1270 VD = 0;
1271 }
1272
John McCall645cf442010-02-06 10:23:53 +00001273 // Derive the type we want the substituted decl to have. This had
1274 // better be non-dependent, or these checks will have serious problems.
John McCall91a57552011-07-15 05:09:51 +00001275 if (parm->isExpandedParameterPack()) {
1276 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1277 } else if (parm->isParameterPack() &&
1278 isa<PackExpansionType>(parm->getType())) {
1279 type = SemaRef.SubstType(
1280 cast<PackExpansionType>(parm->getType())->getPattern(),
1281 TemplateArgs, loc, parm->getDeclName());
1282 } else {
1283 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1284 loc, parm->getDeclName());
1285 }
1286 assert(!type.isNull() && "type substitution failed for param type");
1287 assert(!type->isDependentType() && "param type still dependent");
1288 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCallb8fc0532010-02-06 08:42:39 +00001289
John McCall91a57552011-07-15 05:09:51 +00001290 if (!result.isInvalid()) type = result.get()->getType();
1291 } else {
1292 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1293
1294 // Note that this type can be different from the type of 'result',
1295 // e.g. if it's an enum type.
1296 type = arg.getIntegralType();
1297 }
1298 if (result.isInvalid()) return ExprError();
1299
1300 Expr *resultExpr = result.take();
1301 return SemaRef.Owned(new (SemaRef.Context)
1302 SubstNonTypeTemplateParmExpr(type,
1303 resultExpr->getValueKind(),
1304 loc, parm, resultExpr));
John McCallb8fc0532010-02-06 08:42:39 +00001305}
1306
Douglas Gregorc7793c72011-01-15 01:15:58 +00001307ExprResult
1308TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1309 SubstNonTypeTemplateParmPackExpr *E) {
1310 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1311 // We aren't expanding the parameter pack, so just return ourselves.
1312 return getSema().Owned(E);
1313 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001314
1315 TemplateArgument Arg = E->getArgumentPack();
1316 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall91a57552011-07-15 05:09:51 +00001317 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1318 E->getParameterPackLocation(),
1319 Arg);
Douglas Gregorc7793c72011-01-15 01:15:58 +00001320}
John McCallb8fc0532010-02-06 08:42:39 +00001321
John McCall60d7b3a2010-08-24 06:29:42 +00001322ExprResult
Richard Smith9a4db032012-09-12 00:56:43 +00001323TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1324 SourceLocation Loc) {
1325 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1326 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1327}
1328
1329ExprResult
1330TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1331 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1332 // We can expand this parameter pack now.
1333 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1334 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1335 if (!VD)
1336 return ExprError();
1337 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1338 }
1339
1340 QualType T = TransformType(E->getType());
1341 if (T.isNull())
1342 return ExprError();
1343
1344 // Transform each of the parameter expansions into the corresponding
1345 // parameters in the instantiation of the function decl.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001346 SmallVector<Decl *, 8> Parms;
Richard Smith9a4db032012-09-12 00:56:43 +00001347 Parms.reserve(E->getNumExpansions());
1348 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1349 I != End; ++I) {
1350 ParmVarDecl *D =
1351 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1352 if (!D)
1353 return ExprError();
1354 Parms.push_back(D);
1355 }
1356
1357 return FunctionParmPackExpr::Create(getSema().Context, T,
1358 E->getParameterPack(),
1359 E->getParameterPackLocation(), Parms);
1360}
1361
1362ExprResult
1363TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1364 ParmVarDecl *PD) {
1365 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1366 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1367 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1368 assert(Found && "no instantiation for parameter pack");
1369
1370 Decl *TransformedDecl;
1371 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1372 // If this is a reference to a function parameter pack which we can substitute
1373 // but can't yet expand, build a FunctionParmPackExpr for it.
1374 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1375 QualType T = TransformType(E->getType());
1376 if (T.isNull())
1377 return ExprError();
1378 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1379 E->getExprLoc(), *Pack);
1380 }
1381
1382 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1383 } else {
1384 TransformedDecl = Found->get<Decl*>();
1385 }
1386
1387 // We have either an unexpanded pack or a specific expansion.
1388 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1389 E->getExprLoc());
1390}
1391
1392ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001393TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1394 NamedDecl *D = E->getDecl();
Richard Smith9a4db032012-09-12 00:56:43 +00001395
1396 // Handle references to non-type template parameters and non-type template
1397 // parameter packs.
John McCallb8fc0532010-02-06 08:42:39 +00001398 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1399 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1400 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001401
1402 // We have a non-type template parameter that isn't fully substituted;
1403 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregorb98b1992009-08-11 05:31:07 +00001404 }
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Richard Smith9a4db032012-09-12 00:56:43 +00001406 // Handle references to function parameter packs.
1407 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1408 if (PD->isParameterPack())
1409 return TransformFunctionParmPackRefExpr(E, PD);
1410
John McCall454feb92009-12-08 09:21:05 +00001411 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregorb98b1992009-08-11 05:31:07 +00001412}
1413
John McCall60d7b3a2010-08-24 06:29:42 +00001414ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall454feb92009-12-08 09:21:05 +00001415 CXXDefaultArgExpr *E) {
Sebastian Redla29e51b2009-11-08 13:56:19 +00001416 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1417 getDescribedFunctionTemplate() &&
1418 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor036aed12009-12-23 23:03:06 +00001419 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1420 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1421 E->getParam());
Sebastian Redla29e51b2009-11-08 13:56:19 +00001422}
1423
Douglas Gregor895162d2010-04-30 18:55:50 +00001424QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001425 FunctionProtoTypeLoc TL) {
Douglas Gregor895162d2010-04-30 18:55:50 +00001426 // We need a local instantiation scope for this function prototype.
John McCall2a7fb272010-08-25 05:32:35 +00001427 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
John McCall43fed0d2010-11-12 08:19:04 +00001428 return inherited::TransformFunctionProtoType(TLB, TL);
John McCall21ef0fa2010-03-11 09:03:00 +00001429}
1430
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001431QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1432 FunctionProtoTypeLoc TL,
1433 CXXRecordDecl *ThisContext,
1434 unsigned ThisTypeQuals) {
1435 // We need a local instantiation scope for this function prototype.
1436 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1437 return inherited::TransformFunctionProtoType(TLB, TL, ThisContext,
1438 ThisTypeQuals);
1439}
1440
John McCall21ef0fa2010-03-11 09:03:00 +00001441ParmVarDecl *
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001442TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +00001443 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001444 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001445 bool ExpectParameterPack) {
John McCallfb44de92011-05-01 22:35:37 +00001446 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001447 NumExpansions, ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +00001448}
1449
Mike Stump1eb44332009-09-09 15:08:12 +00001450QualType
John McCalla2becad2009-10-21 00:40:46 +00001451TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001452 TemplateTypeParmTypeLoc TL) {
John McCallf4c73712011-01-19 06:33:43 +00001453 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001454 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor99ebf652009-02-27 19:31:52 +00001455 // Replace the template type parameter with its corresponding
1456 // template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00001457
1458 // If the corresponding template argument is NULL or doesn't exist, it's
1459 // because we are performing instantiation from explicitly-specified
1460 // template arguments in a function template class, but there were some
Douglas Gregor16134c62009-07-01 00:28:38 +00001461 // arguments left unspecified.
John McCalla2becad2009-10-21 00:40:46 +00001462 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1463 TemplateTypeParmTypeLoc NewTL
1464 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1465 NewTL.setNameLoc(TL.getNameLoc());
1466 return TL.getType();
1467 }
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001469 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1470
1471 if (T->isParameterPack()) {
1472 assert(Arg.getKind() == TemplateArgument::Pack &&
1473 "Missing argument pack");
1474
1475 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc3069d62011-01-14 02:55:32 +00001476 // We have the template argument pack, but we're not expanding the
1477 // enclosing pack expansion yet. Just save the template argument
1478 // pack for later substitution.
1479 QualType Result
1480 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1481 SubstTemplateTypeParmPackTypeLoc NewTL
1482 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1483 NewTL.setNameLoc(TL.getNameLoc());
1484 return Result;
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001485 }
1486
Eli Friedman10ec0e42013-07-19 19:40:38 +00001487 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001488 }
1489
1490 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregor99ebf652009-02-27 19:31:52 +00001491 "Template argument kind mismatch");
Douglas Gregord6350ae2009-08-28 20:31:08 +00001492
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001493 QualType Replacement = Arg.getAsType();
John McCall49a832b2009-10-18 09:09:24 +00001494
1495 // TODO: only do this uniquing once, at the start of instantiation.
John McCalla2becad2009-10-21 00:40:46 +00001496 QualType Result
1497 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1498 SubstTemplateTypeParmTypeLoc NewTL
1499 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1500 NewTL.setNameLoc(TL.getNameLoc());
1501 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001502 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001503
1504 // The template type parameter comes from an inner template (e.g.,
1505 // the template parameter list of a member template inside the
1506 // template we are instantiating). Create a new template type
1507 // parameter with the template "level" reduced by one.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001508 TemplateTypeParmDecl *NewTTPDecl = 0;
1509 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1510 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1511 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1512
John McCalla2becad2009-10-21 00:40:46 +00001513 QualType Result
1514 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1515 - TemplateArgs.getNumLevels(),
1516 T->getIndex(),
1517 T->isParameterPack(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001518 NewTTPDecl);
John McCalla2becad2009-10-21 00:40:46 +00001519 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1520 NewTL.setNameLoc(TL.getNameLoc());
1521 return Result;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001522}
Douglas Gregor99ebf652009-02-27 19:31:52 +00001523
Douglas Gregorc3069d62011-01-14 02:55:32 +00001524QualType
1525TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1526 TypeLocBuilder &TLB,
1527 SubstTemplateTypeParmPackTypeLoc TL) {
1528 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1529 // We aren't expanding the parameter pack, so just return ourselves.
1530 SubstTemplateTypeParmPackTypeLoc NewTL
1531 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1532 NewTL.setNameLoc(TL.getNameLoc());
1533 return TL.getType();
1534 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001535
1536 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1537 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1538 QualType Result = Arg.getAsType();
1539
Douglas Gregorc3069d62011-01-14 02:55:32 +00001540 Result = getSema().Context.getSubstTemplateTypeParmType(
1541 TL.getTypePtr()->getReplacedParameter(),
1542 Result);
1543 SubstTemplateTypeParmTypeLoc NewTL
1544 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1545 NewTL.setNameLoc(TL.getNameLoc());
1546 return Result;
1547}
1548
John McCallce3ff2b2009-08-25 22:02:44 +00001549/// \brief Perform substitution on the type T with a given set of template
1550/// arguments.
Douglas Gregor99ebf652009-02-27 19:31:52 +00001551///
1552/// This routine substitutes the given template arguments into the
1553/// type T and produces the instantiated type.
1554///
1555/// \param T the type into which the template arguments will be
1556/// substituted. If this type is not dependent, it will be returned
1557/// immediately.
1558///
James Dennett1dfbd922012-06-14 21:40:34 +00001559/// \param Args the template arguments that will be
Douglas Gregor99ebf652009-02-27 19:31:52 +00001560/// substituted for the top-level template parameters within T.
1561///
Douglas Gregor99ebf652009-02-27 19:31:52 +00001562/// \param Loc the location in the source code where this substitution
1563/// is being performed. It will typically be the location of the
1564/// declarator (if we're instantiating the type of some declaration)
1565/// or the location of the type in the source code (if, e.g., we're
1566/// instantiating the type of a cast expression).
1567///
1568/// \param Entity the name of the entity associated with a declaration
1569/// being instantiated (if any). May be empty to indicate that there
1570/// is no such entity (if, e.g., this is a type that occurs as part of
1571/// a cast expression) or that the entity has no name (e.g., an
1572/// unnamed function parameter).
1573///
1574/// \returns If the instantiation succeeds, the instantiated
1575/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCalla93c9342009-12-07 02:54:59 +00001576TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCallcd7ba1c2009-10-21 00:58:09 +00001577 const MultiLevelTemplateArgumentList &Args,
1578 SourceLocation Loc,
1579 DeclarationName Entity) {
1580 assert(!ActiveTemplateInstantiations.empty() &&
1581 "Cannot perform an instantiation without some context on the "
1582 "instantiation stack");
1583
Douglas Gregor561f8122011-07-01 01:22:09 +00001584 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor836adf62010-05-24 17:22:01 +00001585 !T->getType()->isVariablyModifiedType())
John McCallcd7ba1c2009-10-21 00:58:09 +00001586 return T;
1587
1588 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1589 return Instantiator.TransformType(T);
1590}
1591
Douglas Gregor603cfb42011-01-05 23:12:31 +00001592TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1593 const MultiLevelTemplateArgumentList &Args,
1594 SourceLocation Loc,
1595 DeclarationName Entity) {
1596 assert(!ActiveTemplateInstantiations.empty() &&
1597 "Cannot perform an instantiation without some context on the "
1598 "instantiation stack");
1599
1600 if (TL.getType().isNull())
1601 return 0;
1602
Douglas Gregor561f8122011-07-01 01:22:09 +00001603 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor603cfb42011-01-05 23:12:31 +00001604 !TL.getType()->isVariablyModifiedType()) {
1605 // FIXME: Make a copy of the TypeLoc data here, so that we can
1606 // return a new TypeSourceInfo. Inefficient!
1607 TypeLocBuilder TLB;
1608 TLB.pushFullCopy(TL);
1609 return TLB.getTypeSourceInfo(Context, TL.getType());
1610 }
1611
1612 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1613 TypeLocBuilder TLB;
1614 TLB.reserve(TL.getFullDataSize());
1615 QualType Result = Instantiator.TransformType(TLB, TL);
1616 if (Result.isNull())
1617 return 0;
1618
1619 return TLB.getTypeSourceInfo(Context, Result);
1620}
1621
John McCallcd7ba1c2009-10-21 00:58:09 +00001622/// Deprecated form of the above.
Mike Stump1eb44332009-09-09 15:08:12 +00001623QualType Sema::SubstType(QualType T,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001624 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallce3ff2b2009-08-25 22:02:44 +00001625 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregordf667e72009-03-10 20:44:00 +00001626 assert(!ActiveTemplateInstantiations.empty() &&
1627 "Cannot perform an instantiation without some context on the "
1628 "instantiation stack");
1629
Douglas Gregor836adf62010-05-24 17:22:01 +00001630 // If T is not a dependent type or a variably-modified type, there
1631 // is nothing to do.
Douglas Gregor561f8122011-07-01 01:22:09 +00001632 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregor99ebf652009-02-27 19:31:52 +00001633 return T;
1634
Douglas Gregor577f75a2009-08-04 16:50:30 +00001635 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1636 return Instantiator.TransformType(T);
Douglas Gregor99ebf652009-02-27 19:31:52 +00001637}
Douglas Gregor2943aed2009-03-03 04:44:36 +00001638
John McCall6cd3b9f2010-04-09 17:38:44 +00001639static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor561f8122011-07-01 01:22:09 +00001640 if (T->getType()->isInstantiationDependentType() ||
1641 T->getType()->isVariablyModifiedType())
John McCall6cd3b9f2010-04-09 17:38:44 +00001642 return true;
1643
Abramo Bagnara723df242010-12-14 22:11:44 +00001644 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00001645 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCall6cd3b9f2010-04-09 17:38:44 +00001646 return false;
1647
David Blaikie39e6ab42013-02-18 22:06:02 +00001648 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
John McCall6cd3b9f2010-04-09 17:38:44 +00001649 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1650 ParmVarDecl *P = FP.getArg(I);
1651
Reid Klecknerc66e7e92013-07-31 21:00:18 +00001652 // This must be synthesized from a typedef.
1653 if (!P) continue;
1654
Douglas Gregorc056c172011-05-09 20:45:16 +00001655 // The parameter's type as written might be dependent even if the
1656 // decayed type was not dependent.
1657 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
Douglas Gregor561f8122011-07-01 01:22:09 +00001658 if (TSInfo->getType()->isInstantiationDependentType())
Douglas Gregorc056c172011-05-09 20:45:16 +00001659 return true;
1660
John McCall6cd3b9f2010-04-09 17:38:44 +00001661 // TODO: currently we always rebuild expressions. When we
1662 // properly get lazier about this, we should use the same
1663 // logic to avoid rebuilding prototypes here.
Douglas Gregor7b1cf302011-01-05 21:14:17 +00001664 if (P->hasDefaultArg())
John McCall6cd3b9f2010-04-09 17:38:44 +00001665 return true;
1666 }
1667
1668 return false;
1669}
1670
1671/// A form of SubstType intended specifically for instantiating the
1672/// type of a FunctionDecl. Its purpose is solely to force the
1673/// instantiation of default-argument expressions.
1674TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1675 const MultiLevelTemplateArgumentList &Args,
1676 SourceLocation Loc,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001677 DeclarationName Entity,
1678 CXXRecordDecl *ThisContext,
1679 unsigned ThisTypeQuals) {
John McCall6cd3b9f2010-04-09 17:38:44 +00001680 assert(!ActiveTemplateInstantiations.empty() &&
1681 "Cannot perform an instantiation without some context on the "
1682 "instantiation stack");
1683
1684 if (!NeedsInstantiationAsFunctionType(T))
1685 return T;
1686
1687 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1688
1689 TypeLocBuilder TLB;
1690
1691 TypeLoc TL = T->getTypeLoc();
1692 TLB.reserve(TL.getFullDataSize());
1693
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001694 QualType Result;
David Blaikie39e6ab42013-02-18 22:06:02 +00001695
1696 if (FunctionProtoTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
1697 Result = Instantiator.TransformFunctionProtoType(TLB, Proto, ThisContext,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001698 ThisTypeQuals);
1699 } else {
1700 Result = Instantiator.TransformType(TLB, TL);
1701 }
John McCall6cd3b9f2010-04-09 17:38:44 +00001702 if (Result.isNull())
1703 return 0;
1704
1705 return TLB.getTypeSourceInfo(Context, Result);
1706}
1707
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001708ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001709 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallfb44de92011-05-01 22:35:37 +00001710 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001711 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001712 bool ExpectParameterPack) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001713 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Douglas Gregor603cfb42011-01-05 23:12:31 +00001714 TypeSourceInfo *NewDI = 0;
1715
Douglas Gregor603cfb42011-01-05 23:12:31 +00001716 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00001717 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1718
Douglas Gregor603cfb42011-01-05 23:12:31 +00001719 // We have a function parameter pack. Substitute into the pattern of the
1720 // expansion.
1721 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1722 OldParm->getLocation(), OldParm->getDeclName());
1723 if (!NewDI)
1724 return 0;
1725
1726 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1727 // We still have unexpanded parameter packs, which means that
1728 // our function parameter is still a function parameter pack.
1729 // Therefore, make its type a pack expansion type.
Douglas Gregorcded4f62011-01-14 17:04:44 +00001730 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001731 NumExpansions);
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001732 } else if (ExpectParameterPack) {
1733 // We expected to get a parameter pack but didn't (because the type
1734 // itself is not a pack expansion type), so complain. This can occur when
1735 // the substitution goes through an alias template that "loses" the
1736 // pack expansion.
1737 Diag(OldParm->getLocation(),
1738 diag::err_function_parameter_pack_without_parameter_packs)
1739 << NewDI->getType();
1740 return 0;
1741 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001742 } else {
1743 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1744 OldParm->getDeclName());
1745 }
1746
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001747 if (!NewDI)
1748 return 0;
1749
1750 if (NewDI->getType()->isVoidType()) {
1751 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1752 return 0;
1753 }
1754
1755 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001756 OldParm->getInnerLocStart(),
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001757 OldParm->getLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001758 OldParm->getIdentifier(),
1759 NewDI->getType(), NewDI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001760 OldParm->getStorageClass());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001761 if (!NewParm)
1762 return 0;
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001763
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001764 // Mark the (new) default argument as uninstantiated (if any).
1765 if (OldParm->hasUninstantiatedDefaultArg()) {
1766 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1767 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor8cfb7a32010-10-12 18:23:32 +00001768 } else if (OldParm->hasUnparsedDefaultArg()) {
1769 NewParm->setUnparsedDefaultArg();
1770 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
David Blaikie57296722012-05-01 06:05:57 +00001771 } else if (Expr *Arg = OldParm->getDefaultArg())
1772 // FIXME: if we non-lazily instantiated non-dependent default args for
1773 // non-dependent parameter types we could remove a bunch of duplicate
1774 // conversion warnings for such arguments.
1775 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001776
1777 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001778
Douglas Gregor12c9c002011-01-07 16:43:16 +00001779 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smithc0536c82012-01-25 02:14:59 +00001780 // Add the new parameter to the instantiated parameter pack.
Douglas Gregor12c9c002011-01-07 16:43:16 +00001781 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1782 } else {
1783 // Introduce an Old -> New mapping
Douglas Gregor603cfb42011-01-05 23:12:31 +00001784 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregor12c9c002011-01-07 16:43:16 +00001785 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001786
Argyrios Kyrtzidise3041be2010-07-19 10:14:41 +00001787 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1788 // can be anything, is this right ?
Fariborz Jahanian55a17c02010-07-13 21:05:02 +00001789 NewParm->setDeclContext(CurContext);
John McCallfb44de92011-05-01 22:35:37 +00001790
1791 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1792 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rose09189892013-03-08 22:25:36 +00001793
1794 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1795
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001796 return NewParm;
1797}
1798
Douglas Gregora009b592011-01-07 00:20:55 +00001799/// \brief Substitute the given template arguments into the given set of
1800/// parameters, producing the set of parameter types that would be generated
1801/// from such a substitution.
1802bool Sema::SubstParmTypes(SourceLocation Loc,
1803 ParmVarDecl **Params, unsigned NumParams,
1804 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001805 SmallVectorImpl<QualType> &ParamTypes,
1806 SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregora009b592011-01-07 00:20:55 +00001807 assert(!ActiveTemplateInstantiations.empty() &&
1808 "Cannot perform an instantiation without some context on the "
1809 "instantiation stack");
1810
1811 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1812 DeclarationName());
1813 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001814 ParamTypes, OutParams);
Douglas Gregora009b592011-01-07 00:20:55 +00001815}
1816
John McCallce3ff2b2009-08-25 22:02:44 +00001817/// \brief Perform substitution on the base class specifiers of the
1818/// given class template specialization.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001819///
1820/// Produces a diagnostic and returns true on error, returns false and
1821/// attaches the instantiated base classes to the class template
1822/// specialization if successful.
Mike Stump1eb44332009-09-09 15:08:12 +00001823bool
John McCallce3ff2b2009-08-25 22:02:44 +00001824Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1825 CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001826 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001827 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001828 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Mike Stump1eb44332009-09-09 15:08:12 +00001829 for (ClassTemplateSpecializationDecl::base_class_iterator
Douglas Gregord475b8d2009-03-25 21:17:03 +00001830 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
Douglas Gregor27b152f2009-03-10 18:52:44 +00001831 Base != BaseEnd; ++Base) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001832 if (!Base->getType()->isDependentType()) {
Matt Beaumont-Gay538fccb2013-06-21 18:58:32 +00001833 if (const CXXRecordDecl *RD = Base->getType()->getAsCXXRecordDecl()) {
1834 if (RD->isInvalidDecl())
1835 Instantiation->setInvalidDecl();
1836 }
Fariborz Jahanian71c6e712009-07-22 17:41:53 +00001837 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
Douglas Gregor2943aed2009-03-03 04:44:36 +00001838 continue;
1839 }
1840
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001841 SourceLocation EllipsisLoc;
Douglas Gregor406f98f2011-03-02 02:04:06 +00001842 TypeSourceInfo *BaseTypeLoc;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001843 if (Base->isPackExpansion()) {
1844 // This is a pack expansion. See whether we should expand it now, or
1845 // wait until later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001846 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001847 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1848 Unexpanded);
1849 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00001850 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001851 Optional<unsigned> NumExpansions;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001852 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1853 Base->getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001854 Unexpanded,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001855 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00001856 RetainExpansion,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001857 NumExpansions)) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001858 Invalid = true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001859 continue;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001860 }
1861
1862 // If we should expand this pack expansion now, do so.
1863 if (ShouldExpand) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00001864 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001865 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1866
1867 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1868 TemplateArgs,
1869 Base->getSourceRange().getBegin(),
1870 DeclarationName());
1871 if (!BaseTypeLoc) {
1872 Invalid = true;
1873 continue;
1874 }
1875
1876 if (CXXBaseSpecifier *InstantiatedBase
1877 = CheckBaseSpecifier(Instantiation,
1878 Base->getSourceRange(),
1879 Base->isVirtual(),
1880 Base->getAccessSpecifierAsWritten(),
1881 BaseTypeLoc,
1882 SourceLocation()))
1883 InstantiatedBases.push_back(InstantiatedBase);
1884 else
1885 Invalid = true;
1886 }
1887
1888 continue;
1889 }
1890
1891 // The resulting base specifier will (still) be a pack expansion.
1892 EllipsisLoc = Base->getEllipsisLoc();
Douglas Gregor406f98f2011-03-02 02:04:06 +00001893 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1894 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1895 TemplateArgs,
1896 Base->getSourceRange().getBegin(),
1897 DeclarationName());
1898 } else {
1899 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1900 TemplateArgs,
1901 Base->getSourceRange().getBegin(),
1902 DeclarationName());
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001903 }
1904
Nick Lewycky56062202010-07-26 16:56:01 +00001905 if (!BaseTypeLoc) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001906 Invalid = true;
1907 continue;
1908 }
1909
1910 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregord475b8d2009-03-25 21:17:03 +00001911 = CheckBaseSpecifier(Instantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001912 Base->getSourceRange(),
1913 Base->isVirtual(),
1914 Base->getAccessSpecifierAsWritten(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001915 BaseTypeLoc,
1916 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001917 InstantiatedBases.push_back(InstantiatedBase);
1918 else
1919 Invalid = true;
1920 }
1921
Douglas Gregor27b152f2009-03-10 18:52:44 +00001922 if (!Invalid &&
Jay Foadbeaaccd2009-05-21 09:52:38 +00001923 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001924 InstantiatedBases.size()))
1925 Invalid = true;
1926
1927 return Invalid;
1928}
1929
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001930// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramer5bbc3852012-02-06 11:13:08 +00001931namespace clang {
1932 namespace sema {
1933 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1934 const MultiLevelTemplateArgumentList &TemplateArgs);
1935 }
1936}
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001937
Richard Smithf1c66b42012-03-14 23:13:10 +00001938/// Determine whether we would be unable to instantiate this template (because
1939/// it either has no definition, or is in the process of being instantiated).
1940static bool DiagnoseUninstantiableTemplate(Sema &S,
1941 SourceLocation PointOfInstantiation,
1942 TagDecl *Instantiation,
1943 bool InstantiatedFromMember,
1944 TagDecl *Pattern,
1945 TagDecl *PatternDef,
1946 TemplateSpecializationKind TSK,
1947 bool Complain = true) {
1948 if (PatternDef && !PatternDef->isBeingDefined())
1949 return false;
1950
1951 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1952 // Say nothing
1953 } else if (PatternDef) {
1954 assert(PatternDef->isBeingDefined());
1955 S.Diag(PointOfInstantiation,
1956 diag::err_template_instantiate_within_definition)
1957 << (TSK != TSK_ImplicitInstantiation)
1958 << S.Context.getTypeDeclType(Instantiation);
1959 // Not much point in noting the template declaration here, since
1960 // we're lexically inside it.
1961 Instantiation->setInvalidDecl();
1962 } else if (InstantiatedFromMember) {
1963 S.Diag(PointOfInstantiation,
1964 diag::err_implicit_instantiate_member_undefined)
1965 << S.Context.getTypeDeclType(Instantiation);
1966 S.Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1967 } else {
1968 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1969 << (TSK != TSK_ImplicitInstantiation)
1970 << S.Context.getTypeDeclType(Instantiation);
1971 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1972 }
1973
1974 // In general, Instantiation isn't marked invalid to get more than one
1975 // error for multiple undefined instantiations. But the code that does
1976 // explicit declaration -> explicit definition conversion can't handle
1977 // invalid declarations, so mark as invalid in that case.
1978 if (TSK == TSK_ExplicitInstantiationDeclaration)
1979 Instantiation->setInvalidDecl();
1980 return true;
1981}
1982
Douglas Gregord475b8d2009-03-25 21:17:03 +00001983/// \brief Instantiate the definition of a class from a given pattern.
1984///
1985/// \param PointOfInstantiation The point of instantiation within the
1986/// source code.
1987///
1988/// \param Instantiation is the declaration whose definition is being
1989/// instantiated. This will be either a class template specialization
1990/// or a member class of a class template specialization.
1991///
1992/// \param Pattern is the pattern from which the instantiation
1993/// occurs. This will be either the declaration of a class template or
1994/// the declaration of a member class of a class template.
1995///
1996/// \param TemplateArgs The template arguments to be substituted into
1997/// the pattern.
1998///
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001999/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor5842ba92009-08-24 15:23:48 +00002000///
2001/// \param Complain whether to complain if the class cannot be instantiated due
2002/// to the lack of a definition.
2003///
Douglas Gregord475b8d2009-03-25 21:17:03 +00002004/// \returns true if an error occurred, false otherwise.
2005bool
2006Sema::InstantiateClass(SourceLocation PointOfInstantiation,
2007 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002008 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002009 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002010 bool Complain) {
Mike Stump1eb44332009-09-09 15:08:12 +00002011 CXXRecordDecl *PatternDef
Douglas Gregor952b0172010-02-11 01:04:33 +00002012 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Richard Smithf1c66b42012-03-14 23:13:10 +00002013 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2014 Instantiation->getInstantiatedFromMemberClass(),
2015 Pattern, PatternDef, TSK, Complain))
Douglas Gregord475b8d2009-03-25 21:17:03 +00002016 return true;
Douglas Gregord475b8d2009-03-25 21:17:03 +00002017 Pattern = PatternDef;
2018
Douglas Gregor454885e2009-10-15 15:54:05 +00002019 // \brief Record the point of instantiation.
2020 if (MemberSpecializationInfo *MSInfo
2021 = Instantiation->getMemberSpecializationInfo()) {
2022 MSInfo->setTemplateSpecializationKind(TSK);
2023 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002024 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weberc7feca02011-12-20 20:32:49 +00002025 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002026 Spec->setTemplateSpecializationKind(TSK);
2027 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00002028 }
2029
Douglas Gregord048bb72009-03-25 21:23:52 +00002030 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00002031 if (Inst)
2032 return true;
2033
2034 // Enter the scope of this instantiation. We don't use
2035 // PushDeclContext because we don't have a scope.
John McCallf5813822010-04-29 00:35:03 +00002036 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor9679caf2010-05-12 17:27:19 +00002037 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002038 Sema::PotentiallyEvaluated);
Douglas Gregord475b8d2009-03-25 21:17:03 +00002039
Douglas Gregor05030bb2010-03-24 01:33:17 +00002040 // If this is an instantiation of a local class, merge this local
2041 // instantiation scope with the enclosing scope. Otherwise, every
2042 // instantiation of a class has its own local instantiation scope.
2043 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall2a7fb272010-08-25 05:32:35 +00002044 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor05030bb2010-03-24 01:33:17 +00002045
John McCall1d8d1cc2010-08-01 02:01:53 +00002046 // Pull attributes from the pattern onto the instantiation.
2047 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2048
Douglas Gregord475b8d2009-03-25 21:17:03 +00002049 // Start the definition of this instantiation.
2050 Instantiation->startDefinition();
Douglas Gregor13c85772010-05-06 00:28:52 +00002051
2052 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregord475b8d2009-03-25 21:17:03 +00002053
John McCallce3ff2b2009-08-25 22:02:44 +00002054 // Do substitution on the base class specifiers.
2055 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002056 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002057
Douglas Gregord65587f2010-11-10 19:44:59 +00002058 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002059 SmallVector<Decl*, 4> Fields;
2060 SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
Richard Smith7a614d82011-06-11 17:19:42 +00002061 FieldsWithMemberInitializers;
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002062 // Delay instantiation of late parsed attributes.
2063 LateInstantiatedAttrVec LateAttrs;
2064 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2065
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002066 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002067 MemberEnd = Pattern->decls_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002068 Member != MemberEnd; ++Member) {
Argyrios Kyrtzidisbb5e4312010-11-04 03:18:57 +00002069 // Don't instantiate members not belonging in this semantic context.
2070 // e.g. for:
2071 // @code
2072 // template <int i> class A {
2073 // class B *g;
2074 // };
2075 // @endcode
2076 // 'class B' has the template as lexical context but semantically it is
2077 // introduced in namespace scope.
2078 if ((*Member)->getDeclContext() != Pattern)
2079 continue;
2080
Douglas Gregord65587f2010-11-10 19:44:59 +00002081 if ((*Member)->isInvalidDecl()) {
Richard Smithe3f470a2012-07-11 22:37:56 +00002082 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00002083 continue;
2084 }
2085
2086 Decl *NewMember = Instantiator.Visit(*Member);
Douglas Gregord475b8d2009-03-25 21:17:03 +00002087 if (NewMember) {
Richard Smith7a614d82011-06-11 17:19:42 +00002088 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCalld226f652010-08-21 09:40:31 +00002089 Fields.push_back(Field);
Richard Smith7a614d82011-06-11 17:19:42 +00002090 FieldDecl *OldField = cast<FieldDecl>(*Member);
2091 if (OldField->getInClassInitializer())
2092 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
2093 Field));
Richard Smith1af83c42012-03-23 03:33:32 +00002094 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2095 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2096 // specialization causes the implicit instantiation of the definitions
2097 // of unscoped member enumerations.
2098 // Record a point of instantiation for this implicit instantiation.
Richard Smith3343fad2012-03-23 23:09:08 +00002099 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2100 Enum->isCompleteDefinition()) {
Richard Smith1af83c42012-03-23 03:33:32 +00002101 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2102 assert(MSInfo && "no spec info for member enum specialization");
2103 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2104 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2105 }
Richard Smithe3f470a2012-07-11 22:37:56 +00002106 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2107 if (SA->isFailed()) {
2108 // A static_assert failed. Bail out; instantiating this
2109 // class is probably not meaningful.
2110 Instantiation->setInvalidDecl();
2111 break;
2112 }
Richard Smith1af83c42012-03-23 03:33:32 +00002113 }
2114
2115 if (NewMember->isInvalidDecl())
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002116 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002117 } else {
2118 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002119 // instantiations was a semantic disaster, and we'll want to mark the
2120 // declaration invalid.
2121 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregord475b8d2009-03-25 21:17:03 +00002122 }
2123 }
2124
2125 // Finish checking fields.
David Blaikie77b6de02011-09-22 02:58:26 +00002126 ActOnFields(0, Instantiation->getLocation(), Instantiation, Fields,
2127 SourceLocation(), SourceLocation(), 0);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002128 CheckCompletedCXXClass(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002129
2130 // Attach any in-class member initializers now the class is complete.
Richard Smithd5be2b52012-12-08 02:13:02 +00002131 // FIXME: We are supposed to defer instantiating these until they are needed.
Benjamin Kramer268efba2012-05-17 12:01:52 +00002132 if (!FieldsWithMemberInitializers.empty()) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002133 // C++11 [expr.prim.general]p4:
2134 // Otherwise, if a member-declarator declares a non-static data member
2135 // (9.2) of a class X, the expression this is a prvalue of type "pointer
2136 // to X" within the optional brace-or-equal-initializer. It shall not
2137 // appear elsewhere in the member-declarator.
2138 CXXThisScopeRAII ThisScope(*this, Instantiation, (unsigned)0);
2139
2140 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
2141 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
2142 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
2143 Expr *OldInit = OldField->getInClassInitializer();
Richard Smith7a614d82011-06-11 17:19:42 +00002144
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002145 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2146 /*CXXDirectInit=*/false);
2147 if (NewInit.isInvalid())
2148 NewField->setInvalidDecl();
2149 else {
2150 Expr *Init = NewInit.take();
2151 assert(Init && "no-argument initializer in class");
2152 assert(!isa<ParenListExpr>(Init) && "call-style init in class");
Richard Smithca523302012-06-10 03:12:00 +00002153 ActOnCXXInClassMemberInitializer(NewField, Init->getLocStart(), Init);
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002154 }
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002155 }
Richard Smith7a614d82011-06-11 17:19:42 +00002156 }
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002157 // Instantiate late parsed attributes, and attach them to their decls.
2158 // See Sema::InstantiateAttrs
2159 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2160 E = LateAttrs.end(); I != E; ++I) {
2161 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2162 CurrentInstantiationScope = I->Scope;
Richard Smithcafeb942013-06-07 02:33:37 +00002163
2164 // Allow 'this' within late-parsed attributes.
2165 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2166 CXXRecordDecl *ThisContext =
2167 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2168 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2169 ND && ND->isCXXInstanceMember());
2170
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002171 Attr *NewAttr =
2172 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2173 I->NewDecl->addAttr(NewAttr);
2174 LocalInstantiationScope::deleteScopes(I->Scope,
2175 Instantiator.getStartingScope());
2176 }
2177 Instantiator.disableLateAttributeInstantiation();
2178 LateAttrs.clear();
2179
Richard Smithb9d0b762012-07-27 04:22:15 +00002180 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002181
Abramo Bagnarae9946242011-11-18 08:08:52 +00002182 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis734bd6e2012-02-11 01:59:57 +00002183 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002184 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnara09d82122011-10-03 20:34:03 +00002185 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002186 }
Abramo Bagnara09d82122011-10-03 20:34:03 +00002187
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002188 if (!Instantiation->isInvalidDecl()) {
John McCall1f2e1a92012-08-10 03:15:35 +00002189 // Perform any dependent diagnostics from the pattern.
2190 PerformDependentDiagnostics(Pattern, TemplateArgs);
2191
Douglas Gregord65587f2010-11-10 19:44:59 +00002192 // Instantiate any out-of-line class template partial
2193 // specializations now.
Richard Smithe688ddf2013-09-26 03:49:48 +00002194 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregord65587f2010-11-10 19:44:59 +00002195 P = Instantiator.delayed_partial_spec_begin(),
2196 PEnd = Instantiator.delayed_partial_spec_end();
2197 P != PEnd; ++P) {
2198 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smithe688ddf2013-09-26 03:49:48 +00002199 P->first, P->second)) {
2200 Instantiation->setInvalidDecl();
2201 break;
2202 }
2203 }
2204
2205 // Instantiate any out-of-line variable template partial
2206 // specializations now.
2207 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2208 P = Instantiator.delayed_var_partial_spec_begin(),
2209 PEnd = Instantiator.delayed_var_partial_spec_end();
2210 P != PEnd; ++P) {
2211 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2212 P->first, P->second)) {
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002213 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00002214 break;
2215 }
2216 }
2217 }
2218
Douglas Gregord475b8d2009-03-25 21:17:03 +00002219 // Exit the scope of this instantiation.
John McCallf5813822010-04-29 00:35:03 +00002220 SavedContext.pop();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002221
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002222 if (!Instantiation->isInvalidDecl()) {
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002223 Consumer.HandleTagDeclDefinition(Instantiation);
2224
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002225 // Always emit the vtable for an explicit instantiation definition
2226 // of a polymorphic class template specialization.
2227 if (TSK == TSK_ExplicitInstantiationDefinition)
2228 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2229 }
2230
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002231 return Instantiation->isInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002232}
2233
Richard Smithf1c66b42012-03-14 23:13:10 +00002234/// \brief Instantiate the definition of an enum from a given pattern.
2235///
2236/// \param PointOfInstantiation The point of instantiation within the
2237/// source code.
2238/// \param Instantiation is the declaration whose definition is being
2239/// instantiated. This will be a member enumeration of a class
2240/// temploid specialization, or a local enumeration within a
2241/// function temploid specialization.
2242/// \param Pattern The templated declaration from which the instantiation
2243/// occurs.
2244/// \param TemplateArgs The template arguments to be substituted into
2245/// the pattern.
2246/// \param TSK The kind of implicit or explicit instantiation to perform.
2247///
2248/// \return \c true if an error occurred, \c false otherwise.
2249bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2250 EnumDecl *Instantiation, EnumDecl *Pattern,
2251 const MultiLevelTemplateArgumentList &TemplateArgs,
2252 TemplateSpecializationKind TSK) {
2253 EnumDecl *PatternDef = Pattern->getDefinition();
2254 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2255 Instantiation->getInstantiatedFromMemberEnum(),
2256 Pattern, PatternDef, TSK,/*Complain*/true))
2257 return true;
2258 Pattern = PatternDef;
2259
2260 // Record the point of instantiation.
2261 if (MemberSpecializationInfo *MSInfo
2262 = Instantiation->getMemberSpecializationInfo()) {
2263 MSInfo->setTemplateSpecializationKind(TSK);
2264 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2265 }
2266
2267 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2268 if (Inst)
2269 return true;
2270
2271 // Enter the scope of this instantiation. We don't use
2272 // PushDeclContext because we don't have a scope.
2273 ContextRAII SavedContext(*this, Instantiation);
2274 EnterExpressionEvaluationContext EvalContext(*this,
2275 Sema::PotentiallyEvaluated);
2276
2277 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2278
2279 // Pull attributes from the pattern onto the instantiation.
2280 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2281
2282 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2283 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2284
2285 // Exit the scope of this instantiation.
2286 SavedContext.pop();
2287
2288 return Instantiation->isInvalidDecl();
2289}
2290
Douglas Gregor9b623632010-10-12 23:32:35 +00002291namespace {
2292 /// \brief A partial specialization whose template arguments have matched
2293 /// a given template-id.
2294 struct PartialSpecMatchResult {
2295 ClassTemplatePartialSpecializationDecl *Partial;
2296 TemplateArgumentList *Args;
Douglas Gregor9b623632010-10-12 23:32:35 +00002297 };
2298}
2299
Larisse Voufo567f9172013-08-22 00:59:14 +00002300bool Sema::InstantiateClassTemplateSpecialization(
2301 SourceLocation PointOfInstantiation,
2302 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2303 TemplateSpecializationKind TSK, bool Complain) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00002304 // Perform the actual instantiation on the canonical declaration.
2305 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002306 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor2943aed2009-03-03 04:44:36 +00002307
Douglas Gregor52604ab2009-09-11 21:19:12 +00002308 // Check whether we have already instantiated or specialized this class
2309 // template specialization.
2310 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2311 if (ClassTemplateSpec->getSpecializationKind() ==
2312 TSK_ExplicitInstantiationDeclaration &&
2313 TSK == TSK_ExplicitInstantiationDefinition) {
2314 // An explicit instantiation definition follows an explicit instantiation
2315 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2316 // explicit instantiation.
2317 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002318
2319 // If this is an explicit instantiation definition, mark the
2320 // vtable as used.
Nico Weberc7feca02011-12-20 20:32:49 +00002321 if (TSK == TSK_ExplicitInstantiationDefinition &&
2322 !ClassTemplateSpec->isInvalidDecl())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002323 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2324
Douglas Gregor52604ab2009-09-11 21:19:12 +00002325 return false;
2326 }
2327
2328 // We can only instantiate something that hasn't already been
2329 // instantiated or specialized. Fail without any diagnostics: our
2330 // caller will provide an error message.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002331 return true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00002332 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002333
Douglas Gregor9eea08b2009-09-15 16:51:42 +00002334 if (ClassTemplateSpec->isInvalidDecl())
2335 return true;
2336
Douglas Gregor2943aed2009-03-03 04:44:36 +00002337 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregord6350ae2009-08-28 20:31:08 +00002338 CXXRecordDecl *Pattern = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002339
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002340 // C++ [temp.class.spec.match]p1:
2341 // When a class template is used in a context that requires an
2342 // instantiation of the class, it is necessary to determine
2343 // whether the instantiation is to be generated using the primary
2344 // template or one of the partial specializations. This is done by
2345 // matching the template arguments of the class template
2346 // specialization with the template argument lists of the partial
2347 // specializations.
Douglas Gregor9b623632010-10-12 23:32:35 +00002348 typedef PartialSpecMatchResult MatchResult;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002349 SmallVector<MatchResult, 4> Matched;
2350 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002351 Template->getPartialSpecializations(PartialSpecs);
Larisse Voufo43847122013-07-19 23:00:19 +00002352 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002353 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2354 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo43847122013-07-19 23:00:19 +00002355 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorf67875d2009-06-12 18:26:56 +00002356 if (TemplateDeductionResult Result
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002357 = DeduceTemplateArguments(Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00002358 ClassTemplateSpec->getTemplateArgs(),
2359 Info)) {
Larisse Voufo43847122013-07-19 23:00:19 +00002360 // Store the failed-deduction information for use in diagnostics, later.
2361 // TODO: Actually use the failed-deduction info?
2362 FailedCandidates.addCandidate()
2363 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorf67875d2009-06-12 18:26:56 +00002364 (void)Result;
2365 } else {
Douglas Gregor9b623632010-10-12 23:32:35 +00002366 Matched.push_back(PartialSpecMatchResult());
2367 Matched.back().Partial = Partial;
2368 Matched.back().Args = Info.take();
Douglas Gregorf67875d2009-06-12 18:26:56 +00002369 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002370 }
2371
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002372 // If we're dealing with a member template where the template parameters
2373 // have been instantiated, this provides the original template parameters
2374 // from which the member template's parameters were instantiated.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002375 SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002376
Douglas Gregored9c0f92009-10-29 00:04:11 +00002377 if (Matched.size() >= 1) {
Craig Topper09d19ef2013-07-04 03:08:24 +00002378 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002379 if (Matched.size() == 1) {
2380 // -- If exactly one matching specialization is found, the
2381 // instantiation is generated from that specialization.
2382 // We don't need to do anything for this.
2383 } else {
2384 // -- If more than one matching specialization is found, the
2385 // partial order rules (14.5.4.2) are used to determine
2386 // whether one of the specializations is more specialized
2387 // than the others. If none of the specializations is more
2388 // specialized than all of the other matching
2389 // specializations, then the use of the class template is
2390 // ambiguous and the program is ill-formed.
Craig Topper09d19ef2013-07-04 03:08:24 +00002391 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2392 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002393 P != PEnd; ++P) {
Douglas Gregor9b623632010-10-12 23:32:35 +00002394 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002395 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002396 == P->Partial)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002397 Best = P;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002398 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002399
Douglas Gregored9c0f92009-10-29 00:04:11 +00002400 // Determine if the best partial specialization is more specialized than
2401 // the others.
2402 bool Ambiguous = false;
Craig Topper09d19ef2013-07-04 03:08:24 +00002403 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2404 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002405 P != PEnd; ++P) {
2406 if (P != Best &&
Douglas Gregor9b623632010-10-12 23:32:35 +00002407 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002408 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002409 != Best->Partial) {
Douglas Gregored9c0f92009-10-29 00:04:11 +00002410 Ambiguous = true;
2411 break;
2412 }
2413 }
2414
2415 if (Ambiguous) {
2416 // Partial ordering did not produce a clear winner. Complain.
2417 ClassTemplateSpec->setInvalidDecl();
2418 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2419 << ClassTemplateSpec;
2420
2421 // Print the matching partial specializations.
Craig Topper09d19ef2013-07-04 03:08:24 +00002422 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2423 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002424 P != PEnd; ++P)
Douglas Gregor9b623632010-10-12 23:32:35 +00002425 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2426 << getTemplateArgumentBindingsText(
2427 P->Partial->getTemplateParameters(),
2428 *P->Args);
Douglas Gregord6350ae2009-08-28 20:31:08 +00002429
Douglas Gregored9c0f92009-10-29 00:04:11 +00002430 return true;
2431 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002432 }
2433
2434 // Instantiate using the best class template partial specialization.
Douglas Gregor9b623632010-10-12 23:32:35 +00002435 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002436 while (OrigPartialSpec->getInstantiatedFromMember()) {
2437 // If we've found an explicit specialization of this class template,
2438 // stop here and use that as the pattern.
2439 if (OrigPartialSpec->isMemberSpecialization())
2440 break;
2441
2442 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2443 }
2444
2445 Pattern = OrigPartialSpec;
Douglas Gregor9b623632010-10-12 23:32:35 +00002446 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002447 } else {
2448 // -- If no matches are found, the instantiation is generated
2449 // from the primary template.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002450 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002451 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2452 // If we've found an explicit specialization of this class template,
2453 // stop here and use that as the pattern.
2454 if (OrigTemplate->isMemberSpecialization())
2455 break;
2456
Douglas Gregord6350ae2009-08-28 20:31:08 +00002457 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002458 }
2459
Douglas Gregord6350ae2009-08-28 20:31:08 +00002460 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002461 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002462
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002463 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2464 Pattern,
2465 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002466 TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002467 Complain);
Mike Stump1eb44332009-09-09 15:08:12 +00002468
Douglas Gregor199d9912009-06-05 00:53:49 +00002469 return Result;
Douglas Gregor2943aed2009-03-03 04:44:36 +00002470}
Douglas Gregor5953d8b2009-03-19 17:26:29 +00002471
John McCallce3ff2b2009-08-25 22:02:44 +00002472/// \brief Instantiates the definitions of all of the member
2473/// of the given class, which is an instantiation of a class template
2474/// or a member class of a template.
Douglas Gregora58861f2009-05-13 20:28:22 +00002475void
2476Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002477 CXXRecordDecl *Instantiation,
2478 const MultiLevelTemplateArgumentList &TemplateArgs,
2479 TemplateSpecializationKind TSK) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002480 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
2481 DEnd = Instantiation->decls_end();
Douglas Gregora58861f2009-05-13 20:28:22 +00002482 D != DEnd; ++D) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002483 bool SuppressNew = false;
Douglas Gregora58861f2009-05-13 20:28:22 +00002484 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002485 if (FunctionDecl *Pattern
2486 = Function->getInstantiatedFromMemberFunction()) {
2487 MemberSpecializationInfo *MSInfo
2488 = Function->getMemberSpecializationInfo();
2489 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002490 if (MSInfo->getTemplateSpecializationKind()
2491 == TSK_ExplicitSpecialization)
2492 continue;
2493
Douglas Gregor0d035142009-10-27 18:42:08 +00002494 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2495 Function,
2496 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002497 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002498 SuppressNew) ||
2499 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002500 continue;
2501
Sean Hunt10620eb2011-05-06 20:44:56 +00002502 if (Function->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002503 continue;
2504
2505 if (TSK == TSK_ExplicitInstantiationDefinition) {
2506 // C++0x [temp.explicit]p8:
2507 // An explicit instantiation definition that names a class template
2508 // specialization explicitly instantiates the class template
2509 // specialization and is only an explicit instantiation definition
2510 // of members whose definition is visible at the point of
2511 // instantiation.
Sean Hunt10620eb2011-05-06 20:44:56 +00002512 if (!Pattern->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002513 continue;
2514
2515 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2516
2517 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2518 } else {
2519 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2520 }
Douglas Gregorf6b11852009-10-08 15:14:33 +00002521 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002522 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
Richard Smithd0629eb2013-09-27 20:14:12 +00002523 if (isa<VarTemplateSpecializationDecl>(Var))
2524 continue;
2525
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002526 if (Var->isStaticDataMember()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002527 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2528 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002529 if (MSInfo->getTemplateSpecializationKind()
2530 == TSK_ExplicitSpecialization)
2531 continue;
2532
Douglas Gregor0d035142009-10-27 18:42:08 +00002533 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2534 Var,
2535 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002536 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002537 SuppressNew) ||
2538 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002539 continue;
2540
Douglas Gregor0d035142009-10-27 18:42:08 +00002541 if (TSK == TSK_ExplicitInstantiationDefinition) {
2542 // C++0x [temp.explicit]p8:
2543 // An explicit instantiation definition that names a class template
2544 // specialization explicitly instantiates the class template
2545 // specialization and is only an explicit instantiation definition
2546 // of members whose definition is visible at the point of
2547 // instantiation.
2548 if (!Var->getInstantiatedFromStaticDataMember()
2549 ->getOutOfLineDefinition())
2550 continue;
2551
2552 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002553 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor0d035142009-10-27 18:42:08 +00002554 } else {
2555 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2556 }
2557 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002558 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
Douglas Gregora77eaa92010-04-18 18:11:38 +00002559 // Always skip the injected-class-name, along with any
2560 // redeclarations of nested classes, since both would cause us
2561 // to try to instantiate the members of a class twice.
Douglas Gregoref96ee02012-01-14 16:38:05 +00002562 if (Record->isInjectedClassName() || Record->getPreviousDecl())
Douglas Gregor2db32322009-10-07 23:56:10 +00002563 continue;
2564
Douglas Gregor0d035142009-10-27 18:42:08 +00002565 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2566 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002567
2568 if (MSInfo->getTemplateSpecializationKind()
2569 == TSK_ExplicitSpecialization)
2570 continue;
Nico Weberc956b6e2010-09-27 21:02:09 +00002571
Douglas Gregor0d035142009-10-27 18:42:08 +00002572 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2573 Record,
2574 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002575 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002576 SuppressNew) ||
2577 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002578 continue;
2579
Douglas Gregor0d035142009-10-27 18:42:08 +00002580 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2581 assert(Pattern && "Missing instantiated-from-template information");
2582
Douglas Gregor952b0172010-02-11 01:04:33 +00002583 if (!Record->getDefinition()) {
2584 if (!Pattern->getDefinition()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002585 // C++0x [temp.explicit]p8:
2586 // An explicit instantiation definition that names a class template
2587 // specialization explicitly instantiates the class template
2588 // specialization and is only an explicit instantiation definition
2589 // of members whose definition is visible at the point of
2590 // instantiation.
2591 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2592 MSInfo->setTemplateSpecializationKind(TSK);
2593 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2594 }
2595
2596 continue;
2597 }
2598
2599 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002600 TemplateArgs,
2601 TSK);
Nico Weberc956b6e2010-09-27 21:02:09 +00002602 } else {
2603 if (TSK == TSK_ExplicitInstantiationDefinition &&
2604 Record->getTemplateSpecializationKind() ==
2605 TSK_ExplicitInstantiationDeclaration) {
2606 Record->setTemplateSpecializationKind(TSK);
2607 MarkVTableUsed(PointOfInstantiation, Record, true);
2608 }
Douglas Gregor0d035142009-10-27 18:42:08 +00002609 }
Douglas Gregore9374d52009-10-08 01:19:17 +00002610
Douglas Gregor952b0172010-02-11 01:04:33 +00002611 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00002612 if (Pattern)
2613 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2614 TSK);
Richard Smithf1c66b42012-03-14 23:13:10 +00002615 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(*D)) {
2616 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2617 assert(MSInfo && "No member specialization information?");
2618
2619 if (MSInfo->getTemplateSpecializationKind()
2620 == TSK_ExplicitSpecialization)
2621 continue;
2622
2623 if (CheckSpecializationInstantiationRedecl(
2624 PointOfInstantiation, TSK, Enum,
2625 MSInfo->getTemplateSpecializationKind(),
2626 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2627 SuppressNew)
2628 continue;
2629
2630 if (Enum->getDefinition())
2631 continue;
2632
2633 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2634 assert(Pattern && "Missing instantiated-from-template information");
2635
2636 if (TSK == TSK_ExplicitInstantiationDefinition) {
2637 if (!Pattern->getDefinition())
2638 continue;
2639
2640 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2641 } else {
2642 MSInfo->setTemplateSpecializationKind(TSK);
2643 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2644 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002645 }
2646 }
2647}
2648
2649/// \brief Instantiate the definitions of all of the members of the
2650/// given class template specialization, which was named as part of an
2651/// explicit instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +00002652void
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002653Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregora58861f2009-05-13 20:28:22 +00002654 SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002655 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2656 TemplateSpecializationKind TSK) {
Douglas Gregora58861f2009-05-13 20:28:22 +00002657 // C++0x [temp.explicit]p7:
2658 // An explicit instantiation that names a class template
2659 // specialization is an explicit instantion of the same kind
2660 // (declaration or definition) of each of its members (not
2661 // including members inherited from base classes) that has not
2662 // been previously explicitly specialized in the translation unit
2663 // containing the explicit instantiation, except as described
2664 // below.
2665 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002666 getTemplateInstantiationArgs(ClassTemplateSpec),
2667 TSK);
Douglas Gregora58861f2009-05-13 20:28:22 +00002668}
2669
John McCall60d7b3a2010-08-24 06:29:42 +00002670StmtResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002671Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor43959a92009-08-20 07:17:43 +00002672 if (!S)
2673 return Owned(S);
2674
2675 TemplateInstantiator Instantiator(*this, TemplateArgs,
2676 SourceLocation(),
2677 DeclarationName());
2678 return Instantiator.TransformStmt(S);
2679}
2680
John McCall60d7b3a2010-08-24 06:29:42 +00002681ExprResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002682Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorb98b1992009-08-11 05:31:07 +00002683 if (!E)
2684 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002685
Douglas Gregorb98b1992009-08-11 05:31:07 +00002686 TemplateInstantiator Instantiator(*this, TemplateArgs,
2687 SourceLocation(),
2688 DeclarationName());
2689 return Instantiator.TransformExpr(E);
2690}
2691
Richard Smithc83c2302012-12-19 01:39:02 +00002692ExprResult Sema::SubstInitializer(Expr *Init,
2693 const MultiLevelTemplateArgumentList &TemplateArgs,
2694 bool CXXDirectInit) {
2695 TemplateInstantiator Instantiator(*this, TemplateArgs,
2696 SourceLocation(),
2697 DeclarationName());
2698 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2699}
2700
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002701bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2702 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002703 SmallVectorImpl<Expr *> &Outputs) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002704 if (NumExprs == 0)
2705 return false;
Richard Smithc83c2302012-12-19 01:39:02 +00002706
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002707 TemplateInstantiator Instantiator(*this, TemplateArgs,
2708 SourceLocation(),
2709 DeclarationName());
2710 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2711}
2712
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002713NestedNameSpecifierLoc
2714Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2715 const MultiLevelTemplateArgumentList &TemplateArgs) {
2716 if (!NNS)
2717 return NestedNameSpecifierLoc();
2718
2719 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2720 DeclarationName());
2721 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2722}
2723
Abramo Bagnara25777432010-08-11 22:01:17 +00002724/// \brief Do template substitution on declaration name info.
2725DeclarationNameInfo
2726Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2727 const MultiLevelTemplateArgumentList &TemplateArgs) {
2728 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2729 NameInfo.getName());
2730 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2731}
2732
Douglas Gregorde650ae2009-03-31 18:38:02 +00002733TemplateName
Douglas Gregor1d752d72011-03-02 18:46:51 +00002734Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2735 TemplateName Name, SourceLocation Loc,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002736 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord1067e52009-08-06 06:41:21 +00002737 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2738 DeclarationName());
Douglas Gregor1d752d72011-03-02 18:46:51 +00002739 CXXScopeSpec SS;
2740 SS.Adopt(QualifierLoc);
2741 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregorde650ae2009-03-31 18:38:02 +00002742}
Douglas Gregor91333002009-06-11 00:06:24 +00002743
Douglas Gregore02e2622010-12-22 21:19:48 +00002744bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2745 TemplateArgumentListInfo &Result,
John McCall833ca992009-10-29 08:12:44 +00002746 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor670444e2009-08-04 22:27:00 +00002747 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2748 DeclarationName());
Douglas Gregore02e2622010-12-22 21:19:48 +00002749
2750 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregor91333002009-06-11 00:06:24 +00002751}
Douglas Gregor895162d2010-04-30 18:55:50 +00002752
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002753
2754static const Decl* getCanonicalParmVarDecl(const Decl *D) {
2755 // When storing ParmVarDecls in the local instantiation scope, we always
2756 // want to use the ParmVarDecl from the canonical function declaration,
2757 // since the map is then valid for any redeclaration or definition of that
2758 // function.
2759 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2760 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2761 unsigned i = PV->getFunctionScopeIndex();
2762 return FD->getCanonicalDecl()->getParamDecl(i);
2763 }
2764 }
2765 return D;
2766}
2767
2768
Douglas Gregor12c9c002011-01-07 16:43:16 +00002769llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2770LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002771 D = getCanonicalParmVarDecl(D);
Chris Lattner57ad3782011-02-17 20:34:02 +00002772 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor895162d2010-04-30 18:55:50 +00002773 Current = Current->Outer) {
Chris Lattner57ad3782011-02-17 20:34:02 +00002774
Douglas Gregor895162d2010-04-30 18:55:50 +00002775 // Check if we found something within this scope.
Douglas Gregorebb1c562010-12-21 21:22:51 +00002776 const Decl *CheckD = D;
2777 do {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002778 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregorebb1c562010-12-21 21:22:51 +00002779 if (Found != Current->LocalDecls.end())
Douglas Gregor12c9c002011-01-07 16:43:16 +00002780 return &Found->second;
Douglas Gregorebb1c562010-12-21 21:22:51 +00002781
2782 // If this is a tag declaration, it's possible that we need to look for
2783 // a previous declaration.
2784 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregoref96ee02012-01-14 16:38:05 +00002785 CheckD = Tag->getPreviousDecl();
Douglas Gregorebb1c562010-12-21 21:22:51 +00002786 else
2787 CheckD = 0;
2788 } while (CheckD);
2789
Douglas Gregor895162d2010-04-30 18:55:50 +00002790 // If we aren't combined with our outer scope, we're done.
2791 if (!Current->CombineWithOuterScope)
2792 break;
2793 }
Chris Lattner57ad3782011-02-17 20:34:02 +00002794
Serge Pavlovdc49d522013-07-15 06:14:07 +00002795 // If we're performing a partial substitution during template argument
2796 // deduction, we may not have values for template parameters yet.
2797 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2798 isa<TemplateTemplateParmDecl>(D))
2799 return 0;
2800
Chris Lattner57ad3782011-02-17 20:34:02 +00002801 // If we didn't find the decl, then we either have a sema bug, or we have a
2802 // forward reference to a label declaration. Return null to indicate that
2803 // we have an uninstantiated label.
2804 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Douglas Gregor895162d2010-04-30 18:55:50 +00002805 return 0;
2806}
2807
John McCall2a7fb272010-08-25 05:32:35 +00002808void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002809 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002810 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregord3731192011-01-10 07:32:04 +00002811 if (Stored.isNull())
2812 Stored = Inst;
Benjamin Kramer3bbffd52013-04-12 15:22:25 +00002813 else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>())
2814 Pack->push_back(Inst);
2815 else
Douglas Gregord3731192011-01-10 07:32:04 +00002816 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Douglas Gregor895162d2010-04-30 18:55:50 +00002817}
Douglas Gregor12c9c002011-01-07 16:43:16 +00002818
2819void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2820 Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002821 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002822 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2823 Pack->push_back(Inst);
2824}
2825
2826void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002827 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002828 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2829 assert(Stored.isNull() && "Already instantiated this local");
2830 DeclArgumentPack *Pack = new DeclArgumentPack;
2831 Stored = Pack;
2832 ArgumentPacks.push_back(Pack);
2833}
2834
Douglas Gregord3731192011-01-10 07:32:04 +00002835void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2836 const TemplateArgument *ExplicitArgs,
2837 unsigned NumExplicitArgs) {
2838 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2839 "Already have a partially-substituted pack");
2840 assert((!PartiallySubstitutedPack
2841 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2842 "Wrong number of arguments in partially-substituted pack");
2843 PartiallySubstitutedPack = Pack;
2844 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2845 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2846}
2847
2848NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2849 const TemplateArgument **ExplicitArgs,
2850 unsigned *NumExplicitArgs) const {
2851 if (ExplicitArgs)
2852 *ExplicitArgs = 0;
2853 if (NumExplicitArgs)
2854 *NumExplicitArgs = 0;
2855
2856 for (const LocalInstantiationScope *Current = this; Current;
2857 Current = Current->Outer) {
2858 if (Current->PartiallySubstitutedPack) {
2859 if (ExplicitArgs)
2860 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2861 if (NumExplicitArgs)
2862 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2863
2864 return Current->PartiallySubstitutedPack;
2865 }
2866
2867 if (!Current->CombineWithOuterScope)
2868 break;
2869 }
2870
2871 return 0;
2872}