blob: 60f447711e2b6b39545305c627ecbe9776506e70 [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"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/Expr.h"
19#include "clang/Basic/LangOptions.h"
John McCall19510852010-08-20 18:27:03 +000020#include "clang/Sema/DeclSpec.h"
Richard Smith7a614d82011-06-11 17:19:42 +000021#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000022#include "clang/Sema/Lookup.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000024#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000025
26using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000027using namespace sema;
Douglas Gregor99ebf652009-02-27 19:31:52 +000028
Douglas Gregoree1828a2009-03-10 18:03:33 +000029//===----------------------------------------------------------------------===/
30// Template Instantiation Support
31//===----------------------------------------------------------------------===/
32
Douglas Gregord6350ae2009-08-28 20:31:08 +000033/// \brief Retrieve the template argument list(s) that should be used to
34/// instantiate the definition of the given declaration.
Douglas Gregor0f8716b2009-11-09 19:17:50 +000035///
36/// \param D the declaration for which we are computing template instantiation
37/// arguments.
38///
39/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor525f96c2010-02-05 07:33:43 +000040///
41/// \param RelativeToPrimary true if we should get the template
42/// arguments relative to the primary template, even when we're
43/// dealing with a specialization. This is only relevant for function
44/// template specializations.
Douglas Gregore7089b02010-05-03 23:29:10 +000045///
46/// \param Pattern If non-NULL, indicates the pattern from which we will be
47/// instantiating the definition of the given declaration, \p D. This is
48/// used to determine the proper set of template instantiation arguments for
49/// friend function template specializations.
Douglas Gregord1102432009-08-28 17:37:35 +000050MultiLevelTemplateArgumentList
Douglas Gregor0f8716b2009-11-09 19:17:50 +000051Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor525f96c2010-02-05 07:33:43 +000052 const TemplateArgumentList *Innermost,
Douglas Gregore7089b02010-05-03 23:29:10 +000053 bool RelativeToPrimary,
54 const FunctionDecl *Pattern) {
Douglas Gregord1102432009-08-28 17:37:35 +000055 // Accumulate the set of template argument lists in this structure.
56 MultiLevelTemplateArgumentList Result;
Mike Stump1eb44332009-09-09 15:08:12 +000057
Douglas Gregor0f8716b2009-11-09 19:17:50 +000058 if (Innermost)
59 Result.addOuterTemplateArguments(Innermost);
60
Douglas Gregord1102432009-08-28 17:37:35 +000061 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregor93104c12011-05-22 00:21:10 +000062 if (!Ctx) {
Douglas Gregord1102432009-08-28 17:37:35 +000063 Ctx = D->getDeclContext();
Douglas Gregor93104c12011-05-22 00:21:10 +000064
Douglas Gregor383041d2011-06-15 14:20:42 +000065 // If we have a template template parameter with translation unit context,
66 // then we're performing substitution into a default template argument of
67 // this template template parameter before we've constructed the template
68 // that will own this template template parameter. In this case, we
69 // use empty template parameter lists for all of the outer templates
70 // to avoid performing any substitutions.
71 if (Ctx->isTranslationUnit()) {
72 if (TemplateTemplateParmDecl *TTP
73 = dyn_cast<TemplateTemplateParmDecl>(D)) {
74 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
Richard Smith7a9f7c72013-05-17 03:04:50 +000075 Result.addOuterTemplateArguments(None);
Douglas Gregor383041d2011-06-15 14:20:42 +000076 return Result;
77 }
78 }
Douglas Gregor93104c12011-05-22 00:21:10 +000079 }
80
John McCallf181d8a2009-08-29 03:16:09 +000081 while (!Ctx->isFileContext()) {
Douglas Gregord1102432009-08-28 17:37:35 +000082 // Add template arguments from a class template instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +000083 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregord1102432009-08-28 17:37:35 +000084 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
85 // We're done when we hit an explicit specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +000086 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
87 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregord1102432009-08-28 17:37:35 +000088 break;
Mike Stump1eb44332009-09-09 15:08:12 +000089
Douglas Gregord1102432009-08-28 17:37:35 +000090 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +000091
92 // If this class template specialization was instantiated from a
93 // specialized member that is a class template, we're done.
94 assert(Spec->getSpecializedTemplate() && "No class template?");
95 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
96 break;
Mike Stump1eb44332009-09-09 15:08:12 +000097 }
Douglas Gregord1102432009-08-28 17:37:35 +000098 // Add template arguments from a function template specialization.
John McCallf181d8a2009-08-29 03:16:09 +000099 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor525f96c2010-02-05 07:33:43 +0000100 if (!RelativeToPrimary &&
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000101 (Function->getTemplateSpecializationKind() ==
102 TSK_ExplicitSpecialization &&
103 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000104 break;
105
Douglas Gregord1102432009-08-28 17:37:35 +0000106 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000107 = Function->getTemplateSpecializationArgs()) {
108 // Add the template arguments for this specialization.
Douglas Gregord1102432009-08-28 17:37:35 +0000109 Result.addOuterTemplateArguments(TemplateArgs);
John McCallf181d8a2009-08-29 03:16:09 +0000110
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000111 // If this function was instantiated from a specialized member that is
112 // a function template, we're done.
113 assert(Function->getPrimaryTemplate() && "No function template?");
114 if (Function->getPrimaryTemplate()->isMemberSpecialization())
115 break;
Douglas Gregorc494f772011-03-05 17:54:25 +0000116 } else if (FunctionTemplateDecl *FunTmpl
117 = Function->getDescribedFunctionTemplate()) {
118 // Add the "injected" template arguments.
Richard Smith7a9f7c72013-05-17 03:04:50 +0000119 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000120 }
121
John McCallf181d8a2009-08-29 03:16:09 +0000122 // If this is a friend declaration and it declares an entity at
123 // namespace scope, take arguments from its lexical parent
Douglas Gregore7089b02010-05-03 23:29:10 +0000124 // instead of its semantic parent, unless of course the pattern we're
125 // instantiating actually comes from the file's context!
John McCallf181d8a2009-08-29 03:16:09 +0000126 if (Function->getFriendObjectKind() &&
Douglas Gregore7089b02010-05-03 23:29:10 +0000127 Function->getDeclContext()->isFileContext() &&
128 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCallf181d8a2009-08-29 03:16:09 +0000129 Ctx = Function->getLexicalDeclContext();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000130 RelativeToPrimary = false;
John McCallf181d8a2009-08-29 03:16:09 +0000131 continue;
132 }
Douglas Gregor24bae922010-07-08 18:37:38 +0000133 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
134 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
135 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith7a9f7c72013-05-17 03:04:50 +0000136 const TemplateSpecializationType *TST =
137 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
138 Result.addOuterTemplateArguments(
139 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor24bae922010-07-08 18:37:38 +0000140 if (ClassTemplate->isMemberSpecialization())
141 break;
142 }
Douglas Gregord1102432009-08-28 17:37:35 +0000143 }
John McCallf181d8a2009-08-29 03:16:09 +0000144
145 Ctx = Ctx->getParent();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000146 RelativeToPrimary = false;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000147 }
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Douglas Gregord1102432009-08-28 17:37:35 +0000149 return Result;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000150}
151
Douglas Gregorf35f8282009-11-11 21:54:23 +0000152bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
153 switch (Kind) {
154 case TemplateInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000155 case ExceptionSpecInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000156 case DefaultTemplateArgumentInstantiation:
157 case DefaultFunctionArgumentInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000158 case ExplicitTemplateArgumentSubstitution:
159 case DeducedTemplateArgumentSubstitution:
160 case PriorTemplateArgumentSubstitution:
Richard Smithab91ef12012-07-08 02:38:24 +0000161 return true;
162
Douglas Gregorf35f8282009-11-11 21:54:23 +0000163 case DefaultTemplateArgumentChecking:
164 return false;
165 }
David Blaikie7530c032012-01-17 06:56:22 +0000166
167 llvm_unreachable("Invalid InstantiationKind!");
Douglas Gregorf35f8282009-11-11 21:54:23 +0000168}
169
Douglas Gregor26dce442009-03-10 00:06:19 +0000170Sema::InstantiatingTemplate::
171InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000172 Decl *Entity,
Douglas Gregor26dce442009-03-10 00:06:19 +0000173 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000174 : SemaRef(SemaRef),
175 SavedInNonInstantiationSFINAEContext(
176 SemaRef.InNonInstantiationSFINAEContext)
177{
Douglas Gregordf667e72009-03-10 20:44:00 +0000178 Invalid = CheckInstantiationDepth(PointOfInstantiation,
179 InstantiationRange);
180 if (!Invalid) {
Douglas Gregor26dce442009-03-10 00:06:19 +0000181 ActiveTemplateInstantiation Inst;
Douglas Gregordf667e72009-03-10 20:44:00 +0000182 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
Douglas Gregor26dce442009-03-10 00:06:19 +0000183 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000184 Inst.Entity = Entity;
Douglas Gregor313a81d2009-03-12 18:36:18 +0000185 Inst.TemplateArgs = 0;
186 Inst.NumTemplateArgs = 0;
Douglas Gregordf667e72009-03-10 20:44:00 +0000187 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000188 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregordf667e72009-03-10 20:44:00 +0000189 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregordf667e72009-03-10 20:44:00 +0000190 }
191}
192
Richard Smithe6975e92012-04-17 00:58:00 +0000193Sema::InstantiatingTemplate::
194InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
195 FunctionDecl *Entity, ExceptionSpecification,
196 SourceRange InstantiationRange)
197 : SemaRef(SemaRef),
198 SavedInNonInstantiationSFINAEContext(
199 SemaRef.InNonInstantiationSFINAEContext)
200{
201 Invalid = CheckInstantiationDepth(PointOfInstantiation,
202 InstantiationRange);
203 if (!Invalid) {
204 ActiveTemplateInstantiation Inst;
205 Inst.Kind = ActiveTemplateInstantiation::ExceptionSpecInstantiation;
206 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000207 Inst.Entity = Entity;
Richard Smithe6975e92012-04-17 00:58:00 +0000208 Inst.TemplateArgs = 0;
209 Inst.NumTemplateArgs = 0;
210 Inst.InstantiationRange = InstantiationRange;
211 SemaRef.InNonInstantiationSFINAEContext = false;
212 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
213 }
214}
215
Richard Smith7e54fb52012-07-16 01:09:10 +0000216Sema::InstantiatingTemplate::
217InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
218 TemplateDecl *Template,
219 ArrayRef<TemplateArgument> TemplateArgs,
220 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000221 : SemaRef(SemaRef),
222 SavedInNonInstantiationSFINAEContext(
223 SemaRef.InNonInstantiationSFINAEContext)
224{
Douglas Gregordf667e72009-03-10 20:44:00 +0000225 Invalid = CheckInstantiationDepth(PointOfInstantiation,
226 InstantiationRange);
227 if (!Invalid) {
228 ActiveTemplateInstantiation Inst;
Mike Stump1eb44332009-09-09 15:08:12 +0000229 Inst.Kind
Douglas Gregordf667e72009-03-10 20:44:00 +0000230 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
231 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000232 Inst.Entity = Template;
Richard Smith7e54fb52012-07-16 01:09:10 +0000233 Inst.TemplateArgs = TemplateArgs.data();
234 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregor26dce442009-03-10 00:06:19 +0000235 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000236 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor26dce442009-03-10 00:06:19 +0000237 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor26dce442009-03-10 00:06:19 +0000238 }
239}
240
Richard Smith7e54fb52012-07-16 01:09:10 +0000241Sema::InstantiatingTemplate::
242InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
243 FunctionTemplateDecl *FunctionTemplate,
244 ArrayRef<TemplateArgument> TemplateArgs,
245 ActiveTemplateInstantiation::InstantiationKind Kind,
246 sema::TemplateDeductionInfo &DeductionInfo,
247 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000248 : SemaRef(SemaRef),
249 SavedInNonInstantiationSFINAEContext(
250 SemaRef.InNonInstantiationSFINAEContext)
251{
Richard Smithab91ef12012-07-08 02:38:24 +0000252 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Douglas Gregorcca9e962009-07-01 22:01:06 +0000253 if (!Invalid) {
254 ActiveTemplateInstantiation Inst;
255 Inst.Kind = Kind;
256 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000257 Inst.Entity = FunctionTemplate;
Richard Smith7e54fb52012-07-16 01:09:10 +0000258 Inst.TemplateArgs = TemplateArgs.data();
259 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregor9b623632010-10-12 23:32:35 +0000260 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000261 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000262 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000263 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregorf35f8282009-11-11 21:54:23 +0000264
265 if (!Inst.isInstantiationRecord())
266 ++SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000267 }
268}
269
Richard Smith7e54fb52012-07-16 01:09:10 +0000270Sema::InstantiatingTemplate::
271InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
272 ClassTemplatePartialSpecializationDecl *PartialSpec,
273 ArrayRef<TemplateArgument> TemplateArgs,
274 sema::TemplateDeductionInfo &DeductionInfo,
275 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000276 : SemaRef(SemaRef),
277 SavedInNonInstantiationSFINAEContext(
278 SemaRef.InNonInstantiationSFINAEContext)
279{
Richard Smithab91ef12012-07-08 02:38:24 +0000280 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
281 if (!Invalid) {
282 ActiveTemplateInstantiation Inst;
283 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
284 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000285 Inst.Entity = PartialSpec;
Richard Smith7e54fb52012-07-16 01:09:10 +0000286 Inst.TemplateArgs = TemplateArgs.data();
287 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000288 Inst.DeductionInfo = &DeductionInfo;
289 Inst.InstantiationRange = InstantiationRange;
290 SemaRef.InNonInstantiationSFINAEContext = false;
291 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
292 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000293}
294
Richard Smith7e54fb52012-07-16 01:09:10 +0000295Sema::InstantiatingTemplate::
296InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
297 ParmVarDecl *Param,
298 ArrayRef<TemplateArgument> TemplateArgs,
299 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000300 : SemaRef(SemaRef),
301 SavedInNonInstantiationSFINAEContext(
302 SemaRef.InNonInstantiationSFINAEContext)
303{
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000304 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000305 if (!Invalid) {
306 ActiveTemplateInstantiation Inst;
307 Inst.Kind
308 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000309 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000310 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000311 Inst.TemplateArgs = TemplateArgs.data();
312 Inst.NumTemplateArgs = TemplateArgs.size();
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000313 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000314 SemaRef.InNonInstantiationSFINAEContext = false;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000315 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000316 }
317}
318
319Sema::InstantiatingTemplate::
320InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000321 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
322 ArrayRef<TemplateArgument> TemplateArgs,
323 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000324 : SemaRef(SemaRef),
325 SavedInNonInstantiationSFINAEContext(
326 SemaRef.InNonInstantiationSFINAEContext)
327{
Richard Smithab91ef12012-07-08 02:38:24 +0000328 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
329 if (!Invalid) {
330 ActiveTemplateInstantiation Inst;
331 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
332 Inst.PointOfInstantiation = PointOfInstantiation;
333 Inst.Template = Template;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000334 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000335 Inst.TemplateArgs = TemplateArgs.data();
336 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000337 Inst.InstantiationRange = InstantiationRange;
338 SemaRef.InNonInstantiationSFINAEContext = false;
339 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
340 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000341}
342
343Sema::InstantiatingTemplate::
344InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000345 NamedDecl *Template, TemplateTemplateParmDecl *Param,
346 ArrayRef<TemplateArgument> TemplateArgs,
347 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000348 : SemaRef(SemaRef),
349 SavedInNonInstantiationSFINAEContext(
350 SemaRef.InNonInstantiationSFINAEContext)
351{
Richard Smithab91ef12012-07-08 02:38:24 +0000352 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
353 if (!Invalid) {
354 ActiveTemplateInstantiation Inst;
355 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
356 Inst.PointOfInstantiation = PointOfInstantiation;
357 Inst.Template = Template;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000358 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000359 Inst.TemplateArgs = TemplateArgs.data();
360 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000361 Inst.InstantiationRange = InstantiationRange;
362 SemaRef.InNonInstantiationSFINAEContext = false;
363 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
364 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000365}
366
367Sema::InstantiatingTemplate::
368InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000369 TemplateDecl *Template, NamedDecl *Param,
370 ArrayRef<TemplateArgument> TemplateArgs,
371 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000372 : SemaRef(SemaRef),
373 SavedInNonInstantiationSFINAEContext(
374 SemaRef.InNonInstantiationSFINAEContext)
375{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000376 Invalid = false;
377
378 ActiveTemplateInstantiation Inst;
379 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
380 Inst.PointOfInstantiation = PointOfInstantiation;
381 Inst.Template = Template;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000382 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000383 Inst.TemplateArgs = TemplateArgs.data();
384 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregorf35f8282009-11-11 21:54:23 +0000385 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000386 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000387 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
388
389 assert(!Inst.isInstantiationRecord());
390 ++SemaRef.NonInstantiationEntries;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000391}
392
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000393void Sema::InstantiatingTemplate::Clear() {
394 if (!Invalid) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000395 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
396 assert(SemaRef.NonInstantiationEntries > 0);
397 --SemaRef.NonInstantiationEntries;
398 }
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000399 SemaRef.InNonInstantiationSFINAEContext
400 = SavedInNonInstantiationSFINAEContext;
Douglas Gregor26dce442009-03-10 00:06:19 +0000401 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000402 Invalid = true;
403 }
Douglas Gregor26dce442009-03-10 00:06:19 +0000404}
405
Douglas Gregordf667e72009-03-10 20:44:00 +0000406bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
407 SourceLocation PointOfInstantiation,
408 SourceRange InstantiationRange) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000409 assert(SemaRef.NonInstantiationEntries <=
410 SemaRef.ActiveTemplateInstantiations.size());
411 if ((SemaRef.ActiveTemplateInstantiations.size() -
412 SemaRef.NonInstantiationEntries)
David Blaikie4e4d0842012-03-11 07:00:24 +0000413 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregordf667e72009-03-10 20:44:00 +0000414 return false;
415
Mike Stump1eb44332009-09-09 15:08:12 +0000416 SemaRef.Diag(PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000417 diag::err_template_recursion_depth_exceeded)
David Blaikie4e4d0842012-03-11 07:00:24 +0000418 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregordf667e72009-03-10 20:44:00 +0000419 << InstantiationRange;
420 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikie4e4d0842012-03-11 07:00:24 +0000421 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregordf667e72009-03-10 20:44:00 +0000422 return true;
423}
424
Douglas Gregoree1828a2009-03-10 18:03:33 +0000425/// \brief Prints the current instantiation stack through a series of
426/// notes.
427void Sema::PrintInstantiationStack() {
Douglas Gregor575cf372010-04-20 07:18:24 +0000428 // Determine which template instantiations to skip, if any.
429 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
430 unsigned Limit = Diags.getTemplateBacktraceLimit();
431 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
432 SkipStart = Limit / 2 + Limit % 2;
433 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
434 }
435
Douglas Gregorcca9e962009-07-01 22:01:06 +0000436 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregor575cf372010-04-20 07:18:24 +0000437 unsigned InstantiationIdx = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000438 for (SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
Douglas Gregoree1828a2009-03-10 18:03:33 +0000439 Active = ActiveTemplateInstantiations.rbegin(),
440 ActiveEnd = ActiveTemplateInstantiations.rend();
441 Active != ActiveEnd;
Douglas Gregor575cf372010-04-20 07:18:24 +0000442 ++Active, ++InstantiationIdx) {
443 // Skip this instantiation?
444 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
445 if (InstantiationIdx == SkipStart) {
446 // Note that we're skipping instantiations.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000447 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor575cf372010-04-20 07:18:24 +0000448 diag::note_instantiation_contexts_suppressed)
449 << unsigned(ActiveTemplateInstantiations.size() - Limit);
450 }
451 continue;
452 }
453
Douglas Gregordf667e72009-03-10 20:44:00 +0000454 switch (Active->Kind) {
455 case ActiveTemplateInstantiation::TemplateInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000456 Decl *D = Active->Entity;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000457 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
458 unsigned DiagID = diag::note_template_member_class_here;
459 if (isa<ClassTemplateSpecializationDecl>(Record))
460 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000461 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000462 << Context.getTypeDeclType(Record)
463 << Active->InstantiationRange;
Douglas Gregor7caa6822009-07-24 20:34:43 +0000464 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1637be72009-06-26 00:10:03 +0000465 unsigned DiagID;
466 if (Function->getPrimaryTemplate())
467 DiagID = diag::note_function_template_spec_here;
468 else
469 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000470 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000471 << Function
472 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000473 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000474 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor7caa6822009-07-24 20:34:43 +0000475 diag::note_template_static_data_member_def_here)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000476 << VD
477 << Active->InstantiationRange;
Richard Smithf1c66b42012-03-14 23:13:10 +0000478 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
479 Diags.Report(Active->PointOfInstantiation,
480 diag::note_template_enum_def_here)
481 << ED
482 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000483 } else {
484 Diags.Report(Active->PointOfInstantiation,
485 diag::note_template_type_alias_instantiation_here)
486 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregor7caa6822009-07-24 20:34:43 +0000487 << Active->InstantiationRange;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000488 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000489 break;
490 }
491
492 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000493 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
Benjamin Kramer5eada842013-02-22 15:46:01 +0000494 SmallVector<char, 128> TemplateArgsStr;
495 llvm::raw_svector_ostream OS(TemplateArgsStr);
496 Template->printName(OS);
497 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000498 Active->TemplateArgs,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000499 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000500 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000501 Diags.Report(Active->PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000502 diag::note_default_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000503 << OS.str()
Douglas Gregordf667e72009-03-10 20:44:00 +0000504 << Active->InstantiationRange;
505 break;
506 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000507
Douglas Gregorcca9e962009-07-01 22:01:06 +0000508 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000509 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000510 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000511 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000512 << FnTmpl
513 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
514 Active->TemplateArgs,
515 Active->NumTemplateArgs)
516 << Active->InstantiationRange;
Douglas Gregor637a4092009-06-10 23:47:09 +0000517 break;
518 }
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Douglas Gregorcca9e962009-07-01 22:01:06 +0000520 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000521 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
522 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000523 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000524 diag::note_partial_spec_deduct_instantiation_here)
525 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor5e402912010-03-30 20:35:20 +0000526 << getTemplateArgumentBindingsText(
527 PartialSpec->getTemplateParameters(),
528 Active->TemplateArgs,
529 Active->NumTemplateArgs)
Douglas Gregorcca9e962009-07-01 22:01:06 +0000530 << Active->InstantiationRange;
531 } else {
532 FunctionTemplateDecl *FnTmpl
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000533 = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000534 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000535 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000536 << FnTmpl
537 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
538 Active->TemplateArgs,
539 Active->NumTemplateArgs)
540 << Active->InstantiationRange;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000541 }
542 break;
Douglas Gregor637a4092009-06-10 23:47:09 +0000543
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000544 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000545 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000546 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Benjamin Kramer5eada842013-02-22 15:46:01 +0000548 SmallVector<char, 128> TemplateArgsStr;
549 llvm::raw_svector_ostream OS(TemplateArgsStr);
550 FD->printName(OS);
551 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000552 Active->TemplateArgs,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000553 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000554 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000555 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000556 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000557 << OS.str()
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000558 << Active->InstantiationRange;
559 break;
560 }
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000562 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000563 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000564 std::string Name;
565 if (!Parm->getName().empty())
566 Name = std::string(" '") + Parm->getName().str() + "'";
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000567
568 TemplateParameterList *TemplateParams = 0;
569 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
570 TemplateParams = Template->getTemplateParameters();
571 else
572 TemplateParams =
573 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
574 ->getTemplateParameters();
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000575 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000576 diag::note_prior_template_arg_substitution)
577 << isa<TemplateTemplateParmDecl>(Parm)
578 << Name
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000579 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000580 Active->TemplateArgs,
581 Active->NumTemplateArgs)
582 << Active->InstantiationRange;
583 break;
584 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000585
586 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000587 TemplateParameterList *TemplateParams = 0;
588 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
589 TemplateParams = Template->getTemplateParameters();
590 else
591 TemplateParams =
592 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
593 ->getTemplateParameters();
594
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000595 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000596 diag::note_template_default_arg_checking)
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000597 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000598 Active->TemplateArgs,
599 Active->NumTemplateArgs)
600 << Active->InstantiationRange;
601 break;
602 }
Richard Smithe6975e92012-04-17 00:58:00 +0000603
604 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
605 Diags.Report(Active->PointOfInstantiation,
606 diag::note_template_exception_spec_instantiation_here)
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000607 << cast<FunctionDecl>(Active->Entity)
Richard Smithe6975e92012-04-17 00:58:00 +0000608 << Active->InstantiationRange;
609 break;
Douglas Gregordf667e72009-03-10 20:44:00 +0000610 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000611 }
612}
613
David Blaikiedc84cd52013-02-20 22:23:23 +0000614Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000615 if (InNonInstantiationSFINAEContext)
David Blaikiedc84cd52013-02-20 22:23:23 +0000616 return Optional<TemplateDeductionInfo *>(0);
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000617
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000618 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
619 Active = ActiveTemplateInstantiations.rbegin(),
620 ActiveEnd = ActiveTemplateInstantiations.rend();
621 Active != ActiveEnd;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000622 ++Active)
623 {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000624 switch(Active->Kind) {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000625 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smitha43ea642012-04-26 07:24:08 +0000626 // An instantiation of an alias template may or may not be a SFINAE
627 // context, depending on what else is on the stack.
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000628 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smitha43ea642012-04-26 07:24:08 +0000629 break;
630 // Fall through.
631 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000632 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorcca9e962009-07-01 22:01:06 +0000633 // This is a template instantiation, so there is no SFINAE.
David Blaikie66874fb2013-02-21 01:47:18 +0000634 return None;
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000636 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000637 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000638 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000639 // A default template argument instantiation and substitution into
640 // template parameters with arguments for prior parameters may or may
641 // not be a SFINAE context; look further up the stack.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000642 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000643
Douglas Gregorcca9e962009-07-01 22:01:06 +0000644 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
645 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
646 // We're either substitution explicitly-specified template arguments
647 // or deduced template arguments, so SFINAE applies.
Douglas Gregor9b623632010-10-12 23:32:35 +0000648 assert(Active->DeductionInfo && "Missing deduction info pointer");
649 return Active->DeductionInfo;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000650 }
651 }
652
David Blaikie66874fb2013-02-21 01:47:18 +0000653 return None;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000654}
655
Douglas Gregord3731192011-01-10 07:32:04 +0000656/// \brief Retrieve the depth and index of a parameter pack.
657static std::pair<unsigned, unsigned>
658getDepthAndIndex(NamedDecl *ND) {
659 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
660 return std::make_pair(TTP->getDepth(), TTP->getIndex());
661
662 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
663 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
664
665 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
666 return std::make_pair(TTP->getDepth(), TTP->getIndex());
667}
668
Douglas Gregor99ebf652009-02-27 19:31:52 +0000669//===----------------------------------------------------------------------===/
670// Template Instantiation for Types
671//===----------------------------------------------------------------------===/
Douglas Gregorcd281c32009-02-28 00:25:32 +0000672namespace {
Douglas Gregor895162d2010-04-30 18:55:50 +0000673 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000674 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000675 SourceLocation Loc;
676 DeclarationName Entity;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000677
Douglas Gregorcd281c32009-02-28 00:25:32 +0000678 public:
Douglas Gregor43959a92009-08-20 07:17:43 +0000679 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump1eb44332009-09-09 15:08:12 +0000680
681 TemplateInstantiator(Sema &SemaRef,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000682 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor577f75a2009-08-04 16:50:30 +0000683 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000684 DeclarationName Entity)
685 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregor43959a92009-08-20 07:17:43 +0000686 Entity(Entity) { }
Douglas Gregorcd281c32009-02-28 00:25:32 +0000687
Mike Stump1eb44332009-09-09 15:08:12 +0000688 /// \brief Determine whether the given type \p T has already been
Douglas Gregor577f75a2009-08-04 16:50:30 +0000689 /// transformed.
690 ///
691 /// For the purposes of template instantiation, a type has already been
692 /// transformed if it is NULL or if it is not dependent.
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000693 bool AlreadyTransformed(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Douglas Gregor577f75a2009-08-04 16:50:30 +0000695 /// \brief Returns the location of the entity being instantiated, if known.
696 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +0000697
Douglas Gregor577f75a2009-08-04 16:50:30 +0000698 /// \brief Returns the name of the entity being instantiated, if any.
699 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Douglas Gregor972e6ce2009-10-27 06:26:26 +0000701 /// \brief Sets the "base" location and entity when that
702 /// information is known based on another transformation.
703 void setBase(SourceLocation Loc, DeclarationName Entity) {
704 this->Loc = Loc;
705 this->Entity = Entity;
706 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000707
708 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
709 SourceRange PatternRange,
David Blaikiea71f9d02011-09-22 02:34:54 +0000710 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000711 bool &ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000712 bool &RetainExpansion,
David Blaikiedc84cd52013-02-20 22:23:23 +0000713 Optional<unsigned> &NumExpansions) {
Douglas Gregorb99268b2010-12-21 00:52:54 +0000714 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
715 PatternRange, Unexpanded,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000716 TemplateArgs,
717 ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000718 RetainExpansion,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000719 NumExpansions);
720 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000721
Douglas Gregor12c9c002011-01-07 16:43:16 +0000722 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
723 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
724 }
725
Douglas Gregord3731192011-01-10 07:32:04 +0000726 TemplateArgument ForgetPartiallySubstitutedPack() {
727 TemplateArgument Result;
728 if (NamedDecl *PartialPack
729 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
730 MultiLevelTemplateArgumentList &TemplateArgs
731 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
732 unsigned Depth, Index;
733 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
734 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
735 Result = TemplateArgs(Depth, Index);
736 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
737 }
738 }
739
740 return Result;
741 }
742
743 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
744 if (Arg.isNull())
745 return;
746
747 if (NamedDecl *PartialPack
748 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
749 MultiLevelTemplateArgumentList &TemplateArgs
750 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
751 unsigned Depth, Index;
752 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
753 TemplateArgs.setArgument(Depth, Index, Arg);
754 }
755 }
756
Douglas Gregor577f75a2009-08-04 16:50:30 +0000757 /// \brief Transform the given declaration by instantiating a reference to
758 /// this declaration.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000759 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregorb98b1992009-08-11 05:31:07 +0000760
Douglas Gregordfca6f52012-02-13 22:00:16 +0000761 void transformAttrs(Decl *Old, Decl *New) {
762 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
763 }
764
765 void transformedLocalDecl(Decl *Old, Decl *New) {
766 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
767 }
768
Mike Stump1eb44332009-09-09 15:08:12 +0000769 /// \brief Transform the definition of the given declaration by
Douglas Gregor43959a92009-08-20 07:17:43 +0000770 /// instantiating it.
Douglas Gregoraac571c2010-03-01 17:25:41 +0000771 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Dmitri Gribenkoe23fb902012-09-12 17:01:48 +0000773 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregor6cd21982009-10-20 05:58:46 +0000774 /// declaration.
775 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
776
Douglas Gregor43959a92009-08-20 07:17:43 +0000777 /// \brief Rebuild the exception declaration and register the declaration
778 /// as an instantiated local.
Douglas Gregor83cb9422010-09-09 17:09:21 +0000779 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000780 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000781 SourceLocation StartLoc,
782 SourceLocation NameLoc,
783 IdentifierInfo *Name);
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Douglas Gregorbe270a02010-04-26 17:57:08 +0000785 /// \brief Rebuild the Objective-C exception declaration and register the
786 /// declaration as an instantiated local.
787 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
788 TypeSourceInfo *TSInfo, QualType T);
789
John McCallc4e70192009-09-11 04:59:25 +0000790 /// \brief Check for tag mismatches when instantiating an
791 /// elaborated type.
John McCall21e413f2010-11-04 19:04:38 +0000792 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
793 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000794 NestedNameSpecifierLoc QualifierLoc,
795 QualType T);
John McCallc4e70192009-09-11 04:59:25 +0000796
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000797 TemplateName TransformTemplateName(CXXScopeSpec &SS,
798 TemplateName Name,
799 SourceLocation NameLoc,
800 QualType ObjectType = QualType(),
801 NamedDecl *FirstQualifierInScope = 0);
802
John McCall60d7b3a2010-08-24 06:29:42 +0000803 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
804 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
805 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000806
John McCall60d7b3a2010-08-24 06:29:42 +0000807 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor56bc9832010-12-24 00:15:10 +0000808 NonTypeTemplateParmDecl *D);
Douglas Gregorc7793c72011-01-15 01:15:58 +0000809 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
810 SubstNonTypeTemplateParmPackExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000811
812 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
813 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
814
815 /// \brief Transform a reference to a function parameter pack.
816 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
817 ParmVarDecl *PD);
818
819 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
820 /// expand a function parameter pack reference which refers to an expanded
821 /// pack.
822 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
823
Douglas Gregor895162d2010-04-30 18:55:50 +0000824 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000825 FunctionProtoTypeLoc TL);
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000826 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
827 FunctionProtoTypeLoc TL,
828 CXXRecordDecl *ThisContext,
829 unsigned ThisTypeQuals);
830
Douglas Gregor6a24bfd2011-01-14 22:40:04 +0000831 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +0000832 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +0000833 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +0000834 bool ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +0000835
Mike Stump1eb44332009-09-09 15:08:12 +0000836 /// \brief Transforms a template type parameter type by performing
Douglas Gregor577f75a2009-08-04 16:50:30 +0000837 /// substitution of the corresponding template type argument.
John McCalla2becad2009-10-21 00:40:46 +0000838 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000839 TemplateTypeParmTypeLoc TL);
Nick Lewycky03d98c52010-07-06 19:51:49 +0000840
Douglas Gregorc3069d62011-01-14 02:55:32 +0000841 /// \brief Transforms an already-substituted template type parameter pack
842 /// into either itself (if we aren't substituting into its pack expansion)
843 /// or the appropriate substituted argument.
844 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
845 SubstTemplateTypeParmPackTypeLoc TL);
846
John McCall60d7b3a2010-08-24 06:29:42 +0000847 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewycky03d98c52010-07-06 19:51:49 +0000848 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCall60d7b3a2010-08-24 06:29:42 +0000849 ExprResult Result =
Nick Lewycky03d98c52010-07-06 19:51:49 +0000850 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
851 getSema().CallsUndergoingInstantiation.pop_back();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000852 return Result;
Nick Lewycky03d98c52010-07-06 19:51:49 +0000853 }
John McCall91a57552011-07-15 05:09:51 +0000854
Richard Smith612409e2012-07-25 03:56:55 +0000855 ExprResult TransformLambdaExpr(LambdaExpr *E) {
856 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
857 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
858 }
859
860 ExprResult TransformLambdaScope(LambdaExpr *E,
861 CXXMethodDecl *CallOperator) {
862 CallOperator->setInstantiationOfMemberFunction(E->getCallOperator(),
863 TSK_ImplicitInstantiation);
864 return TreeTransform<TemplateInstantiator>::
865 TransformLambdaScope(E, CallOperator);
866 }
867
John McCall91a57552011-07-15 05:09:51 +0000868 private:
869 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
870 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +0000871 TemplateArgument arg);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000872 };
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000873}
874
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000875bool TemplateInstantiator::AlreadyTransformed(QualType T) {
876 if (T.isNull())
877 return true;
878
Douglas Gregor561f8122011-07-01 01:22:09 +0000879 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000880 return false;
881
882 getSema().MarkDeclarationsReferencedInType(Loc, T);
883 return true;
884}
885
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000886Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregorc68afe22009-09-03 21:38:09 +0000887 if (!D)
888 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Douglas Gregorc68afe22009-09-03 21:38:09 +0000890 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000891 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor6d3e6272010-02-05 19:54:12 +0000892 // If the corresponding template argument is NULL or non-existent, it's
893 // because we are performing instantiation from explicitly-specified
894 // template arguments in a function template, but there were some
895 // arguments left unspecified.
896 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
897 TTP->getPosition()))
898 return D;
899
Douglas Gregor61c4d282011-01-05 15:48:55 +0000900 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
901
902 if (TTP->isParameterPack()) {
903 assert(Arg.getKind() == TemplateArgument::Pack &&
904 "Missing argument pack");
905
Douglas Gregor1aee05d2011-01-15 06:45:20 +0000906 assert(getSema().ArgumentPackSubstitutionIndex >= 0);
Douglas Gregord3731192011-01-10 07:32:04 +0000907 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000908 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
909 }
910
911 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor788cd062009-11-11 01:00:40 +0000912 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregord6350ae2009-08-28 20:31:08 +0000913 "Wrong kind of template template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000914 return Template.getAsTemplateDecl();
Douglas Gregord6350ae2009-08-28 20:31:08 +0000915 }
Mike Stump1eb44332009-09-09 15:08:12 +0000916
Douglas Gregor788cd062009-11-11 01:00:40 +0000917 // Fall through to find the instantiated declaration for this template
918 // template parameter.
Douglas Gregord1067e52009-08-06 06:41:21 +0000919 }
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000921 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000922}
923
Douglas Gregoraac571c2010-03-01 17:25:41 +0000924Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000925 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregor43959a92009-08-20 07:17:43 +0000926 if (!Inst)
927 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Douglas Gregor43959a92009-08-20 07:17:43 +0000929 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
930 return Inst;
931}
932
Douglas Gregor6cd21982009-10-20 05:58:46 +0000933NamedDecl *
934TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
935 SourceLocation Loc) {
936 // If the first part of the nested-name-specifier was a template type
937 // parameter, instantiate that type parameter down to a tag type.
938 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
939 const TemplateTypeParmType *TTP
940 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor984a58b2010-12-20 22:48:17 +0000941
Douglas Gregor6cd21982009-10-20 05:58:46 +0000942 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor984a58b2010-12-20 22:48:17 +0000943 // FIXME: This needs testing w/ member access expressions.
944 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
945
946 if (TTP->isParameterPack()) {
947 assert(Arg.getKind() == TemplateArgument::Pack &&
948 "Missing argument pack");
949
Douglas Gregor2be29f42011-01-14 23:41:42 +0000950 if (getSema().ArgumentPackSubstitutionIndex == -1)
Douglas Gregor984a58b2010-12-20 22:48:17 +0000951 return 0;
Douglas Gregor984a58b2010-12-20 22:48:17 +0000952
Douglas Gregord3731192011-01-10 07:32:04 +0000953 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor984a58b2010-12-20 22:48:17 +0000954 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
955 }
956
957 QualType T = Arg.getAsType();
Douglas Gregor6cd21982009-10-20 05:58:46 +0000958 if (T.isNull())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000959 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000960
961 if (const TagType *Tag = T->getAs<TagType>())
962 return Tag->getDecl();
963
964 // The resulting type is not a tag; complain.
965 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
966 return 0;
967 }
968 }
969
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000970 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000971}
972
Douglas Gregor43959a92009-08-20 07:17:43 +0000973VarDecl *
974TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000975 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000976 SourceLocation StartLoc,
977 SourceLocation NameLoc,
978 IdentifierInfo *Name) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000979 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000980 StartLoc, NameLoc, Name);
Douglas Gregorbe270a02010-04-26 17:57:08 +0000981 if (Var)
982 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
983 return Var;
984}
985
986VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
987 TypeSourceInfo *TSInfo,
988 QualType T) {
989 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
990 if (Var)
Douglas Gregor43959a92009-08-20 07:17:43 +0000991 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
992 return Var;
993}
994
John McCallc4e70192009-09-11 04:59:25 +0000995QualType
John McCall21e413f2010-11-04 19:04:38 +0000996TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
997 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000998 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000999 QualType T) {
John McCallc4e70192009-09-11 04:59:25 +00001000 if (const TagType *TT = T->getAs<TagType>()) {
1001 TagDecl* TD = TT->getDecl();
1002
John McCall21e413f2010-11-04 19:04:38 +00001003 SourceLocation TagLocation = KeywordLoc;
John McCallc4e70192009-09-11 04:59:25 +00001004
John McCallc4e70192009-09-11 04:59:25 +00001005 IdentifierInfo *Id = TD->getIdentifier();
1006
1007 // TODO: should we even warn on struct/class mismatches for this? Seems
1008 // like it's likely to produce a lot of spurious errors.
Richard Smithcbf97c52012-08-17 00:12:27 +00001009 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001010 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieubbf34c02011-06-10 03:11:26 +00001011 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1012 TagLocation, *Id)) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001013 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1014 << Id
1015 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1016 TD->getKindName());
1017 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1018 }
John McCallc4e70192009-09-11 04:59:25 +00001019 }
1020 }
1021
John McCall21e413f2010-11-04 19:04:38 +00001022 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1023 Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +00001024 QualifierLoc,
1025 T);
John McCallc4e70192009-09-11 04:59:25 +00001026}
1027
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001028TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1029 TemplateName Name,
1030 SourceLocation NameLoc,
1031 QualType ObjectType,
1032 NamedDecl *FirstQualifierInScope) {
1033 if (TemplateTemplateParmDecl *TTP
1034 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1035 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1036 // If the corresponding template argument is NULL or non-existent, it's
1037 // because we are performing instantiation from explicitly-specified
1038 // template arguments in a function template, but there were some
1039 // arguments left unspecified.
1040 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1041 TTP->getPosition()))
1042 return Name;
1043
1044 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1045
1046 if (TTP->isParameterPack()) {
1047 assert(Arg.getKind() == TemplateArgument::Pack &&
1048 "Missing argument pack");
1049
1050 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1051 // We have the template argument pack to substitute, but we're not
1052 // actually expanding the enclosing pack expansion yet. So, just
1053 // keep the entire argument pack.
1054 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1055 }
1056
1057 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1058 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1059 }
1060
1061 TemplateName Template = Arg.getAsTemplate();
Richard Smith3e4c6c42011-05-05 21:57:07 +00001062 assert(!Template.isNull() && "Null template template argument");
John McCall14606042011-06-30 08:33:18 +00001063
Douglas Gregor58750382011-03-05 20:06:51 +00001064 // We don't ever want to substitute for a qualified template name, since
1065 // the qualifier is handled separately. So, look through the qualified
1066 // template name to its underlying declaration.
1067 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1068 Template = TemplateName(QTN->getTemplateDecl());
John McCall14606042011-06-30 08:33:18 +00001069
1070 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001071 return Template;
1072 }
1073 }
1074
1075 if (SubstTemplateTemplateParmPackStorage *SubstPack
1076 = Name.getAsSubstTemplateTemplateParmPack()) {
1077 if (getSema().ArgumentPackSubstitutionIndex == -1)
1078 return Name;
1079
1080 const TemplateArgument &ArgPack = SubstPack->getArgumentPack();
1081 assert(getSema().ArgumentPackSubstitutionIndex < (int)ArgPack.pack_size() &&
1082 "Pack substitution index out-of-range");
1083 return ArgPack.pack_begin()[getSema().ArgumentPackSubstitutionIndex]
1084 .getAsTemplate();
1085 }
1086
1087 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1088 FirstQualifierInScope);
1089}
1090
John McCall60d7b3a2010-08-24 06:29:42 +00001091ExprResult
John McCall454feb92009-12-08 09:21:05 +00001092TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson773f3972009-09-11 01:22:35 +00001093 if (!E->isTypeDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00001094 return SemaRef.Owned(E);
Anders Carlsson773f3972009-09-11 01:22:35 +00001095
1096 FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
1097 assert(currentDecl && "Must have current function declaration when "
1098 "instantiating.");
1099
1100 PredefinedExpr::IdentType IT = E->getIdentType();
1101
Anders Carlsson848fa642010-02-11 18:20:28 +00001102 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Anders Carlsson773f3972009-09-11 01:22:35 +00001103
1104 llvm::APInt LengthI(32, Length + 1);
Nico Weberb4e80082012-06-25 22:34:48 +00001105 QualType ResTy;
1106 if (IT == PredefinedExpr::LFunction)
Hans Wennborg15f92ba2013-05-10 10:08:40 +00001107 ResTy = getSema().Context.WideCharTy.withConst();
Nico Weberb4e80082012-06-25 22:34:48 +00001108 else
1109 ResTy = getSema().Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001110 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
1111 ArrayType::Normal, 0);
1112 PredefinedExpr *PE =
1113 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
1114 return getSema().Owned(PE);
1115}
1116
John McCall60d7b3a2010-08-24 06:29:42 +00001117ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001118TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregordcee9802010-02-08 23:41:45 +00001119 NonTypeTemplateParmDecl *NTTP) {
John McCallb8fc0532010-02-06 08:42:39 +00001120 // If the corresponding template argument is NULL or non-existent, it's
1121 // because we are performing instantiation from explicitly-specified
1122 // template arguments in a function template, but there were some
1123 // arguments left unspecified.
1124 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1125 NTTP->getPosition()))
John McCall3fa5cae2010-10-26 07:05:15 +00001126 return SemaRef.Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Douglas Gregor56bc9832010-12-24 00:15:10 +00001128 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1129 if (NTTP->isParameterPack()) {
1130 assert(Arg.getKind() == TemplateArgument::Pack &&
1131 "Missing argument pack");
1132
1133 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc7793c72011-01-15 01:15:58 +00001134 // We have an argument pack, but we can't select a particular argument
1135 // out of it yet. Therefore, we'll build an expression to hold on to that
1136 // argument pack.
1137 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1138 E->getLocation(),
1139 NTTP->getDeclName());
1140 if (TargetType.isNull())
1141 return ExprError();
1142
1143 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1144 NTTP,
1145 E->getLocation(),
1146 Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001147 }
1148
Douglas Gregord3731192011-01-10 07:32:04 +00001149 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor56bc9832010-12-24 00:15:10 +00001150 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1151 }
Mike Stump1eb44332009-09-09 15:08:12 +00001152
John McCall91a57552011-07-15 05:09:51 +00001153 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1154}
1155
1156ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1157 NonTypeTemplateParmDecl *parm,
1158 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +00001159 TemplateArgument arg) {
John McCall91a57552011-07-15 05:09:51 +00001160 ExprResult result;
1161 QualType type;
1162
Richard Smith60983812012-07-09 03:07:20 +00001163 // If the argument is a pack expansion, the parameter must actually be a
1164 // parameter pack, and we should substitute the pattern itself, producing
1165 // an expression which contains an unexpanded parameter pack.
1166 if (arg.isPackExpansion()) {
1167 assert(parm->isParameterPack() && "pack expansion for non-pack");
1168 arg = arg.getPackExpansionPattern();
1169 }
1170
John McCallb8fc0532010-02-06 08:42:39 +00001171 // The template argument itself might be an expression, in which
1172 // case we just return that expression.
John McCall91a57552011-07-15 05:09:51 +00001173 if (arg.getKind() == TemplateArgument::Expression) {
1174 Expr *argExpr = arg.getAsExpr();
1175 result = SemaRef.Owned(argExpr);
1176 type = argExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Eli Friedmand7a6b162012-09-26 02:36:12 +00001178 } else if (arg.getKind() == TemplateArgument::Declaration ||
1179 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregord2008e22012-04-06 22:40:38 +00001180 ValueDecl *VD;
Eli Friedmand7a6b162012-09-26 02:36:12 +00001181 if (arg.getKind() == TemplateArgument::Declaration) {
1182 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Douglas Gregord2008e22012-04-06 22:40:38 +00001184 // Find the instantiation of the template argument. This is
1185 // required for nested templates.
1186 VD = cast_or_null<ValueDecl>(
1187 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1188 if (!VD)
1189 return ExprError();
1190 } else {
1191 // Propagate NULL template argument.
1192 VD = 0;
1193 }
1194
John McCall645cf442010-02-06 10:23:53 +00001195 // Derive the type we want the substituted decl to have. This had
1196 // better be non-dependent, or these checks will have serious problems.
John McCall91a57552011-07-15 05:09:51 +00001197 if (parm->isExpandedParameterPack()) {
1198 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1199 } else if (parm->isParameterPack() &&
1200 isa<PackExpansionType>(parm->getType())) {
1201 type = SemaRef.SubstType(
1202 cast<PackExpansionType>(parm->getType())->getPattern(),
1203 TemplateArgs, loc, parm->getDeclName());
1204 } else {
1205 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1206 loc, parm->getDeclName());
1207 }
1208 assert(!type.isNull() && "type substitution failed for param type");
1209 assert(!type->isDependentType() && "param type still dependent");
1210 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCallb8fc0532010-02-06 08:42:39 +00001211
John McCall91a57552011-07-15 05:09:51 +00001212 if (!result.isInvalid()) type = result.get()->getType();
1213 } else {
1214 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1215
1216 // Note that this type can be different from the type of 'result',
1217 // e.g. if it's an enum type.
1218 type = arg.getIntegralType();
1219 }
1220 if (result.isInvalid()) return ExprError();
1221
1222 Expr *resultExpr = result.take();
1223 return SemaRef.Owned(new (SemaRef.Context)
1224 SubstNonTypeTemplateParmExpr(type,
1225 resultExpr->getValueKind(),
1226 loc, parm, resultExpr));
John McCallb8fc0532010-02-06 08:42:39 +00001227}
1228
Douglas Gregorc7793c72011-01-15 01:15:58 +00001229ExprResult
1230TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1231 SubstNonTypeTemplateParmPackExpr *E) {
1232 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1233 // We aren't expanding the parameter pack, so just return ourselves.
1234 return getSema().Owned(E);
1235 }
1236
Douglas Gregorc7793c72011-01-15 01:15:58 +00001237 const TemplateArgument &ArgPack = E->getArgumentPack();
1238 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1239 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1240
1241 const TemplateArgument &Arg = ArgPack.pack_begin()[Index];
John McCall91a57552011-07-15 05:09:51 +00001242 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1243 E->getParameterPackLocation(),
1244 Arg);
Douglas Gregorc7793c72011-01-15 01:15:58 +00001245}
John McCallb8fc0532010-02-06 08:42:39 +00001246
John McCall60d7b3a2010-08-24 06:29:42 +00001247ExprResult
Richard Smith9a4db032012-09-12 00:56:43 +00001248TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1249 SourceLocation Loc) {
1250 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1251 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1252}
1253
1254ExprResult
1255TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1256 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1257 // We can expand this parameter pack now.
1258 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1259 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1260 if (!VD)
1261 return ExprError();
1262 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1263 }
1264
1265 QualType T = TransformType(E->getType());
1266 if (T.isNull())
1267 return ExprError();
1268
1269 // Transform each of the parameter expansions into the corresponding
1270 // parameters in the instantiation of the function decl.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001271 SmallVector<Decl *, 8> Parms;
Richard Smith9a4db032012-09-12 00:56:43 +00001272 Parms.reserve(E->getNumExpansions());
1273 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1274 I != End; ++I) {
1275 ParmVarDecl *D =
1276 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1277 if (!D)
1278 return ExprError();
1279 Parms.push_back(D);
1280 }
1281
1282 return FunctionParmPackExpr::Create(getSema().Context, T,
1283 E->getParameterPack(),
1284 E->getParameterPackLocation(), Parms);
1285}
1286
1287ExprResult
1288TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1289 ParmVarDecl *PD) {
1290 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1291 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1292 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1293 assert(Found && "no instantiation for parameter pack");
1294
1295 Decl *TransformedDecl;
1296 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1297 // If this is a reference to a function parameter pack which we can substitute
1298 // but can't yet expand, build a FunctionParmPackExpr for it.
1299 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1300 QualType T = TransformType(E->getType());
1301 if (T.isNull())
1302 return ExprError();
1303 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1304 E->getExprLoc(), *Pack);
1305 }
1306
1307 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1308 } else {
1309 TransformedDecl = Found->get<Decl*>();
1310 }
1311
1312 // We have either an unexpanded pack or a specific expansion.
1313 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1314 E->getExprLoc());
1315}
1316
1317ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001318TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1319 NamedDecl *D = E->getDecl();
Richard Smith9a4db032012-09-12 00:56:43 +00001320
1321 // Handle references to non-type template parameters and non-type template
1322 // parameter packs.
John McCallb8fc0532010-02-06 08:42:39 +00001323 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1324 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1325 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001326
1327 // We have a non-type template parameter that isn't fully substituted;
1328 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregorb98b1992009-08-11 05:31:07 +00001329 }
Mike Stump1eb44332009-09-09 15:08:12 +00001330
Richard Smith9a4db032012-09-12 00:56:43 +00001331 // Handle references to function parameter packs.
1332 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1333 if (PD->isParameterPack())
1334 return TransformFunctionParmPackRefExpr(E, PD);
1335
John McCall454feb92009-12-08 09:21:05 +00001336 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregorb98b1992009-08-11 05:31:07 +00001337}
1338
John McCall60d7b3a2010-08-24 06:29:42 +00001339ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall454feb92009-12-08 09:21:05 +00001340 CXXDefaultArgExpr *E) {
Sebastian Redla29e51b2009-11-08 13:56:19 +00001341 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1342 getDescribedFunctionTemplate() &&
1343 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor036aed12009-12-23 23:03:06 +00001344 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1345 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1346 E->getParam());
Sebastian Redla29e51b2009-11-08 13:56:19 +00001347}
1348
Douglas Gregor895162d2010-04-30 18:55:50 +00001349QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001350 FunctionProtoTypeLoc TL) {
Douglas Gregor895162d2010-04-30 18:55:50 +00001351 // We need a local instantiation scope for this function prototype.
John McCall2a7fb272010-08-25 05:32:35 +00001352 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
John McCall43fed0d2010-11-12 08:19:04 +00001353 return inherited::TransformFunctionProtoType(TLB, TL);
John McCall21ef0fa2010-03-11 09:03:00 +00001354}
1355
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001356QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1357 FunctionProtoTypeLoc TL,
1358 CXXRecordDecl *ThisContext,
1359 unsigned ThisTypeQuals) {
1360 // We need a local instantiation scope for this function prototype.
1361 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1362 return inherited::TransformFunctionProtoType(TLB, TL, ThisContext,
1363 ThisTypeQuals);
1364}
1365
John McCall21ef0fa2010-03-11 09:03:00 +00001366ParmVarDecl *
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001367TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +00001368 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001369 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001370 bool ExpectParameterPack) {
John McCallfb44de92011-05-01 22:35:37 +00001371 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001372 NumExpansions, ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +00001373}
1374
Mike Stump1eb44332009-09-09 15:08:12 +00001375QualType
John McCalla2becad2009-10-21 00:40:46 +00001376TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001377 TemplateTypeParmTypeLoc TL) {
John McCallf4c73712011-01-19 06:33:43 +00001378 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001379 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor99ebf652009-02-27 19:31:52 +00001380 // Replace the template type parameter with its corresponding
1381 // template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00001382
1383 // If the corresponding template argument is NULL or doesn't exist, it's
1384 // because we are performing instantiation from explicitly-specified
1385 // template arguments in a function template class, but there were some
Douglas Gregor16134c62009-07-01 00:28:38 +00001386 // arguments left unspecified.
John McCalla2becad2009-10-21 00:40:46 +00001387 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1388 TemplateTypeParmTypeLoc NewTL
1389 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1390 NewTL.setNameLoc(TL.getNameLoc());
1391 return TL.getType();
1392 }
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001394 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1395
1396 if (T->isParameterPack()) {
1397 assert(Arg.getKind() == TemplateArgument::Pack &&
1398 "Missing argument pack");
1399
1400 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc3069d62011-01-14 02:55:32 +00001401 // We have the template argument pack, but we're not expanding the
1402 // enclosing pack expansion yet. Just save the template argument
1403 // pack for later substitution.
1404 QualType Result
1405 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1406 SubstTemplateTypeParmPackTypeLoc NewTL
1407 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1408 NewTL.setNameLoc(TL.getNameLoc());
1409 return Result;
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001410 }
1411
Douglas Gregord3731192011-01-10 07:32:04 +00001412 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001413 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1414 }
1415
1416 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregor99ebf652009-02-27 19:31:52 +00001417 "Template argument kind mismatch");
Douglas Gregord6350ae2009-08-28 20:31:08 +00001418
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001419 QualType Replacement = Arg.getAsType();
John McCall49a832b2009-10-18 09:09:24 +00001420
1421 // TODO: only do this uniquing once, at the start of instantiation.
John McCalla2becad2009-10-21 00:40:46 +00001422 QualType Result
1423 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1424 SubstTemplateTypeParmTypeLoc NewTL
1425 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1426 NewTL.setNameLoc(TL.getNameLoc());
1427 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001428 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001429
1430 // The template type parameter comes from an inner template (e.g.,
1431 // the template parameter list of a member template inside the
1432 // template we are instantiating). Create a new template type
1433 // parameter with the template "level" reduced by one.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001434 TemplateTypeParmDecl *NewTTPDecl = 0;
1435 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1436 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1437 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1438
John McCalla2becad2009-10-21 00:40:46 +00001439 QualType Result
1440 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1441 - TemplateArgs.getNumLevels(),
1442 T->getIndex(),
1443 T->isParameterPack(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001444 NewTTPDecl);
John McCalla2becad2009-10-21 00:40:46 +00001445 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1446 NewTL.setNameLoc(TL.getNameLoc());
1447 return Result;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001448}
Douglas Gregor99ebf652009-02-27 19:31:52 +00001449
Douglas Gregorc3069d62011-01-14 02:55:32 +00001450QualType
1451TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1452 TypeLocBuilder &TLB,
1453 SubstTemplateTypeParmPackTypeLoc TL) {
1454 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1455 // We aren't expanding the parameter pack, so just return ourselves.
1456 SubstTemplateTypeParmPackTypeLoc NewTL
1457 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1458 NewTL.setNameLoc(TL.getNameLoc());
1459 return TL.getType();
1460 }
1461
1462 const TemplateArgument &ArgPack = TL.getTypePtr()->getArgumentPack();
1463 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1464 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1465
1466 QualType Result = ArgPack.pack_begin()[Index].getAsType();
1467 Result = getSema().Context.getSubstTemplateTypeParmType(
1468 TL.getTypePtr()->getReplacedParameter(),
1469 Result);
1470 SubstTemplateTypeParmTypeLoc NewTL
1471 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1472 NewTL.setNameLoc(TL.getNameLoc());
1473 return Result;
1474}
1475
John McCallce3ff2b2009-08-25 22:02:44 +00001476/// \brief Perform substitution on the type T with a given set of template
1477/// arguments.
Douglas Gregor99ebf652009-02-27 19:31:52 +00001478///
1479/// This routine substitutes the given template arguments into the
1480/// type T and produces the instantiated type.
1481///
1482/// \param T the type into which the template arguments will be
1483/// substituted. If this type is not dependent, it will be returned
1484/// immediately.
1485///
James Dennett1dfbd922012-06-14 21:40:34 +00001486/// \param Args the template arguments that will be
Douglas Gregor99ebf652009-02-27 19:31:52 +00001487/// substituted for the top-level template parameters within T.
1488///
Douglas Gregor99ebf652009-02-27 19:31:52 +00001489/// \param Loc the location in the source code where this substitution
1490/// is being performed. It will typically be the location of the
1491/// declarator (if we're instantiating the type of some declaration)
1492/// or the location of the type in the source code (if, e.g., we're
1493/// instantiating the type of a cast expression).
1494///
1495/// \param Entity the name of the entity associated with a declaration
1496/// being instantiated (if any). May be empty to indicate that there
1497/// is no such entity (if, e.g., this is a type that occurs as part of
1498/// a cast expression) or that the entity has no name (e.g., an
1499/// unnamed function parameter).
1500///
1501/// \returns If the instantiation succeeds, the instantiated
1502/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCalla93c9342009-12-07 02:54:59 +00001503TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCallcd7ba1c2009-10-21 00:58:09 +00001504 const MultiLevelTemplateArgumentList &Args,
1505 SourceLocation Loc,
1506 DeclarationName Entity) {
1507 assert(!ActiveTemplateInstantiations.empty() &&
1508 "Cannot perform an instantiation without some context on the "
1509 "instantiation stack");
1510
Douglas Gregor561f8122011-07-01 01:22:09 +00001511 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor836adf62010-05-24 17:22:01 +00001512 !T->getType()->isVariablyModifiedType())
John McCallcd7ba1c2009-10-21 00:58:09 +00001513 return T;
1514
1515 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1516 return Instantiator.TransformType(T);
1517}
1518
Douglas Gregor603cfb42011-01-05 23:12:31 +00001519TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1520 const MultiLevelTemplateArgumentList &Args,
1521 SourceLocation Loc,
1522 DeclarationName Entity) {
1523 assert(!ActiveTemplateInstantiations.empty() &&
1524 "Cannot perform an instantiation without some context on the "
1525 "instantiation stack");
1526
1527 if (TL.getType().isNull())
1528 return 0;
1529
Douglas Gregor561f8122011-07-01 01:22:09 +00001530 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor603cfb42011-01-05 23:12:31 +00001531 !TL.getType()->isVariablyModifiedType()) {
1532 // FIXME: Make a copy of the TypeLoc data here, so that we can
1533 // return a new TypeSourceInfo. Inefficient!
1534 TypeLocBuilder TLB;
1535 TLB.pushFullCopy(TL);
1536 return TLB.getTypeSourceInfo(Context, TL.getType());
1537 }
1538
1539 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1540 TypeLocBuilder TLB;
1541 TLB.reserve(TL.getFullDataSize());
1542 QualType Result = Instantiator.TransformType(TLB, TL);
1543 if (Result.isNull())
1544 return 0;
1545
1546 return TLB.getTypeSourceInfo(Context, Result);
1547}
1548
John McCallcd7ba1c2009-10-21 00:58:09 +00001549/// Deprecated form of the above.
Mike Stump1eb44332009-09-09 15:08:12 +00001550QualType Sema::SubstType(QualType T,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001551 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallce3ff2b2009-08-25 22:02:44 +00001552 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregordf667e72009-03-10 20:44:00 +00001553 assert(!ActiveTemplateInstantiations.empty() &&
1554 "Cannot perform an instantiation without some context on the "
1555 "instantiation stack");
1556
Douglas Gregor836adf62010-05-24 17:22:01 +00001557 // If T is not a dependent type or a variably-modified type, there
1558 // is nothing to do.
Douglas Gregor561f8122011-07-01 01:22:09 +00001559 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregor99ebf652009-02-27 19:31:52 +00001560 return T;
1561
Douglas Gregor577f75a2009-08-04 16:50:30 +00001562 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1563 return Instantiator.TransformType(T);
Douglas Gregor99ebf652009-02-27 19:31:52 +00001564}
Douglas Gregor2943aed2009-03-03 04:44:36 +00001565
John McCall6cd3b9f2010-04-09 17:38:44 +00001566static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor561f8122011-07-01 01:22:09 +00001567 if (T->getType()->isInstantiationDependentType() ||
1568 T->getType()->isVariablyModifiedType())
John McCall6cd3b9f2010-04-09 17:38:44 +00001569 return true;
1570
Abramo Bagnara723df242010-12-14 22:11:44 +00001571 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00001572 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCall6cd3b9f2010-04-09 17:38:44 +00001573 return false;
1574
David Blaikie39e6ab42013-02-18 22:06:02 +00001575 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
John McCall6cd3b9f2010-04-09 17:38:44 +00001576 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1577 ParmVarDecl *P = FP.getArg(I);
1578
Douglas Gregorc056c172011-05-09 20:45:16 +00001579 // The parameter's type as written might be dependent even if the
1580 // decayed type was not dependent.
1581 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
Douglas Gregor561f8122011-07-01 01:22:09 +00001582 if (TSInfo->getType()->isInstantiationDependentType())
Douglas Gregorc056c172011-05-09 20:45:16 +00001583 return true;
1584
John McCall6cd3b9f2010-04-09 17:38:44 +00001585 // TODO: currently we always rebuild expressions. When we
1586 // properly get lazier about this, we should use the same
1587 // logic to avoid rebuilding prototypes here.
Douglas Gregor7b1cf302011-01-05 21:14:17 +00001588 if (P->hasDefaultArg())
John McCall6cd3b9f2010-04-09 17:38:44 +00001589 return true;
1590 }
1591
1592 return false;
1593}
1594
1595/// A form of SubstType intended specifically for instantiating the
1596/// type of a FunctionDecl. Its purpose is solely to force the
1597/// instantiation of default-argument expressions.
1598TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1599 const MultiLevelTemplateArgumentList &Args,
1600 SourceLocation Loc,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001601 DeclarationName Entity,
1602 CXXRecordDecl *ThisContext,
1603 unsigned ThisTypeQuals) {
John McCall6cd3b9f2010-04-09 17:38:44 +00001604 assert(!ActiveTemplateInstantiations.empty() &&
1605 "Cannot perform an instantiation without some context on the "
1606 "instantiation stack");
1607
1608 if (!NeedsInstantiationAsFunctionType(T))
1609 return T;
1610
1611 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1612
1613 TypeLocBuilder TLB;
1614
1615 TypeLoc TL = T->getTypeLoc();
1616 TLB.reserve(TL.getFullDataSize());
1617
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001618 QualType Result;
David Blaikie39e6ab42013-02-18 22:06:02 +00001619
1620 if (FunctionProtoTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
1621 Result = Instantiator.TransformFunctionProtoType(TLB, Proto, ThisContext,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001622 ThisTypeQuals);
1623 } else {
1624 Result = Instantiator.TransformType(TLB, TL);
1625 }
John McCall6cd3b9f2010-04-09 17:38:44 +00001626 if (Result.isNull())
1627 return 0;
1628
1629 return TLB.getTypeSourceInfo(Context, Result);
1630}
1631
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001632ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001633 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallfb44de92011-05-01 22:35:37 +00001634 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001635 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001636 bool ExpectParameterPack) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001637 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Douglas Gregor603cfb42011-01-05 23:12:31 +00001638 TypeSourceInfo *NewDI = 0;
1639
Douglas Gregor603cfb42011-01-05 23:12:31 +00001640 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00001641 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1642
Douglas Gregor603cfb42011-01-05 23:12:31 +00001643 // We have a function parameter pack. Substitute into the pattern of the
1644 // expansion.
1645 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1646 OldParm->getLocation(), OldParm->getDeclName());
1647 if (!NewDI)
1648 return 0;
1649
1650 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1651 // We still have unexpanded parameter packs, which means that
1652 // our function parameter is still a function parameter pack.
1653 // Therefore, make its type a pack expansion type.
Douglas Gregorcded4f62011-01-14 17:04:44 +00001654 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001655 NumExpansions);
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001656 } else if (ExpectParameterPack) {
1657 // We expected to get a parameter pack but didn't (because the type
1658 // itself is not a pack expansion type), so complain. This can occur when
1659 // the substitution goes through an alias template that "loses" the
1660 // pack expansion.
1661 Diag(OldParm->getLocation(),
1662 diag::err_function_parameter_pack_without_parameter_packs)
1663 << NewDI->getType();
1664 return 0;
1665 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001666 } else {
1667 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1668 OldParm->getDeclName());
1669 }
1670
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001671 if (!NewDI)
1672 return 0;
1673
1674 if (NewDI->getType()->isVoidType()) {
1675 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1676 return 0;
1677 }
1678
1679 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001680 OldParm->getInnerLocStart(),
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001681 OldParm->getLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001682 OldParm->getIdentifier(),
1683 NewDI->getType(), NewDI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001684 OldParm->getStorageClass());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001685 if (!NewParm)
1686 return 0;
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001687
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001688 // Mark the (new) default argument as uninstantiated (if any).
1689 if (OldParm->hasUninstantiatedDefaultArg()) {
1690 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1691 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor8cfb7a32010-10-12 18:23:32 +00001692 } else if (OldParm->hasUnparsedDefaultArg()) {
1693 NewParm->setUnparsedDefaultArg();
1694 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
David Blaikie57296722012-05-01 06:05:57 +00001695 } else if (Expr *Arg = OldParm->getDefaultArg())
1696 // FIXME: if we non-lazily instantiated non-dependent default args for
1697 // non-dependent parameter types we could remove a bunch of duplicate
1698 // conversion warnings for such arguments.
1699 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001700
1701 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001702
Douglas Gregor12c9c002011-01-07 16:43:16 +00001703 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smithc0536c82012-01-25 02:14:59 +00001704 // Add the new parameter to the instantiated parameter pack.
Douglas Gregor12c9c002011-01-07 16:43:16 +00001705 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1706 } else {
1707 // Introduce an Old -> New mapping
Douglas Gregor603cfb42011-01-05 23:12:31 +00001708 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregor12c9c002011-01-07 16:43:16 +00001709 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001710
Argyrios Kyrtzidise3041be2010-07-19 10:14:41 +00001711 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1712 // can be anything, is this right ?
Fariborz Jahanian55a17c02010-07-13 21:05:02 +00001713 NewParm->setDeclContext(CurContext);
John McCallfb44de92011-05-01 22:35:37 +00001714
1715 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1716 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rose09189892013-03-08 22:25:36 +00001717
1718 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1719
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001720 return NewParm;
1721}
1722
Douglas Gregora009b592011-01-07 00:20:55 +00001723/// \brief Substitute the given template arguments into the given set of
1724/// parameters, producing the set of parameter types that would be generated
1725/// from such a substitution.
1726bool Sema::SubstParmTypes(SourceLocation Loc,
1727 ParmVarDecl **Params, unsigned NumParams,
1728 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001729 SmallVectorImpl<QualType> &ParamTypes,
1730 SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregora009b592011-01-07 00:20:55 +00001731 assert(!ActiveTemplateInstantiations.empty() &&
1732 "Cannot perform an instantiation without some context on the "
1733 "instantiation stack");
1734
1735 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1736 DeclarationName());
1737 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001738 ParamTypes, OutParams);
Douglas Gregora009b592011-01-07 00:20:55 +00001739}
1740
John McCallce3ff2b2009-08-25 22:02:44 +00001741/// \brief Perform substitution on the base class specifiers of the
1742/// given class template specialization.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001743///
1744/// Produces a diagnostic and returns true on error, returns false and
1745/// attaches the instantiated base classes to the class template
1746/// specialization if successful.
Mike Stump1eb44332009-09-09 15:08:12 +00001747bool
John McCallce3ff2b2009-08-25 22:02:44 +00001748Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1749 CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001750 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001751 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001752 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Mike Stump1eb44332009-09-09 15:08:12 +00001753 for (ClassTemplateSpecializationDecl::base_class_iterator
Douglas Gregord475b8d2009-03-25 21:17:03 +00001754 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
Douglas Gregor27b152f2009-03-10 18:52:44 +00001755 Base != BaseEnd; ++Base) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001756 if (!Base->getType()->isDependentType()) {
Fariborz Jahanian71c6e712009-07-22 17:41:53 +00001757 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
Douglas Gregor2943aed2009-03-03 04:44:36 +00001758 continue;
1759 }
1760
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001761 SourceLocation EllipsisLoc;
Douglas Gregor406f98f2011-03-02 02:04:06 +00001762 TypeSourceInfo *BaseTypeLoc;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001763 if (Base->isPackExpansion()) {
1764 // This is a pack expansion. See whether we should expand it now, or
1765 // wait until later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001766 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001767 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1768 Unexpanded);
1769 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00001770 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001771 Optional<unsigned> NumExpansions;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001772 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1773 Base->getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001774 Unexpanded,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001775 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00001776 RetainExpansion,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001777 NumExpansions)) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001778 Invalid = true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001779 continue;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001780 }
1781
1782 // If we should expand this pack expansion now, do so.
1783 if (ShouldExpand) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00001784 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001785 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1786
1787 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1788 TemplateArgs,
1789 Base->getSourceRange().getBegin(),
1790 DeclarationName());
1791 if (!BaseTypeLoc) {
1792 Invalid = true;
1793 continue;
1794 }
1795
1796 if (CXXBaseSpecifier *InstantiatedBase
1797 = CheckBaseSpecifier(Instantiation,
1798 Base->getSourceRange(),
1799 Base->isVirtual(),
1800 Base->getAccessSpecifierAsWritten(),
1801 BaseTypeLoc,
1802 SourceLocation()))
1803 InstantiatedBases.push_back(InstantiatedBase);
1804 else
1805 Invalid = true;
1806 }
1807
1808 continue;
1809 }
1810
1811 // The resulting base specifier will (still) be a pack expansion.
1812 EllipsisLoc = Base->getEllipsisLoc();
Douglas Gregor406f98f2011-03-02 02:04:06 +00001813 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1814 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1815 TemplateArgs,
1816 Base->getSourceRange().getBegin(),
1817 DeclarationName());
1818 } else {
1819 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1820 TemplateArgs,
1821 Base->getSourceRange().getBegin(),
1822 DeclarationName());
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001823 }
1824
Nick Lewycky56062202010-07-26 16:56:01 +00001825 if (!BaseTypeLoc) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001826 Invalid = true;
1827 continue;
1828 }
1829
1830 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregord475b8d2009-03-25 21:17:03 +00001831 = CheckBaseSpecifier(Instantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001832 Base->getSourceRange(),
1833 Base->isVirtual(),
1834 Base->getAccessSpecifierAsWritten(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001835 BaseTypeLoc,
1836 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001837 InstantiatedBases.push_back(InstantiatedBase);
1838 else
1839 Invalid = true;
1840 }
1841
Douglas Gregor27b152f2009-03-10 18:52:44 +00001842 if (!Invalid &&
Jay Foadbeaaccd2009-05-21 09:52:38 +00001843 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001844 InstantiatedBases.size()))
1845 Invalid = true;
1846
1847 return Invalid;
1848}
1849
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001850// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramer5bbc3852012-02-06 11:13:08 +00001851namespace clang {
1852 namespace sema {
1853 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1854 const MultiLevelTemplateArgumentList &TemplateArgs);
1855 }
1856}
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001857
Richard Smithf1c66b42012-03-14 23:13:10 +00001858/// Determine whether we would be unable to instantiate this template (because
1859/// it either has no definition, or is in the process of being instantiated).
1860static bool DiagnoseUninstantiableTemplate(Sema &S,
1861 SourceLocation PointOfInstantiation,
1862 TagDecl *Instantiation,
1863 bool InstantiatedFromMember,
1864 TagDecl *Pattern,
1865 TagDecl *PatternDef,
1866 TemplateSpecializationKind TSK,
1867 bool Complain = true) {
1868 if (PatternDef && !PatternDef->isBeingDefined())
1869 return false;
1870
1871 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1872 // Say nothing
1873 } else if (PatternDef) {
1874 assert(PatternDef->isBeingDefined());
1875 S.Diag(PointOfInstantiation,
1876 diag::err_template_instantiate_within_definition)
1877 << (TSK != TSK_ImplicitInstantiation)
1878 << S.Context.getTypeDeclType(Instantiation);
1879 // Not much point in noting the template declaration here, since
1880 // we're lexically inside it.
1881 Instantiation->setInvalidDecl();
1882 } else if (InstantiatedFromMember) {
1883 S.Diag(PointOfInstantiation,
1884 diag::err_implicit_instantiate_member_undefined)
1885 << S.Context.getTypeDeclType(Instantiation);
1886 S.Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1887 } else {
1888 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1889 << (TSK != TSK_ImplicitInstantiation)
1890 << S.Context.getTypeDeclType(Instantiation);
1891 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1892 }
1893
1894 // In general, Instantiation isn't marked invalid to get more than one
1895 // error for multiple undefined instantiations. But the code that does
1896 // explicit declaration -> explicit definition conversion can't handle
1897 // invalid declarations, so mark as invalid in that case.
1898 if (TSK == TSK_ExplicitInstantiationDeclaration)
1899 Instantiation->setInvalidDecl();
1900 return true;
1901}
1902
Douglas Gregord475b8d2009-03-25 21:17:03 +00001903/// \brief Instantiate the definition of a class from a given pattern.
1904///
1905/// \param PointOfInstantiation The point of instantiation within the
1906/// source code.
1907///
1908/// \param Instantiation is the declaration whose definition is being
1909/// instantiated. This will be either a class template specialization
1910/// or a member class of a class template specialization.
1911///
1912/// \param Pattern is the pattern from which the instantiation
1913/// occurs. This will be either the declaration of a class template or
1914/// the declaration of a member class of a class template.
1915///
1916/// \param TemplateArgs The template arguments to be substituted into
1917/// the pattern.
1918///
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001919/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor5842ba92009-08-24 15:23:48 +00001920///
1921/// \param Complain whether to complain if the class cannot be instantiated due
1922/// to the lack of a definition.
1923///
Douglas Gregord475b8d2009-03-25 21:17:03 +00001924/// \returns true if an error occurred, false otherwise.
1925bool
1926Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1927 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001928 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001929 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00001930 bool Complain) {
Mike Stump1eb44332009-09-09 15:08:12 +00001931 CXXRecordDecl *PatternDef
Douglas Gregor952b0172010-02-11 01:04:33 +00001932 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Richard Smithf1c66b42012-03-14 23:13:10 +00001933 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1934 Instantiation->getInstantiatedFromMemberClass(),
1935 Pattern, PatternDef, TSK, Complain))
Douglas Gregord475b8d2009-03-25 21:17:03 +00001936 return true;
Douglas Gregord475b8d2009-03-25 21:17:03 +00001937 Pattern = PatternDef;
1938
Douglas Gregor454885e2009-10-15 15:54:05 +00001939 // \brief Record the point of instantiation.
1940 if (MemberSpecializationInfo *MSInfo
1941 = Instantiation->getMemberSpecializationInfo()) {
1942 MSInfo->setTemplateSpecializationKind(TSK);
1943 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001944 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weberc7feca02011-12-20 20:32:49 +00001945 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001946 Spec->setTemplateSpecializationKind(TSK);
1947 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00001948 }
1949
Douglas Gregord048bb72009-03-25 21:23:52 +00001950 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001951 if (Inst)
1952 return true;
1953
1954 // Enter the scope of this instantiation. We don't use
1955 // PushDeclContext because we don't have a scope.
John McCallf5813822010-04-29 00:35:03 +00001956 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor9679caf2010-05-12 17:27:19 +00001957 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00001958 Sema::PotentiallyEvaluated);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001959
Douglas Gregor05030bb2010-03-24 01:33:17 +00001960 // If this is an instantiation of a local class, merge this local
1961 // instantiation scope with the enclosing scope. Otherwise, every
1962 // instantiation of a class has its own local instantiation scope.
1963 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall2a7fb272010-08-25 05:32:35 +00001964 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor05030bb2010-03-24 01:33:17 +00001965
John McCall1d8d1cc2010-08-01 02:01:53 +00001966 // Pull attributes from the pattern onto the instantiation.
1967 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1968
Douglas Gregord475b8d2009-03-25 21:17:03 +00001969 // Start the definition of this instantiation.
1970 Instantiation->startDefinition();
Douglas Gregor13c85772010-05-06 00:28:52 +00001971
1972 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001973
John McCallce3ff2b2009-08-25 22:02:44 +00001974 // Do substitution on the base class specifiers.
1975 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001976 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00001977
Douglas Gregord65587f2010-11-10 19:44:59 +00001978 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001979 SmallVector<Decl*, 4> Fields;
1980 SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
Richard Smith7a614d82011-06-11 17:19:42 +00001981 FieldsWithMemberInitializers;
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001982 // Delay instantiation of late parsed attributes.
1983 LateInstantiatedAttrVec LateAttrs;
1984 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1985
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001986 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001987 MemberEnd = Pattern->decls_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001988 Member != MemberEnd; ++Member) {
Argyrios Kyrtzidisbb5e4312010-11-04 03:18:57 +00001989 // Don't instantiate members not belonging in this semantic context.
1990 // e.g. for:
1991 // @code
1992 // template <int i> class A {
1993 // class B *g;
1994 // };
1995 // @endcode
1996 // 'class B' has the template as lexical context but semantically it is
1997 // introduced in namespace scope.
1998 if ((*Member)->getDeclContext() != Pattern)
1999 continue;
2000
Douglas Gregord65587f2010-11-10 19:44:59 +00002001 if ((*Member)->isInvalidDecl()) {
Richard Smithe3f470a2012-07-11 22:37:56 +00002002 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00002003 continue;
2004 }
2005
2006 Decl *NewMember = Instantiator.Visit(*Member);
Douglas Gregord475b8d2009-03-25 21:17:03 +00002007 if (NewMember) {
Richard Smith7a614d82011-06-11 17:19:42 +00002008 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCalld226f652010-08-21 09:40:31 +00002009 Fields.push_back(Field);
Richard Smith7a614d82011-06-11 17:19:42 +00002010 FieldDecl *OldField = cast<FieldDecl>(*Member);
2011 if (OldField->getInClassInitializer())
2012 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
2013 Field));
Richard Smith1af83c42012-03-23 03:33:32 +00002014 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2015 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2016 // specialization causes the implicit instantiation of the definitions
2017 // of unscoped member enumerations.
2018 // Record a point of instantiation for this implicit instantiation.
Richard Smith3343fad2012-03-23 23:09:08 +00002019 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2020 Enum->isCompleteDefinition()) {
Richard Smith1af83c42012-03-23 03:33:32 +00002021 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2022 assert(MSInfo && "no spec info for member enum specialization");
2023 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2024 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2025 }
Richard Smithe3f470a2012-07-11 22:37:56 +00002026 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2027 if (SA->isFailed()) {
2028 // A static_assert failed. Bail out; instantiating this
2029 // class is probably not meaningful.
2030 Instantiation->setInvalidDecl();
2031 break;
2032 }
Richard Smith1af83c42012-03-23 03:33:32 +00002033 }
2034
2035 if (NewMember->isInvalidDecl())
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002036 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002037 } else {
2038 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002039 // instantiations was a semantic disaster, and we'll want to mark the
2040 // declaration invalid.
2041 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregord475b8d2009-03-25 21:17:03 +00002042 }
2043 }
2044
2045 // Finish checking fields.
David Blaikie77b6de02011-09-22 02:58:26 +00002046 ActOnFields(0, Instantiation->getLocation(), Instantiation, Fields,
2047 SourceLocation(), SourceLocation(), 0);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002048 CheckCompletedCXXClass(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002049
2050 // Attach any in-class member initializers now the class is complete.
Richard Smithd5be2b52012-12-08 02:13:02 +00002051 // FIXME: We are supposed to defer instantiating these until they are needed.
Benjamin Kramer268efba2012-05-17 12:01:52 +00002052 if (!FieldsWithMemberInitializers.empty()) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002053 // C++11 [expr.prim.general]p4:
2054 // Otherwise, if a member-declarator declares a non-static data member
2055 // (9.2) of a class X, the expression this is a prvalue of type "pointer
2056 // to X" within the optional brace-or-equal-initializer. It shall not
2057 // appear elsewhere in the member-declarator.
2058 CXXThisScopeRAII ThisScope(*this, Instantiation, (unsigned)0);
2059
2060 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
2061 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
2062 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
2063 Expr *OldInit = OldField->getInClassInitializer();
Richard Smith7a614d82011-06-11 17:19:42 +00002064
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002065 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2066 /*CXXDirectInit=*/false);
2067 if (NewInit.isInvalid())
2068 NewField->setInvalidDecl();
2069 else {
2070 Expr *Init = NewInit.take();
2071 assert(Init && "no-argument initializer in class");
2072 assert(!isa<ParenListExpr>(Init) && "call-style init in class");
Richard Smithca523302012-06-10 03:12:00 +00002073 ActOnCXXInClassMemberInitializer(NewField, Init->getLocStart(), Init);
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002074 }
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002075 }
Richard Smith7a614d82011-06-11 17:19:42 +00002076 }
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002077 // Instantiate late parsed attributes, and attach them to their decls.
2078 // See Sema::InstantiateAttrs
2079 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2080 E = LateAttrs.end(); I != E; ++I) {
2081 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2082 CurrentInstantiationScope = I->Scope;
2083 Attr *NewAttr =
2084 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2085 I->NewDecl->addAttr(NewAttr);
2086 LocalInstantiationScope::deleteScopes(I->Scope,
2087 Instantiator.getStartingScope());
2088 }
2089 Instantiator.disableLateAttributeInstantiation();
2090 LateAttrs.clear();
2091
Richard Smithb9d0b762012-07-27 04:22:15 +00002092 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002093
Abramo Bagnarae9946242011-11-18 08:08:52 +00002094 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis734bd6e2012-02-11 01:59:57 +00002095 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002096 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnara09d82122011-10-03 20:34:03 +00002097 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002098 }
Abramo Bagnara09d82122011-10-03 20:34:03 +00002099
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002100 if (!Instantiation->isInvalidDecl()) {
John McCall1f2e1a92012-08-10 03:15:35 +00002101 // Perform any dependent diagnostics from the pattern.
2102 PerformDependentDiagnostics(Pattern, TemplateArgs);
2103
Douglas Gregord65587f2010-11-10 19:44:59 +00002104 // Instantiate any out-of-line class template partial
2105 // specializations now.
2106 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2107 P = Instantiator.delayed_partial_spec_begin(),
2108 PEnd = Instantiator.delayed_partial_spec_end();
2109 P != PEnd; ++P) {
2110 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2111 P->first,
2112 P->second)) {
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002113 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00002114 break;
2115 }
2116 }
2117 }
2118
Douglas Gregord475b8d2009-03-25 21:17:03 +00002119 // Exit the scope of this instantiation.
John McCallf5813822010-04-29 00:35:03 +00002120 SavedContext.pop();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002121
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002122 if (!Instantiation->isInvalidDecl()) {
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002123 Consumer.HandleTagDeclDefinition(Instantiation);
2124
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002125 // Always emit the vtable for an explicit instantiation definition
2126 // of a polymorphic class template specialization.
2127 if (TSK == TSK_ExplicitInstantiationDefinition)
2128 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2129 }
2130
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002131 return Instantiation->isInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002132}
2133
Richard Smithf1c66b42012-03-14 23:13:10 +00002134/// \brief Instantiate the definition of an enum from a given pattern.
2135///
2136/// \param PointOfInstantiation The point of instantiation within the
2137/// source code.
2138/// \param Instantiation is the declaration whose definition is being
2139/// instantiated. This will be a member enumeration of a class
2140/// temploid specialization, or a local enumeration within a
2141/// function temploid specialization.
2142/// \param Pattern The templated declaration from which the instantiation
2143/// occurs.
2144/// \param TemplateArgs The template arguments to be substituted into
2145/// the pattern.
2146/// \param TSK The kind of implicit or explicit instantiation to perform.
2147///
2148/// \return \c true if an error occurred, \c false otherwise.
2149bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2150 EnumDecl *Instantiation, EnumDecl *Pattern,
2151 const MultiLevelTemplateArgumentList &TemplateArgs,
2152 TemplateSpecializationKind TSK) {
2153 EnumDecl *PatternDef = Pattern->getDefinition();
2154 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2155 Instantiation->getInstantiatedFromMemberEnum(),
2156 Pattern, PatternDef, TSK,/*Complain*/true))
2157 return true;
2158 Pattern = PatternDef;
2159
2160 // Record the point of instantiation.
2161 if (MemberSpecializationInfo *MSInfo
2162 = Instantiation->getMemberSpecializationInfo()) {
2163 MSInfo->setTemplateSpecializationKind(TSK);
2164 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2165 }
2166
2167 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2168 if (Inst)
2169 return true;
2170
2171 // Enter the scope of this instantiation. We don't use
2172 // PushDeclContext because we don't have a scope.
2173 ContextRAII SavedContext(*this, Instantiation);
2174 EnterExpressionEvaluationContext EvalContext(*this,
2175 Sema::PotentiallyEvaluated);
2176
2177 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2178
2179 // Pull attributes from the pattern onto the instantiation.
2180 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2181
2182 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2183 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2184
2185 // Exit the scope of this instantiation.
2186 SavedContext.pop();
2187
2188 return Instantiation->isInvalidDecl();
2189}
2190
Douglas Gregor9b623632010-10-12 23:32:35 +00002191namespace {
2192 /// \brief A partial specialization whose template arguments have matched
2193 /// a given template-id.
2194 struct PartialSpecMatchResult {
2195 ClassTemplatePartialSpecializationDecl *Partial;
2196 TemplateArgumentList *Args;
Douglas Gregor9b623632010-10-12 23:32:35 +00002197 };
2198}
2199
Mike Stump1eb44332009-09-09 15:08:12 +00002200bool
Douglas Gregor2943aed2009-03-03 04:44:36 +00002201Sema::InstantiateClassTemplateSpecialization(
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002202 SourceLocation PointOfInstantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00002203 ClassTemplateSpecializationDecl *ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002204 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002205 bool Complain) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00002206 // Perform the actual instantiation on the canonical declaration.
2207 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002208 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor2943aed2009-03-03 04:44:36 +00002209
Douglas Gregor52604ab2009-09-11 21:19:12 +00002210 // Check whether we have already instantiated or specialized this class
2211 // template specialization.
2212 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2213 if (ClassTemplateSpec->getSpecializationKind() ==
2214 TSK_ExplicitInstantiationDeclaration &&
2215 TSK == TSK_ExplicitInstantiationDefinition) {
2216 // An explicit instantiation definition follows an explicit instantiation
2217 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2218 // explicit instantiation.
2219 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002220
2221 // If this is an explicit instantiation definition, mark the
2222 // vtable as used.
Nico Weberc7feca02011-12-20 20:32:49 +00002223 if (TSK == TSK_ExplicitInstantiationDefinition &&
2224 !ClassTemplateSpec->isInvalidDecl())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002225 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2226
Douglas Gregor52604ab2009-09-11 21:19:12 +00002227 return false;
2228 }
2229
2230 // We can only instantiate something that hasn't already been
2231 // instantiated or specialized. Fail without any diagnostics: our
2232 // caller will provide an error message.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002233 return true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00002234 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002235
Douglas Gregor9eea08b2009-09-15 16:51:42 +00002236 if (ClassTemplateSpec->isInvalidDecl())
2237 return true;
2238
Douglas Gregor2943aed2009-03-03 04:44:36 +00002239 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregord6350ae2009-08-28 20:31:08 +00002240 CXXRecordDecl *Pattern = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002241
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002242 // C++ [temp.class.spec.match]p1:
2243 // When a class template is used in a context that requires an
2244 // instantiation of the class, it is necessary to determine
2245 // whether the instantiation is to be generated using the primary
2246 // template or one of the partial specializations. This is done by
2247 // matching the template arguments of the class template
2248 // specialization with the template argument lists of the partial
2249 // specializations.
Douglas Gregor9b623632010-10-12 23:32:35 +00002250 typedef PartialSpecMatchResult MatchResult;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002251 SmallVector<MatchResult, 4> Matched;
2252 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002253 Template->getPartialSpecializations(PartialSpecs);
2254 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2255 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Craig Topper93e45992012-09-19 02:26:47 +00002256 TemplateDeductionInfo Info(PointOfInstantiation);
Douglas Gregorf67875d2009-06-12 18:26:56 +00002257 if (TemplateDeductionResult Result
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002258 = DeduceTemplateArguments(Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00002259 ClassTemplateSpec->getTemplateArgs(),
2260 Info)) {
2261 // FIXME: Store the failed-deduction information for use in
2262 // diagnostics, later.
2263 (void)Result;
2264 } else {
Douglas Gregor9b623632010-10-12 23:32:35 +00002265 Matched.push_back(PartialSpecMatchResult());
2266 Matched.back().Partial = Partial;
2267 Matched.back().Args = Info.take();
Douglas Gregorf67875d2009-06-12 18:26:56 +00002268 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002269 }
2270
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002271 // If we're dealing with a member template where the template parameters
2272 // have been instantiated, this provides the original template parameters
2273 // from which the member template's parameters were instantiated.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002274 SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002275
Douglas Gregored9c0f92009-10-29 00:04:11 +00002276 if (Matched.size() >= 1) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002277 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002278 if (Matched.size() == 1) {
2279 // -- If exactly one matching specialization is found, the
2280 // instantiation is generated from that specialization.
2281 // We don't need to do anything for this.
2282 } else {
2283 // -- If more than one matching specialization is found, the
2284 // partial order rules (14.5.4.2) are used to determine
2285 // whether one of the specializations is more specialized
2286 // than the others. If none of the specializations is more
2287 // specialized than all of the other matching
2288 // specializations, then the use of the class template is
2289 // ambiguous and the program is ill-formed.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002290 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002291 PEnd = Matched.end();
2292 P != PEnd; ++P) {
Douglas Gregor9b623632010-10-12 23:32:35 +00002293 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002294 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002295 == P->Partial)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002296 Best = P;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002297 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002298
Douglas Gregored9c0f92009-10-29 00:04:11 +00002299 // Determine if the best partial specialization is more specialized than
2300 // the others.
2301 bool Ambiguous = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002302 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002303 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002304 P != PEnd; ++P) {
2305 if (P != Best &&
Douglas Gregor9b623632010-10-12 23:32:35 +00002306 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002307 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002308 != Best->Partial) {
Douglas Gregored9c0f92009-10-29 00:04:11 +00002309 Ambiguous = true;
2310 break;
2311 }
2312 }
2313
2314 if (Ambiguous) {
2315 // Partial ordering did not produce a clear winner. Complain.
2316 ClassTemplateSpec->setInvalidDecl();
2317 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2318 << ClassTemplateSpec;
2319
2320 // Print the matching partial specializations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002321 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002322 PEnd = Matched.end();
2323 P != PEnd; ++P)
Douglas Gregor9b623632010-10-12 23:32:35 +00002324 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2325 << getTemplateArgumentBindingsText(
2326 P->Partial->getTemplateParameters(),
2327 *P->Args);
Douglas Gregord6350ae2009-08-28 20:31:08 +00002328
Douglas Gregored9c0f92009-10-29 00:04:11 +00002329 return true;
2330 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002331 }
2332
2333 // Instantiate using the best class template partial specialization.
Douglas Gregor9b623632010-10-12 23:32:35 +00002334 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002335 while (OrigPartialSpec->getInstantiatedFromMember()) {
2336 // If we've found an explicit specialization of this class template,
2337 // stop here and use that as the pattern.
2338 if (OrigPartialSpec->isMemberSpecialization())
2339 break;
2340
2341 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2342 }
2343
2344 Pattern = OrigPartialSpec;
Douglas Gregor9b623632010-10-12 23:32:35 +00002345 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002346 } else {
2347 // -- If no matches are found, the instantiation is generated
2348 // from the primary template.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002349 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002350 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2351 // If we've found an explicit specialization of this class template,
2352 // stop here and use that as the pattern.
2353 if (OrigTemplate->isMemberSpecialization())
2354 break;
2355
Douglas Gregord6350ae2009-08-28 20:31:08 +00002356 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002357 }
2358
Douglas Gregord6350ae2009-08-28 20:31:08 +00002359 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002360 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002361
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002362 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2363 Pattern,
2364 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002365 TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002366 Complain);
Mike Stump1eb44332009-09-09 15:08:12 +00002367
Douglas Gregor199d9912009-06-05 00:53:49 +00002368 return Result;
Douglas Gregor2943aed2009-03-03 04:44:36 +00002369}
Douglas Gregor5953d8b2009-03-19 17:26:29 +00002370
John McCallce3ff2b2009-08-25 22:02:44 +00002371/// \brief Instantiates the definitions of all of the member
2372/// of the given class, which is an instantiation of a class template
2373/// or a member class of a template.
Douglas Gregora58861f2009-05-13 20:28:22 +00002374void
2375Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002376 CXXRecordDecl *Instantiation,
2377 const MultiLevelTemplateArgumentList &TemplateArgs,
2378 TemplateSpecializationKind TSK) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002379 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
2380 DEnd = Instantiation->decls_end();
Douglas Gregora58861f2009-05-13 20:28:22 +00002381 D != DEnd; ++D) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002382 bool SuppressNew = false;
Douglas Gregora58861f2009-05-13 20:28:22 +00002383 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002384 if (FunctionDecl *Pattern
2385 = Function->getInstantiatedFromMemberFunction()) {
2386 MemberSpecializationInfo *MSInfo
2387 = Function->getMemberSpecializationInfo();
2388 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002389 if (MSInfo->getTemplateSpecializationKind()
2390 == TSK_ExplicitSpecialization)
2391 continue;
2392
Douglas Gregor0d035142009-10-27 18:42:08 +00002393 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2394 Function,
2395 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002396 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002397 SuppressNew) ||
2398 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002399 continue;
2400
Sean Hunt10620eb2011-05-06 20:44:56 +00002401 if (Function->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002402 continue;
2403
2404 if (TSK == TSK_ExplicitInstantiationDefinition) {
2405 // C++0x [temp.explicit]p8:
2406 // An explicit instantiation definition that names a class template
2407 // specialization explicitly instantiates the class template
2408 // specialization and is only an explicit instantiation definition
2409 // of members whose definition is visible at the point of
2410 // instantiation.
Sean Hunt10620eb2011-05-06 20:44:56 +00002411 if (!Pattern->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002412 continue;
2413
2414 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2415
2416 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2417 } else {
2418 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2419 }
Douglas Gregorf6b11852009-10-08 15:14:33 +00002420 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002421 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002422 if (Var->isStaticDataMember()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002423 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2424 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002425 if (MSInfo->getTemplateSpecializationKind()
2426 == TSK_ExplicitSpecialization)
2427 continue;
2428
Douglas Gregor0d035142009-10-27 18:42:08 +00002429 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2430 Var,
2431 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002432 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002433 SuppressNew) ||
2434 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002435 continue;
2436
Douglas Gregor0d035142009-10-27 18:42:08 +00002437 if (TSK == TSK_ExplicitInstantiationDefinition) {
2438 // C++0x [temp.explicit]p8:
2439 // An explicit instantiation definition that names a class template
2440 // specialization explicitly instantiates the class template
2441 // specialization and is only an explicit instantiation definition
2442 // of members whose definition is visible at the point of
2443 // instantiation.
2444 if (!Var->getInstantiatedFromStaticDataMember()
2445 ->getOutOfLineDefinition())
2446 continue;
2447
2448 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002449 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor0d035142009-10-27 18:42:08 +00002450 } else {
2451 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2452 }
2453 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002454 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
Douglas Gregora77eaa92010-04-18 18:11:38 +00002455 // Always skip the injected-class-name, along with any
2456 // redeclarations of nested classes, since both would cause us
2457 // to try to instantiate the members of a class twice.
Douglas Gregoref96ee02012-01-14 16:38:05 +00002458 if (Record->isInjectedClassName() || Record->getPreviousDecl())
Douglas Gregor2db32322009-10-07 23:56:10 +00002459 continue;
2460
Douglas Gregor0d035142009-10-27 18:42:08 +00002461 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2462 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002463
2464 if (MSInfo->getTemplateSpecializationKind()
2465 == TSK_ExplicitSpecialization)
2466 continue;
Nico Weberc956b6e2010-09-27 21:02:09 +00002467
Douglas Gregor0d035142009-10-27 18:42:08 +00002468 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2469 Record,
2470 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002471 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002472 SuppressNew) ||
2473 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002474 continue;
2475
Douglas Gregor0d035142009-10-27 18:42:08 +00002476 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2477 assert(Pattern && "Missing instantiated-from-template information");
2478
Douglas Gregor952b0172010-02-11 01:04:33 +00002479 if (!Record->getDefinition()) {
2480 if (!Pattern->getDefinition()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002481 // C++0x [temp.explicit]p8:
2482 // An explicit instantiation definition that names a class template
2483 // specialization explicitly instantiates the class template
2484 // specialization and is only an explicit instantiation definition
2485 // of members whose definition is visible at the point of
2486 // instantiation.
2487 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2488 MSInfo->setTemplateSpecializationKind(TSK);
2489 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2490 }
2491
2492 continue;
2493 }
2494
2495 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002496 TemplateArgs,
2497 TSK);
Nico Weberc956b6e2010-09-27 21:02:09 +00002498 } else {
2499 if (TSK == TSK_ExplicitInstantiationDefinition &&
2500 Record->getTemplateSpecializationKind() ==
2501 TSK_ExplicitInstantiationDeclaration) {
2502 Record->setTemplateSpecializationKind(TSK);
2503 MarkVTableUsed(PointOfInstantiation, Record, true);
2504 }
Douglas Gregor0d035142009-10-27 18:42:08 +00002505 }
Douglas Gregore9374d52009-10-08 01:19:17 +00002506
Douglas Gregor952b0172010-02-11 01:04:33 +00002507 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00002508 if (Pattern)
2509 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2510 TSK);
Richard Smithf1c66b42012-03-14 23:13:10 +00002511 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(*D)) {
2512 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2513 assert(MSInfo && "No member specialization information?");
2514
2515 if (MSInfo->getTemplateSpecializationKind()
2516 == TSK_ExplicitSpecialization)
2517 continue;
2518
2519 if (CheckSpecializationInstantiationRedecl(
2520 PointOfInstantiation, TSK, Enum,
2521 MSInfo->getTemplateSpecializationKind(),
2522 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2523 SuppressNew)
2524 continue;
2525
2526 if (Enum->getDefinition())
2527 continue;
2528
2529 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2530 assert(Pattern && "Missing instantiated-from-template information");
2531
2532 if (TSK == TSK_ExplicitInstantiationDefinition) {
2533 if (!Pattern->getDefinition())
2534 continue;
2535
2536 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2537 } else {
2538 MSInfo->setTemplateSpecializationKind(TSK);
2539 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2540 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002541 }
2542 }
2543}
2544
2545/// \brief Instantiate the definitions of all of the members of the
2546/// given class template specialization, which was named as part of an
2547/// explicit instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +00002548void
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002549Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregora58861f2009-05-13 20:28:22 +00002550 SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002551 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2552 TemplateSpecializationKind TSK) {
Douglas Gregora58861f2009-05-13 20:28:22 +00002553 // C++0x [temp.explicit]p7:
2554 // An explicit instantiation that names a class template
2555 // specialization is an explicit instantion of the same kind
2556 // (declaration or definition) of each of its members (not
2557 // including members inherited from base classes) that has not
2558 // been previously explicitly specialized in the translation unit
2559 // containing the explicit instantiation, except as described
2560 // below.
2561 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002562 getTemplateInstantiationArgs(ClassTemplateSpec),
2563 TSK);
Douglas Gregora58861f2009-05-13 20:28:22 +00002564}
2565
John McCall60d7b3a2010-08-24 06:29:42 +00002566StmtResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002567Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor43959a92009-08-20 07:17:43 +00002568 if (!S)
2569 return Owned(S);
2570
2571 TemplateInstantiator Instantiator(*this, TemplateArgs,
2572 SourceLocation(),
2573 DeclarationName());
2574 return Instantiator.TransformStmt(S);
2575}
2576
John McCall60d7b3a2010-08-24 06:29:42 +00002577ExprResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002578Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorb98b1992009-08-11 05:31:07 +00002579 if (!E)
2580 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002581
Douglas Gregorb98b1992009-08-11 05:31:07 +00002582 TemplateInstantiator Instantiator(*this, TemplateArgs,
2583 SourceLocation(),
2584 DeclarationName());
2585 return Instantiator.TransformExpr(E);
2586}
2587
Richard Smithc83c2302012-12-19 01:39:02 +00002588ExprResult Sema::SubstInitializer(Expr *Init,
2589 const MultiLevelTemplateArgumentList &TemplateArgs,
2590 bool CXXDirectInit) {
2591 TemplateInstantiator Instantiator(*this, TemplateArgs,
2592 SourceLocation(),
2593 DeclarationName());
2594 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2595}
2596
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002597bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2598 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002599 SmallVectorImpl<Expr *> &Outputs) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002600 if (NumExprs == 0)
2601 return false;
Richard Smithc83c2302012-12-19 01:39:02 +00002602
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002603 TemplateInstantiator Instantiator(*this, TemplateArgs,
2604 SourceLocation(),
2605 DeclarationName());
2606 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2607}
2608
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002609NestedNameSpecifierLoc
2610Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2611 const MultiLevelTemplateArgumentList &TemplateArgs) {
2612 if (!NNS)
2613 return NestedNameSpecifierLoc();
2614
2615 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2616 DeclarationName());
2617 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2618}
2619
Abramo Bagnara25777432010-08-11 22:01:17 +00002620/// \brief Do template substitution on declaration name info.
2621DeclarationNameInfo
2622Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2623 const MultiLevelTemplateArgumentList &TemplateArgs) {
2624 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2625 NameInfo.getName());
2626 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2627}
2628
Douglas Gregorde650ae2009-03-31 18:38:02 +00002629TemplateName
Douglas Gregor1d752d72011-03-02 18:46:51 +00002630Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2631 TemplateName Name, SourceLocation Loc,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002632 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord1067e52009-08-06 06:41:21 +00002633 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2634 DeclarationName());
Douglas Gregor1d752d72011-03-02 18:46:51 +00002635 CXXScopeSpec SS;
2636 SS.Adopt(QualifierLoc);
2637 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregorde650ae2009-03-31 18:38:02 +00002638}
Douglas Gregor91333002009-06-11 00:06:24 +00002639
Douglas Gregore02e2622010-12-22 21:19:48 +00002640bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2641 TemplateArgumentListInfo &Result,
John McCall833ca992009-10-29 08:12:44 +00002642 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor670444e2009-08-04 22:27:00 +00002643 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2644 DeclarationName());
Douglas Gregore02e2622010-12-22 21:19:48 +00002645
2646 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregor91333002009-06-11 00:06:24 +00002647}
Douglas Gregor895162d2010-04-30 18:55:50 +00002648
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002649
2650static const Decl* getCanonicalParmVarDecl(const Decl *D) {
2651 // When storing ParmVarDecls in the local instantiation scope, we always
2652 // want to use the ParmVarDecl from the canonical function declaration,
2653 // since the map is then valid for any redeclaration or definition of that
2654 // function.
2655 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2656 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2657 unsigned i = PV->getFunctionScopeIndex();
2658 return FD->getCanonicalDecl()->getParamDecl(i);
2659 }
2660 }
2661 return D;
2662}
2663
2664
Douglas Gregor12c9c002011-01-07 16:43:16 +00002665llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2666LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002667 D = getCanonicalParmVarDecl(D);
Chris Lattner57ad3782011-02-17 20:34:02 +00002668 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor895162d2010-04-30 18:55:50 +00002669 Current = Current->Outer) {
Chris Lattner57ad3782011-02-17 20:34:02 +00002670
Douglas Gregor895162d2010-04-30 18:55:50 +00002671 // Check if we found something within this scope.
Douglas Gregorebb1c562010-12-21 21:22:51 +00002672 const Decl *CheckD = D;
2673 do {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002674 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregorebb1c562010-12-21 21:22:51 +00002675 if (Found != Current->LocalDecls.end())
Douglas Gregor12c9c002011-01-07 16:43:16 +00002676 return &Found->second;
Douglas Gregorebb1c562010-12-21 21:22:51 +00002677
2678 // If this is a tag declaration, it's possible that we need to look for
2679 // a previous declaration.
2680 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregoref96ee02012-01-14 16:38:05 +00002681 CheckD = Tag->getPreviousDecl();
Douglas Gregorebb1c562010-12-21 21:22:51 +00002682 else
2683 CheckD = 0;
2684 } while (CheckD);
2685
Douglas Gregor895162d2010-04-30 18:55:50 +00002686 // If we aren't combined with our outer scope, we're done.
2687 if (!Current->CombineWithOuterScope)
2688 break;
2689 }
Chris Lattner57ad3782011-02-17 20:34:02 +00002690
2691 // If we didn't find the decl, then we either have a sema bug, or we have a
2692 // forward reference to a label declaration. Return null to indicate that
2693 // we have an uninstantiated label.
2694 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Douglas Gregor895162d2010-04-30 18:55:50 +00002695 return 0;
2696}
2697
John McCall2a7fb272010-08-25 05:32:35 +00002698void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002699 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002700 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregord3731192011-01-10 07:32:04 +00002701 if (Stored.isNull())
2702 Stored = Inst;
Benjamin Kramer3bbffd52013-04-12 15:22:25 +00002703 else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>())
2704 Pack->push_back(Inst);
2705 else
Douglas Gregord3731192011-01-10 07:32:04 +00002706 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Douglas Gregor895162d2010-04-30 18:55:50 +00002707}
Douglas Gregor12c9c002011-01-07 16:43:16 +00002708
2709void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2710 Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002711 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002712 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2713 Pack->push_back(Inst);
2714}
2715
2716void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002717 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002718 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2719 assert(Stored.isNull() && "Already instantiated this local");
2720 DeclArgumentPack *Pack = new DeclArgumentPack;
2721 Stored = Pack;
2722 ArgumentPacks.push_back(Pack);
2723}
2724
Douglas Gregord3731192011-01-10 07:32:04 +00002725void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2726 const TemplateArgument *ExplicitArgs,
2727 unsigned NumExplicitArgs) {
2728 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2729 "Already have a partially-substituted pack");
2730 assert((!PartiallySubstitutedPack
2731 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2732 "Wrong number of arguments in partially-substituted pack");
2733 PartiallySubstitutedPack = Pack;
2734 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2735 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2736}
2737
2738NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2739 const TemplateArgument **ExplicitArgs,
2740 unsigned *NumExplicitArgs) const {
2741 if (ExplicitArgs)
2742 *ExplicitArgs = 0;
2743 if (NumExplicitArgs)
2744 *NumExplicitArgs = 0;
2745
2746 for (const LocalInstantiationScope *Current = this; Current;
2747 Current = Current->Outer) {
2748 if (Current->PartiallySubstitutedPack) {
2749 if (ExplicitArgs)
2750 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2751 if (NumExplicitArgs)
2752 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2753
2754 return Current->PartiallySubstitutedPack;
2755 }
2756
2757 if (!Current->CombineWithOuterScope)
2758 break;
2759 }
2760
2761 return 0;
2762}