blob: 57eb64d127ae4f96b6a2d850a6761913107407eb [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;
Richard Smithb7751002013-07-25 23:08:39 +0000401
402 // Name lookup no longer looks in this template's defining module.
403 assert(SemaRef.ActiveTemplateInstantiations.size() >=
404 SemaRef.ActiveTemplateInstantiationLookupModules.size() &&
405 "forgot to remove a lookup module for a template instantiation");
406 if (SemaRef.ActiveTemplateInstantiations.size() ==
407 SemaRef.ActiveTemplateInstantiationLookupModules.size()) {
408 if (Module *M = SemaRef.ActiveTemplateInstantiationLookupModules.back())
409 SemaRef.LookupModulesCache.erase(M);
410 SemaRef.ActiveTemplateInstantiationLookupModules.pop_back();
411 }
412
Douglas Gregor26dce442009-03-10 00:06:19 +0000413 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000414 Invalid = true;
415 }
Douglas Gregor26dce442009-03-10 00:06:19 +0000416}
417
Douglas Gregordf667e72009-03-10 20:44:00 +0000418bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
419 SourceLocation PointOfInstantiation,
420 SourceRange InstantiationRange) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000421 assert(SemaRef.NonInstantiationEntries <=
422 SemaRef.ActiveTemplateInstantiations.size());
423 if ((SemaRef.ActiveTemplateInstantiations.size() -
424 SemaRef.NonInstantiationEntries)
David Blaikie4e4d0842012-03-11 07:00:24 +0000425 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregordf667e72009-03-10 20:44:00 +0000426 return false;
427
Mike Stump1eb44332009-09-09 15:08:12 +0000428 SemaRef.Diag(PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000429 diag::err_template_recursion_depth_exceeded)
David Blaikie4e4d0842012-03-11 07:00:24 +0000430 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregordf667e72009-03-10 20:44:00 +0000431 << InstantiationRange;
432 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikie4e4d0842012-03-11 07:00:24 +0000433 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregordf667e72009-03-10 20:44:00 +0000434 return true;
435}
436
Douglas Gregoree1828a2009-03-10 18:03:33 +0000437/// \brief Prints the current instantiation stack through a series of
438/// notes.
439void Sema::PrintInstantiationStack() {
Douglas Gregor575cf372010-04-20 07:18:24 +0000440 // Determine which template instantiations to skip, if any.
441 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
442 unsigned Limit = Diags.getTemplateBacktraceLimit();
443 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
444 SkipStart = Limit / 2 + Limit % 2;
445 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
446 }
447
Douglas Gregorcca9e962009-07-01 22:01:06 +0000448 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregor575cf372010-04-20 07:18:24 +0000449 unsigned InstantiationIdx = 0;
Craig Topper09d19ef2013-07-04 03:08:24 +0000450 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
Douglas Gregoree1828a2009-03-10 18:03:33 +0000451 Active = ActiveTemplateInstantiations.rbegin(),
452 ActiveEnd = ActiveTemplateInstantiations.rend();
453 Active != ActiveEnd;
Douglas Gregor575cf372010-04-20 07:18:24 +0000454 ++Active, ++InstantiationIdx) {
455 // Skip this instantiation?
456 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
457 if (InstantiationIdx == SkipStart) {
458 // Note that we're skipping instantiations.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000459 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor575cf372010-04-20 07:18:24 +0000460 diag::note_instantiation_contexts_suppressed)
461 << unsigned(ActiveTemplateInstantiations.size() - Limit);
462 }
463 continue;
464 }
465
Douglas Gregordf667e72009-03-10 20:44:00 +0000466 switch (Active->Kind) {
467 case ActiveTemplateInstantiation::TemplateInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000468 Decl *D = Active->Entity;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000469 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
470 unsigned DiagID = diag::note_template_member_class_here;
471 if (isa<ClassTemplateSpecializationDecl>(Record))
472 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000473 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000474 << Context.getTypeDeclType(Record)
475 << Active->InstantiationRange;
Douglas Gregor7caa6822009-07-24 20:34:43 +0000476 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1637be72009-06-26 00:10:03 +0000477 unsigned DiagID;
478 if (Function->getPrimaryTemplate())
479 DiagID = diag::note_function_template_spec_here;
480 else
481 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000482 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000483 << Function
484 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000485 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000486 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor7caa6822009-07-24 20:34:43 +0000487 diag::note_template_static_data_member_def_here)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000488 << VD
489 << Active->InstantiationRange;
Richard Smithf1c66b42012-03-14 23:13:10 +0000490 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
491 Diags.Report(Active->PointOfInstantiation,
492 diag::note_template_enum_def_here)
493 << ED
494 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000495 } else {
496 Diags.Report(Active->PointOfInstantiation,
497 diag::note_template_type_alias_instantiation_here)
498 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregor7caa6822009-07-24 20:34:43 +0000499 << Active->InstantiationRange;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000500 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000501 break;
502 }
503
504 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000505 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
Benjamin Kramer5eada842013-02-22 15:46:01 +0000506 SmallVector<char, 128> TemplateArgsStr;
507 llvm::raw_svector_ostream OS(TemplateArgsStr);
508 Template->printName(OS);
509 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000510 Active->TemplateArgs,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000511 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000512 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000513 Diags.Report(Active->PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000514 diag::note_default_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000515 << OS.str()
Douglas Gregordf667e72009-03-10 20:44:00 +0000516 << Active->InstantiationRange;
517 break;
518 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000519
Douglas Gregorcca9e962009-07-01 22:01:06 +0000520 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000521 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000522 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000523 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000524 << FnTmpl
525 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
526 Active->TemplateArgs,
527 Active->NumTemplateArgs)
528 << Active->InstantiationRange;
Douglas Gregor637a4092009-06-10 23:47:09 +0000529 break;
530 }
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Douglas Gregorcca9e962009-07-01 22:01:06 +0000532 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000533 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
534 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000535 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000536 diag::note_partial_spec_deduct_instantiation_here)
537 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor5e402912010-03-30 20:35:20 +0000538 << getTemplateArgumentBindingsText(
539 PartialSpec->getTemplateParameters(),
540 Active->TemplateArgs,
541 Active->NumTemplateArgs)
Douglas Gregorcca9e962009-07-01 22:01:06 +0000542 << Active->InstantiationRange;
543 } else {
544 FunctionTemplateDecl *FnTmpl
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000545 = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000546 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000547 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000548 << FnTmpl
549 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
550 Active->TemplateArgs,
551 Active->NumTemplateArgs)
552 << Active->InstantiationRange;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000553 }
554 break;
Douglas Gregor637a4092009-06-10 23:47:09 +0000555
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000556 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000557 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000558 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Benjamin Kramer5eada842013-02-22 15:46:01 +0000560 SmallVector<char, 128> TemplateArgsStr;
561 llvm::raw_svector_ostream OS(TemplateArgsStr);
562 FD->printName(OS);
563 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000564 Active->TemplateArgs,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000565 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000566 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000567 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000568 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000569 << OS.str()
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000570 << Active->InstantiationRange;
571 break;
572 }
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000574 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000575 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000576 std::string Name;
577 if (!Parm->getName().empty())
578 Name = std::string(" '") + Parm->getName().str() + "'";
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000579
580 TemplateParameterList *TemplateParams = 0;
581 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
582 TemplateParams = Template->getTemplateParameters();
583 else
584 TemplateParams =
585 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
586 ->getTemplateParameters();
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000587 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000588 diag::note_prior_template_arg_substitution)
589 << isa<TemplateTemplateParmDecl>(Parm)
590 << Name
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000591 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000592 Active->TemplateArgs,
593 Active->NumTemplateArgs)
594 << Active->InstantiationRange;
595 break;
596 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000597
598 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000599 TemplateParameterList *TemplateParams = 0;
600 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
601 TemplateParams = Template->getTemplateParameters();
602 else
603 TemplateParams =
604 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
605 ->getTemplateParameters();
606
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000607 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000608 diag::note_template_default_arg_checking)
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000609 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000610 Active->TemplateArgs,
611 Active->NumTemplateArgs)
612 << Active->InstantiationRange;
613 break;
614 }
Richard Smithe6975e92012-04-17 00:58:00 +0000615
616 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
617 Diags.Report(Active->PointOfInstantiation,
618 diag::note_template_exception_spec_instantiation_here)
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000619 << cast<FunctionDecl>(Active->Entity)
Richard Smithe6975e92012-04-17 00:58:00 +0000620 << Active->InstantiationRange;
621 break;
Douglas Gregordf667e72009-03-10 20:44:00 +0000622 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000623 }
624}
625
David Blaikiedc84cd52013-02-20 22:23:23 +0000626Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000627 if (InNonInstantiationSFINAEContext)
David Blaikiedc84cd52013-02-20 22:23:23 +0000628 return Optional<TemplateDeductionInfo *>(0);
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000629
Craig Topper09d19ef2013-07-04 03:08:24 +0000630 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000631 Active = ActiveTemplateInstantiations.rbegin(),
632 ActiveEnd = ActiveTemplateInstantiations.rend();
633 Active != ActiveEnd;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000634 ++Active)
635 {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000636 switch(Active->Kind) {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000637 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smitha43ea642012-04-26 07:24:08 +0000638 // An instantiation of an alias template may or may not be a SFINAE
639 // context, depending on what else is on the stack.
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000640 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smitha43ea642012-04-26 07:24:08 +0000641 break;
642 // Fall through.
643 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000644 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorcca9e962009-07-01 22:01:06 +0000645 // This is a template instantiation, so there is no SFINAE.
David Blaikie66874fb2013-02-21 01:47:18 +0000646 return None;
Mike Stump1eb44332009-09-09 15:08:12 +0000647
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000648 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000649 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000650 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000651 // A default template argument instantiation and substitution into
652 // template parameters with arguments for prior parameters may or may
653 // not be a SFINAE context; look further up the stack.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000654 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000655
Douglas Gregorcca9e962009-07-01 22:01:06 +0000656 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
657 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
658 // We're either substitution explicitly-specified template arguments
659 // or deduced template arguments, so SFINAE applies.
Douglas Gregor9b623632010-10-12 23:32:35 +0000660 assert(Active->DeductionInfo && "Missing deduction info pointer");
661 return Active->DeductionInfo;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000662 }
663 }
664
David Blaikie66874fb2013-02-21 01:47:18 +0000665 return None;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000666}
667
Douglas Gregord3731192011-01-10 07:32:04 +0000668/// \brief Retrieve the depth and index of a parameter pack.
669static std::pair<unsigned, unsigned>
670getDepthAndIndex(NamedDecl *ND) {
671 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
672 return std::make_pair(TTP->getDepth(), TTP->getIndex());
673
674 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
675 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
676
677 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
678 return std::make_pair(TTP->getDepth(), TTP->getIndex());
679}
680
Douglas Gregor99ebf652009-02-27 19:31:52 +0000681//===----------------------------------------------------------------------===/
682// Template Instantiation for Types
683//===----------------------------------------------------------------------===/
Douglas Gregorcd281c32009-02-28 00:25:32 +0000684namespace {
Douglas Gregor895162d2010-04-30 18:55:50 +0000685 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000686 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000687 SourceLocation Loc;
688 DeclarationName Entity;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000689
Douglas Gregorcd281c32009-02-28 00:25:32 +0000690 public:
Douglas Gregor43959a92009-08-20 07:17:43 +0000691 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump1eb44332009-09-09 15:08:12 +0000692
693 TemplateInstantiator(Sema &SemaRef,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000694 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor577f75a2009-08-04 16:50:30 +0000695 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000696 DeclarationName Entity)
697 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregor43959a92009-08-20 07:17:43 +0000698 Entity(Entity) { }
Douglas Gregorcd281c32009-02-28 00:25:32 +0000699
Mike Stump1eb44332009-09-09 15:08:12 +0000700 /// \brief Determine whether the given type \p T has already been
Douglas Gregor577f75a2009-08-04 16:50:30 +0000701 /// transformed.
702 ///
703 /// For the purposes of template instantiation, a type has already been
704 /// transformed if it is NULL or if it is not dependent.
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000705 bool AlreadyTransformed(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Douglas Gregor577f75a2009-08-04 16:50:30 +0000707 /// \brief Returns the location of the entity being instantiated, if known.
708 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Douglas Gregor577f75a2009-08-04 16:50:30 +0000710 /// \brief Returns the name of the entity being instantiated, if any.
711 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Douglas Gregor972e6ce2009-10-27 06:26:26 +0000713 /// \brief Sets the "base" location and entity when that
714 /// information is known based on another transformation.
715 void setBase(SourceLocation Loc, DeclarationName Entity) {
716 this->Loc = Loc;
717 this->Entity = Entity;
718 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000719
720 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
721 SourceRange PatternRange,
David Blaikiea71f9d02011-09-22 02:34:54 +0000722 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000723 bool &ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000724 bool &RetainExpansion,
David Blaikiedc84cd52013-02-20 22:23:23 +0000725 Optional<unsigned> &NumExpansions) {
Douglas Gregorb99268b2010-12-21 00:52:54 +0000726 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
727 PatternRange, Unexpanded,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000728 TemplateArgs,
729 ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000730 RetainExpansion,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000731 NumExpansions);
732 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000733
Douglas Gregor12c9c002011-01-07 16:43:16 +0000734 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
735 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
736 }
737
Douglas Gregord3731192011-01-10 07:32:04 +0000738 TemplateArgument ForgetPartiallySubstitutedPack() {
739 TemplateArgument Result;
740 if (NamedDecl *PartialPack
741 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
742 MultiLevelTemplateArgumentList &TemplateArgs
743 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
744 unsigned Depth, Index;
745 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
746 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
747 Result = TemplateArgs(Depth, Index);
748 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
749 }
750 }
751
752 return Result;
753 }
754
755 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
756 if (Arg.isNull())
757 return;
758
759 if (NamedDecl *PartialPack
760 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
761 MultiLevelTemplateArgumentList &TemplateArgs
762 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
763 unsigned Depth, Index;
764 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
765 TemplateArgs.setArgument(Depth, Index, Arg);
766 }
767 }
768
Douglas Gregor577f75a2009-08-04 16:50:30 +0000769 /// \brief Transform the given declaration by instantiating a reference to
770 /// this declaration.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000771 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregorb98b1992009-08-11 05:31:07 +0000772
Douglas Gregordfca6f52012-02-13 22:00:16 +0000773 void transformAttrs(Decl *Old, Decl *New) {
774 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
775 }
776
777 void transformedLocalDecl(Decl *Old, Decl *New) {
778 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
779 }
780
Mike Stump1eb44332009-09-09 15:08:12 +0000781 /// \brief Transform the definition of the given declaration by
Douglas Gregor43959a92009-08-20 07:17:43 +0000782 /// instantiating it.
Douglas Gregoraac571c2010-03-01 17:25:41 +0000783 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Dmitri Gribenkoe23fb902012-09-12 17:01:48 +0000785 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregor6cd21982009-10-20 05:58:46 +0000786 /// declaration.
787 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
788
Douglas Gregor43959a92009-08-20 07:17:43 +0000789 /// \brief Rebuild the exception declaration and register the declaration
790 /// as an instantiated local.
Douglas Gregor83cb9422010-09-09 17:09:21 +0000791 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000792 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000793 SourceLocation StartLoc,
794 SourceLocation NameLoc,
795 IdentifierInfo *Name);
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Douglas Gregorbe270a02010-04-26 17:57:08 +0000797 /// \brief Rebuild the Objective-C exception declaration and register the
798 /// declaration as an instantiated local.
799 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
800 TypeSourceInfo *TSInfo, QualType T);
801
John McCallc4e70192009-09-11 04:59:25 +0000802 /// \brief Check for tag mismatches when instantiating an
803 /// elaborated type.
John McCall21e413f2010-11-04 19:04:38 +0000804 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
805 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000806 NestedNameSpecifierLoc QualifierLoc,
807 QualType T);
John McCallc4e70192009-09-11 04:59:25 +0000808
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000809 TemplateName TransformTemplateName(CXXScopeSpec &SS,
810 TemplateName Name,
811 SourceLocation NameLoc,
812 QualType ObjectType = QualType(),
813 NamedDecl *FirstQualifierInScope = 0);
814
John McCall60d7b3a2010-08-24 06:29:42 +0000815 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
816 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
817 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000818
John McCall60d7b3a2010-08-24 06:29:42 +0000819 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor56bc9832010-12-24 00:15:10 +0000820 NonTypeTemplateParmDecl *D);
Douglas Gregorc7793c72011-01-15 01:15:58 +0000821 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
822 SubstNonTypeTemplateParmPackExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000823
824 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
825 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
826
827 /// \brief Transform a reference to a function parameter pack.
828 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
829 ParmVarDecl *PD);
830
831 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
832 /// expand a function parameter pack reference which refers to an expanded
833 /// pack.
834 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
835
Douglas Gregor895162d2010-04-30 18:55:50 +0000836 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000837 FunctionProtoTypeLoc TL);
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000838 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
839 FunctionProtoTypeLoc TL,
840 CXXRecordDecl *ThisContext,
841 unsigned ThisTypeQuals);
842
Douglas Gregor6a24bfd2011-01-14 22:40:04 +0000843 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +0000844 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +0000845 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +0000846 bool ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +0000847
Mike Stump1eb44332009-09-09 15:08:12 +0000848 /// \brief Transforms a template type parameter type by performing
Douglas Gregor577f75a2009-08-04 16:50:30 +0000849 /// substitution of the corresponding template type argument.
John McCalla2becad2009-10-21 00:40:46 +0000850 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000851 TemplateTypeParmTypeLoc TL);
Nick Lewycky03d98c52010-07-06 19:51:49 +0000852
Douglas Gregorc3069d62011-01-14 02:55:32 +0000853 /// \brief Transforms an already-substituted template type parameter pack
854 /// into either itself (if we aren't substituting into its pack expansion)
855 /// or the appropriate substituted argument.
856 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
857 SubstTemplateTypeParmPackTypeLoc TL);
858
John McCall60d7b3a2010-08-24 06:29:42 +0000859 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewycky03d98c52010-07-06 19:51:49 +0000860 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCall60d7b3a2010-08-24 06:29:42 +0000861 ExprResult Result =
Nick Lewycky03d98c52010-07-06 19:51:49 +0000862 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
863 getSema().CallsUndergoingInstantiation.pop_back();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000864 return Result;
Nick Lewycky03d98c52010-07-06 19:51:49 +0000865 }
John McCall91a57552011-07-15 05:09:51 +0000866
Richard Smith612409e2012-07-25 03:56:55 +0000867 ExprResult TransformLambdaExpr(LambdaExpr *E) {
868 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
869 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
870 }
871
872 ExprResult TransformLambdaScope(LambdaExpr *E,
873 CXXMethodDecl *CallOperator) {
874 CallOperator->setInstantiationOfMemberFunction(E->getCallOperator(),
875 TSK_ImplicitInstantiation);
876 return TreeTransform<TemplateInstantiator>::
877 TransformLambdaScope(E, CallOperator);
878 }
879
John McCall91a57552011-07-15 05:09:51 +0000880 private:
881 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
882 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +0000883 TemplateArgument arg);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000884 };
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000885}
886
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000887bool TemplateInstantiator::AlreadyTransformed(QualType T) {
888 if (T.isNull())
889 return true;
890
Douglas Gregor561f8122011-07-01 01:22:09 +0000891 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000892 return false;
893
894 getSema().MarkDeclarationsReferencedInType(Loc, T);
895 return true;
896}
897
Eli Friedman10ec0e42013-07-19 19:40:38 +0000898static TemplateArgument
899getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
900 assert(S.ArgumentPackSubstitutionIndex >= 0);
901 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
902 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
903 if (Arg.isPackExpansion())
904 Arg = Arg.getPackExpansionPattern();
905 return Arg;
906}
907
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000908Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregorc68afe22009-09-03 21:38:09 +0000909 if (!D)
910 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000911
Douglas Gregorc68afe22009-09-03 21:38:09 +0000912 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000913 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor6d3e6272010-02-05 19:54:12 +0000914 // If the corresponding template argument is NULL or non-existent, it's
915 // because we are performing instantiation from explicitly-specified
916 // template arguments in a function template, but there were some
917 // arguments left unspecified.
918 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
919 TTP->getPosition()))
920 return D;
921
Douglas Gregor61c4d282011-01-05 15:48:55 +0000922 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
923
924 if (TTP->isParameterPack()) {
925 assert(Arg.getKind() == TemplateArgument::Pack &&
926 "Missing argument pack");
Eli Friedman10ec0e42013-07-19 19:40:38 +0000927 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000928 }
929
930 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor788cd062009-11-11 01:00:40 +0000931 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregord6350ae2009-08-28 20:31:08 +0000932 "Wrong kind of template template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000933 return Template.getAsTemplateDecl();
Douglas Gregord6350ae2009-08-28 20:31:08 +0000934 }
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Douglas Gregor788cd062009-11-11 01:00:40 +0000936 // Fall through to find the instantiated declaration for this template
937 // template parameter.
Douglas Gregord1067e52009-08-06 06:41:21 +0000938 }
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000940 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000941}
942
Douglas Gregoraac571c2010-03-01 17:25:41 +0000943Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000944 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregor43959a92009-08-20 07:17:43 +0000945 if (!Inst)
946 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Douglas Gregor43959a92009-08-20 07:17:43 +0000948 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
949 return Inst;
950}
951
Douglas Gregor6cd21982009-10-20 05:58:46 +0000952NamedDecl *
953TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
954 SourceLocation Loc) {
955 // If the first part of the nested-name-specifier was a template type
956 // parameter, instantiate that type parameter down to a tag type.
957 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
958 const TemplateTypeParmType *TTP
959 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor984a58b2010-12-20 22:48:17 +0000960
Douglas Gregor6cd21982009-10-20 05:58:46 +0000961 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor984a58b2010-12-20 22:48:17 +0000962 // FIXME: This needs testing w/ member access expressions.
963 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
964
965 if (TTP->isParameterPack()) {
966 assert(Arg.getKind() == TemplateArgument::Pack &&
967 "Missing argument pack");
968
Douglas Gregor2be29f42011-01-14 23:41:42 +0000969 if (getSema().ArgumentPackSubstitutionIndex == -1)
Douglas Gregor984a58b2010-12-20 22:48:17 +0000970 return 0;
Douglas Gregor984a58b2010-12-20 22:48:17 +0000971
Eli Friedman10ec0e42013-07-19 19:40:38 +0000972 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor984a58b2010-12-20 22:48:17 +0000973 }
974
975 QualType T = Arg.getAsType();
Douglas Gregor6cd21982009-10-20 05:58:46 +0000976 if (T.isNull())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000977 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000978
979 if (const TagType *Tag = T->getAs<TagType>())
980 return Tag->getDecl();
981
982 // The resulting type is not a tag; complain.
983 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
984 return 0;
985 }
986 }
987
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000988 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000989}
990
Douglas Gregor43959a92009-08-20 07:17:43 +0000991VarDecl *
992TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000993 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000994 SourceLocation StartLoc,
995 SourceLocation NameLoc,
996 IdentifierInfo *Name) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000997 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000998 StartLoc, NameLoc, Name);
Douglas Gregorbe270a02010-04-26 17:57:08 +0000999 if (Var)
1000 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1001 return Var;
1002}
1003
1004VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1005 TypeSourceInfo *TSInfo,
1006 QualType T) {
1007 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1008 if (Var)
Douglas Gregor43959a92009-08-20 07:17:43 +00001009 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1010 return Var;
1011}
1012
John McCallc4e70192009-09-11 04:59:25 +00001013QualType
John McCall21e413f2010-11-04 19:04:38 +00001014TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1015 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +00001016 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001017 QualType T) {
John McCallc4e70192009-09-11 04:59:25 +00001018 if (const TagType *TT = T->getAs<TagType>()) {
1019 TagDecl* TD = TT->getDecl();
1020
John McCall21e413f2010-11-04 19:04:38 +00001021 SourceLocation TagLocation = KeywordLoc;
John McCallc4e70192009-09-11 04:59:25 +00001022
John McCallc4e70192009-09-11 04:59:25 +00001023 IdentifierInfo *Id = TD->getIdentifier();
1024
1025 // TODO: should we even warn on struct/class mismatches for this? Seems
1026 // like it's likely to produce a lot of spurious errors.
Richard Smithcbf97c52012-08-17 00:12:27 +00001027 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001028 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieubbf34c02011-06-10 03:11:26 +00001029 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1030 TagLocation, *Id)) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001031 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1032 << Id
1033 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1034 TD->getKindName());
1035 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1036 }
John McCallc4e70192009-09-11 04:59:25 +00001037 }
1038 }
1039
John McCall21e413f2010-11-04 19:04:38 +00001040 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1041 Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +00001042 QualifierLoc,
1043 T);
John McCallc4e70192009-09-11 04:59:25 +00001044}
1045
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001046TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1047 TemplateName Name,
1048 SourceLocation NameLoc,
1049 QualType ObjectType,
1050 NamedDecl *FirstQualifierInScope) {
1051 if (TemplateTemplateParmDecl *TTP
1052 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1053 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1054 // If the corresponding template argument is NULL or non-existent, it's
1055 // because we are performing instantiation from explicitly-specified
1056 // template arguments in a function template, but there were some
1057 // arguments left unspecified.
1058 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1059 TTP->getPosition()))
1060 return Name;
1061
1062 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1063
1064 if (TTP->isParameterPack()) {
1065 assert(Arg.getKind() == TemplateArgument::Pack &&
1066 "Missing argument pack");
1067
1068 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1069 // We have the template argument pack to substitute, but we're not
1070 // actually expanding the enclosing pack expansion yet. So, just
1071 // keep the entire argument pack.
1072 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1073 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001074
1075 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001076 }
1077
1078 TemplateName Template = Arg.getAsTemplate();
Richard Smith3e4c6c42011-05-05 21:57:07 +00001079 assert(!Template.isNull() && "Null template template argument");
John McCall14606042011-06-30 08:33:18 +00001080
Douglas Gregor58750382011-03-05 20:06:51 +00001081 // We don't ever want to substitute for a qualified template name, since
1082 // the qualifier is handled separately. So, look through the qualified
1083 // template name to its underlying declaration.
1084 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1085 Template = TemplateName(QTN->getTemplateDecl());
John McCall14606042011-06-30 08:33:18 +00001086
1087 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001088 return Template;
1089 }
1090 }
1091
1092 if (SubstTemplateTemplateParmPackStorage *SubstPack
1093 = Name.getAsSubstTemplateTemplateParmPack()) {
1094 if (getSema().ArgumentPackSubstitutionIndex == -1)
1095 return Name;
1096
Eli Friedman10ec0e42013-07-19 19:40:38 +00001097 TemplateArgument Arg = SubstPack->getArgumentPack();
1098 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1099 return Arg.getAsTemplate();
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001100 }
1101
1102 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1103 FirstQualifierInScope);
1104}
1105
John McCall60d7b3a2010-08-24 06:29:42 +00001106ExprResult
John McCall454feb92009-12-08 09:21:05 +00001107TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson773f3972009-09-11 01:22:35 +00001108 if (!E->isTypeDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00001109 return SemaRef.Owned(E);
Anders Carlsson773f3972009-09-11 01:22:35 +00001110
1111 FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
1112 assert(currentDecl && "Must have current function declaration when "
1113 "instantiating.");
1114
1115 PredefinedExpr::IdentType IT = E->getIdentType();
1116
Anders Carlsson848fa642010-02-11 18:20:28 +00001117 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Anders Carlsson773f3972009-09-11 01:22:35 +00001118
1119 llvm::APInt LengthI(32, Length + 1);
Nico Weberb4e80082012-06-25 22:34:48 +00001120 QualType ResTy;
1121 if (IT == PredefinedExpr::LFunction)
Hans Wennborg15f92ba2013-05-10 10:08:40 +00001122 ResTy = getSema().Context.WideCharTy.withConst();
Nico Weberb4e80082012-06-25 22:34:48 +00001123 else
1124 ResTy = getSema().Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001125 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
1126 ArrayType::Normal, 0);
1127 PredefinedExpr *PE =
1128 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
1129 return getSema().Owned(PE);
1130}
1131
John McCall60d7b3a2010-08-24 06:29:42 +00001132ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001133TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregordcee9802010-02-08 23:41:45 +00001134 NonTypeTemplateParmDecl *NTTP) {
John McCallb8fc0532010-02-06 08:42:39 +00001135 // If the corresponding template argument is NULL or non-existent, it's
1136 // because we are performing instantiation from explicitly-specified
1137 // template arguments in a function template, but there were some
1138 // arguments left unspecified.
1139 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1140 NTTP->getPosition()))
John McCall3fa5cae2010-10-26 07:05:15 +00001141 return SemaRef.Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Douglas Gregor56bc9832010-12-24 00:15:10 +00001143 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1144 if (NTTP->isParameterPack()) {
1145 assert(Arg.getKind() == TemplateArgument::Pack &&
1146 "Missing argument pack");
1147
1148 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc7793c72011-01-15 01:15:58 +00001149 // We have an argument pack, but we can't select a particular argument
1150 // out of it yet. Therefore, we'll build an expression to hold on to that
1151 // argument pack.
1152 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1153 E->getLocation(),
1154 NTTP->getDeclName());
1155 if (TargetType.isNull())
1156 return ExprError();
1157
1158 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1159 NTTP,
1160 E->getLocation(),
1161 Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001162 }
1163
Eli Friedman10ec0e42013-07-19 19:40:38 +00001164 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001165 }
Mike Stump1eb44332009-09-09 15:08:12 +00001166
John McCall91a57552011-07-15 05:09:51 +00001167 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1168}
1169
1170ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1171 NonTypeTemplateParmDecl *parm,
1172 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +00001173 TemplateArgument arg) {
John McCall91a57552011-07-15 05:09:51 +00001174 ExprResult result;
1175 QualType type;
1176
John McCallb8fc0532010-02-06 08:42:39 +00001177 // The template argument itself might be an expression, in which
1178 // case we just return that expression.
John McCall91a57552011-07-15 05:09:51 +00001179 if (arg.getKind() == TemplateArgument::Expression) {
1180 Expr *argExpr = arg.getAsExpr();
1181 result = SemaRef.Owned(argExpr);
1182 type = argExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Eli Friedmand7a6b162012-09-26 02:36:12 +00001184 } else if (arg.getKind() == TemplateArgument::Declaration ||
1185 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregord2008e22012-04-06 22:40:38 +00001186 ValueDecl *VD;
Eli Friedmand7a6b162012-09-26 02:36:12 +00001187 if (arg.getKind() == TemplateArgument::Declaration) {
1188 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Douglas Gregord2008e22012-04-06 22:40:38 +00001190 // Find the instantiation of the template argument. This is
1191 // required for nested templates.
1192 VD = cast_or_null<ValueDecl>(
1193 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1194 if (!VD)
1195 return ExprError();
1196 } else {
1197 // Propagate NULL template argument.
1198 VD = 0;
1199 }
1200
John McCall645cf442010-02-06 10:23:53 +00001201 // Derive the type we want the substituted decl to have. This had
1202 // better be non-dependent, or these checks will have serious problems.
John McCall91a57552011-07-15 05:09:51 +00001203 if (parm->isExpandedParameterPack()) {
1204 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1205 } else if (parm->isParameterPack() &&
1206 isa<PackExpansionType>(parm->getType())) {
1207 type = SemaRef.SubstType(
1208 cast<PackExpansionType>(parm->getType())->getPattern(),
1209 TemplateArgs, loc, parm->getDeclName());
1210 } else {
1211 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1212 loc, parm->getDeclName());
1213 }
1214 assert(!type.isNull() && "type substitution failed for param type");
1215 assert(!type->isDependentType() && "param type still dependent");
1216 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCallb8fc0532010-02-06 08:42:39 +00001217
John McCall91a57552011-07-15 05:09:51 +00001218 if (!result.isInvalid()) type = result.get()->getType();
1219 } else {
1220 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1221
1222 // Note that this type can be different from the type of 'result',
1223 // e.g. if it's an enum type.
1224 type = arg.getIntegralType();
1225 }
1226 if (result.isInvalid()) return ExprError();
1227
1228 Expr *resultExpr = result.take();
1229 return SemaRef.Owned(new (SemaRef.Context)
1230 SubstNonTypeTemplateParmExpr(type,
1231 resultExpr->getValueKind(),
1232 loc, parm, resultExpr));
John McCallb8fc0532010-02-06 08:42:39 +00001233}
1234
Douglas Gregorc7793c72011-01-15 01:15:58 +00001235ExprResult
1236TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1237 SubstNonTypeTemplateParmPackExpr *E) {
1238 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1239 // We aren't expanding the parameter pack, so just return ourselves.
1240 return getSema().Owned(E);
1241 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001242
1243 TemplateArgument Arg = E->getArgumentPack();
1244 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall91a57552011-07-15 05:09:51 +00001245 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1246 E->getParameterPackLocation(),
1247 Arg);
Douglas Gregorc7793c72011-01-15 01:15:58 +00001248}
John McCallb8fc0532010-02-06 08:42:39 +00001249
John McCall60d7b3a2010-08-24 06:29:42 +00001250ExprResult
Richard Smith9a4db032012-09-12 00:56:43 +00001251TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1252 SourceLocation Loc) {
1253 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1254 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1255}
1256
1257ExprResult
1258TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1259 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1260 // We can expand this parameter pack now.
1261 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1262 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1263 if (!VD)
1264 return ExprError();
1265 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1266 }
1267
1268 QualType T = TransformType(E->getType());
1269 if (T.isNull())
1270 return ExprError();
1271
1272 // Transform each of the parameter expansions into the corresponding
1273 // parameters in the instantiation of the function decl.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001274 SmallVector<Decl *, 8> Parms;
Richard Smith9a4db032012-09-12 00:56:43 +00001275 Parms.reserve(E->getNumExpansions());
1276 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1277 I != End; ++I) {
1278 ParmVarDecl *D =
1279 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1280 if (!D)
1281 return ExprError();
1282 Parms.push_back(D);
1283 }
1284
1285 return FunctionParmPackExpr::Create(getSema().Context, T,
1286 E->getParameterPack(),
1287 E->getParameterPackLocation(), Parms);
1288}
1289
1290ExprResult
1291TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1292 ParmVarDecl *PD) {
1293 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1294 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1295 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1296 assert(Found && "no instantiation for parameter pack");
1297
1298 Decl *TransformedDecl;
1299 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1300 // If this is a reference to a function parameter pack which we can substitute
1301 // but can't yet expand, build a FunctionParmPackExpr for it.
1302 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1303 QualType T = TransformType(E->getType());
1304 if (T.isNull())
1305 return ExprError();
1306 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1307 E->getExprLoc(), *Pack);
1308 }
1309
1310 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1311 } else {
1312 TransformedDecl = Found->get<Decl*>();
1313 }
1314
1315 // We have either an unexpanded pack or a specific expansion.
1316 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1317 E->getExprLoc());
1318}
1319
1320ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001321TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1322 NamedDecl *D = E->getDecl();
Richard Smith9a4db032012-09-12 00:56:43 +00001323
1324 // Handle references to non-type template parameters and non-type template
1325 // parameter packs.
John McCallb8fc0532010-02-06 08:42:39 +00001326 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1327 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1328 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001329
1330 // We have a non-type template parameter that isn't fully substituted;
1331 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregorb98b1992009-08-11 05:31:07 +00001332 }
Mike Stump1eb44332009-09-09 15:08:12 +00001333
Richard Smith9a4db032012-09-12 00:56:43 +00001334 // Handle references to function parameter packs.
1335 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1336 if (PD->isParameterPack())
1337 return TransformFunctionParmPackRefExpr(E, PD);
1338
John McCall454feb92009-12-08 09:21:05 +00001339 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregorb98b1992009-08-11 05:31:07 +00001340}
1341
John McCall60d7b3a2010-08-24 06:29:42 +00001342ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall454feb92009-12-08 09:21:05 +00001343 CXXDefaultArgExpr *E) {
Sebastian Redla29e51b2009-11-08 13:56:19 +00001344 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1345 getDescribedFunctionTemplate() &&
1346 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor036aed12009-12-23 23:03:06 +00001347 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1348 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1349 E->getParam());
Sebastian Redla29e51b2009-11-08 13:56:19 +00001350}
1351
Douglas Gregor895162d2010-04-30 18:55:50 +00001352QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001353 FunctionProtoTypeLoc TL) {
Douglas Gregor895162d2010-04-30 18:55:50 +00001354 // We need a local instantiation scope for this function prototype.
John McCall2a7fb272010-08-25 05:32:35 +00001355 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
John McCall43fed0d2010-11-12 08:19:04 +00001356 return inherited::TransformFunctionProtoType(TLB, TL);
John McCall21ef0fa2010-03-11 09:03:00 +00001357}
1358
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001359QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1360 FunctionProtoTypeLoc TL,
1361 CXXRecordDecl *ThisContext,
1362 unsigned ThisTypeQuals) {
1363 // We need a local instantiation scope for this function prototype.
1364 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1365 return inherited::TransformFunctionProtoType(TLB, TL, ThisContext,
1366 ThisTypeQuals);
1367}
1368
John McCall21ef0fa2010-03-11 09:03:00 +00001369ParmVarDecl *
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001370TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +00001371 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001372 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001373 bool ExpectParameterPack) {
John McCallfb44de92011-05-01 22:35:37 +00001374 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001375 NumExpansions, ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +00001376}
1377
Mike Stump1eb44332009-09-09 15:08:12 +00001378QualType
John McCalla2becad2009-10-21 00:40:46 +00001379TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001380 TemplateTypeParmTypeLoc TL) {
John McCallf4c73712011-01-19 06:33:43 +00001381 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001382 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor99ebf652009-02-27 19:31:52 +00001383 // Replace the template type parameter with its corresponding
1384 // template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00001385
1386 // If the corresponding template argument is NULL or doesn't exist, it's
1387 // because we are performing instantiation from explicitly-specified
1388 // template arguments in a function template class, but there were some
Douglas Gregor16134c62009-07-01 00:28:38 +00001389 // arguments left unspecified.
John McCalla2becad2009-10-21 00:40:46 +00001390 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1391 TemplateTypeParmTypeLoc NewTL
1392 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1393 NewTL.setNameLoc(TL.getNameLoc());
1394 return TL.getType();
1395 }
Mike Stump1eb44332009-09-09 15:08:12 +00001396
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001397 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1398
1399 if (T->isParameterPack()) {
1400 assert(Arg.getKind() == TemplateArgument::Pack &&
1401 "Missing argument pack");
1402
1403 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc3069d62011-01-14 02:55:32 +00001404 // We have the template argument pack, but we're not expanding the
1405 // enclosing pack expansion yet. Just save the template argument
1406 // pack for later substitution.
1407 QualType Result
1408 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1409 SubstTemplateTypeParmPackTypeLoc NewTL
1410 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1411 NewTL.setNameLoc(TL.getNameLoc());
1412 return Result;
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001413 }
1414
Eli Friedman10ec0e42013-07-19 19:40:38 +00001415 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001416 }
1417
1418 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregor99ebf652009-02-27 19:31:52 +00001419 "Template argument kind mismatch");
Douglas Gregord6350ae2009-08-28 20:31:08 +00001420
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001421 QualType Replacement = Arg.getAsType();
John McCall49a832b2009-10-18 09:09:24 +00001422
1423 // TODO: only do this uniquing once, at the start of instantiation.
John McCalla2becad2009-10-21 00:40:46 +00001424 QualType Result
1425 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1426 SubstTemplateTypeParmTypeLoc NewTL
1427 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1428 NewTL.setNameLoc(TL.getNameLoc());
1429 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001430 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001431
1432 // The template type parameter comes from an inner template (e.g.,
1433 // the template parameter list of a member template inside the
1434 // template we are instantiating). Create a new template type
1435 // parameter with the template "level" reduced by one.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001436 TemplateTypeParmDecl *NewTTPDecl = 0;
1437 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1438 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1439 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1440
John McCalla2becad2009-10-21 00:40:46 +00001441 QualType Result
1442 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1443 - TemplateArgs.getNumLevels(),
1444 T->getIndex(),
1445 T->isParameterPack(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001446 NewTTPDecl);
John McCalla2becad2009-10-21 00:40:46 +00001447 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1448 NewTL.setNameLoc(TL.getNameLoc());
1449 return Result;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001450}
Douglas Gregor99ebf652009-02-27 19:31:52 +00001451
Douglas Gregorc3069d62011-01-14 02:55:32 +00001452QualType
1453TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1454 TypeLocBuilder &TLB,
1455 SubstTemplateTypeParmPackTypeLoc TL) {
1456 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1457 // We aren't expanding the parameter pack, so just return ourselves.
1458 SubstTemplateTypeParmPackTypeLoc NewTL
1459 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1460 NewTL.setNameLoc(TL.getNameLoc());
1461 return TL.getType();
1462 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001463
1464 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1465 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1466 QualType Result = Arg.getAsType();
1467
Douglas Gregorc3069d62011-01-14 02:55:32 +00001468 Result = getSema().Context.getSubstTemplateTypeParmType(
1469 TL.getTypePtr()->getReplacedParameter(),
1470 Result);
1471 SubstTemplateTypeParmTypeLoc NewTL
1472 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1473 NewTL.setNameLoc(TL.getNameLoc());
1474 return Result;
1475}
1476
John McCallce3ff2b2009-08-25 22:02:44 +00001477/// \brief Perform substitution on the type T with a given set of template
1478/// arguments.
Douglas Gregor99ebf652009-02-27 19:31:52 +00001479///
1480/// This routine substitutes the given template arguments into the
1481/// type T and produces the instantiated type.
1482///
1483/// \param T the type into which the template arguments will be
1484/// substituted. If this type is not dependent, it will be returned
1485/// immediately.
1486///
James Dennett1dfbd922012-06-14 21:40:34 +00001487/// \param Args the template arguments that will be
Douglas Gregor99ebf652009-02-27 19:31:52 +00001488/// substituted for the top-level template parameters within T.
1489///
Douglas Gregor99ebf652009-02-27 19:31:52 +00001490/// \param Loc the location in the source code where this substitution
1491/// is being performed. It will typically be the location of the
1492/// declarator (if we're instantiating the type of some declaration)
1493/// or the location of the type in the source code (if, e.g., we're
1494/// instantiating the type of a cast expression).
1495///
1496/// \param Entity the name of the entity associated with a declaration
1497/// being instantiated (if any). May be empty to indicate that there
1498/// is no such entity (if, e.g., this is a type that occurs as part of
1499/// a cast expression) or that the entity has no name (e.g., an
1500/// unnamed function parameter).
1501///
1502/// \returns If the instantiation succeeds, the instantiated
1503/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCalla93c9342009-12-07 02:54:59 +00001504TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCallcd7ba1c2009-10-21 00:58:09 +00001505 const MultiLevelTemplateArgumentList &Args,
1506 SourceLocation Loc,
1507 DeclarationName Entity) {
1508 assert(!ActiveTemplateInstantiations.empty() &&
1509 "Cannot perform an instantiation without some context on the "
1510 "instantiation stack");
1511
Douglas Gregor561f8122011-07-01 01:22:09 +00001512 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor836adf62010-05-24 17:22:01 +00001513 !T->getType()->isVariablyModifiedType())
John McCallcd7ba1c2009-10-21 00:58:09 +00001514 return T;
1515
1516 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1517 return Instantiator.TransformType(T);
1518}
1519
Douglas Gregor603cfb42011-01-05 23:12:31 +00001520TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1521 const MultiLevelTemplateArgumentList &Args,
1522 SourceLocation Loc,
1523 DeclarationName Entity) {
1524 assert(!ActiveTemplateInstantiations.empty() &&
1525 "Cannot perform an instantiation without some context on the "
1526 "instantiation stack");
1527
1528 if (TL.getType().isNull())
1529 return 0;
1530
Douglas Gregor561f8122011-07-01 01:22:09 +00001531 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor603cfb42011-01-05 23:12:31 +00001532 !TL.getType()->isVariablyModifiedType()) {
1533 // FIXME: Make a copy of the TypeLoc data here, so that we can
1534 // return a new TypeSourceInfo. Inefficient!
1535 TypeLocBuilder TLB;
1536 TLB.pushFullCopy(TL);
1537 return TLB.getTypeSourceInfo(Context, TL.getType());
1538 }
1539
1540 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1541 TypeLocBuilder TLB;
1542 TLB.reserve(TL.getFullDataSize());
1543 QualType Result = Instantiator.TransformType(TLB, TL);
1544 if (Result.isNull())
1545 return 0;
1546
1547 return TLB.getTypeSourceInfo(Context, Result);
1548}
1549
John McCallcd7ba1c2009-10-21 00:58:09 +00001550/// Deprecated form of the above.
Mike Stump1eb44332009-09-09 15:08:12 +00001551QualType Sema::SubstType(QualType T,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001552 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallce3ff2b2009-08-25 22:02:44 +00001553 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregordf667e72009-03-10 20:44:00 +00001554 assert(!ActiveTemplateInstantiations.empty() &&
1555 "Cannot perform an instantiation without some context on the "
1556 "instantiation stack");
1557
Douglas Gregor836adf62010-05-24 17:22:01 +00001558 // If T is not a dependent type or a variably-modified type, there
1559 // is nothing to do.
Douglas Gregor561f8122011-07-01 01:22:09 +00001560 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregor99ebf652009-02-27 19:31:52 +00001561 return T;
1562
Douglas Gregor577f75a2009-08-04 16:50:30 +00001563 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1564 return Instantiator.TransformType(T);
Douglas Gregor99ebf652009-02-27 19:31:52 +00001565}
Douglas Gregor2943aed2009-03-03 04:44:36 +00001566
John McCall6cd3b9f2010-04-09 17:38:44 +00001567static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor561f8122011-07-01 01:22:09 +00001568 if (T->getType()->isInstantiationDependentType() ||
1569 T->getType()->isVariablyModifiedType())
John McCall6cd3b9f2010-04-09 17:38:44 +00001570 return true;
1571
Abramo Bagnara723df242010-12-14 22:11:44 +00001572 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00001573 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCall6cd3b9f2010-04-09 17:38:44 +00001574 return false;
1575
David Blaikie39e6ab42013-02-18 22:06:02 +00001576 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
John McCall6cd3b9f2010-04-09 17:38:44 +00001577 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1578 ParmVarDecl *P = FP.getArg(I);
1579
Reid Klecknerc66e7e92013-07-31 21:00:18 +00001580 // This must be synthesized from a typedef.
1581 if (!P) continue;
1582
Douglas Gregorc056c172011-05-09 20:45:16 +00001583 // The parameter's type as written might be dependent even if the
1584 // decayed type was not dependent.
1585 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
Douglas Gregor561f8122011-07-01 01:22:09 +00001586 if (TSInfo->getType()->isInstantiationDependentType())
Douglas Gregorc056c172011-05-09 20:45:16 +00001587 return true;
1588
John McCall6cd3b9f2010-04-09 17:38:44 +00001589 // TODO: currently we always rebuild expressions. When we
1590 // properly get lazier about this, we should use the same
1591 // logic to avoid rebuilding prototypes here.
Douglas Gregor7b1cf302011-01-05 21:14:17 +00001592 if (P->hasDefaultArg())
John McCall6cd3b9f2010-04-09 17:38:44 +00001593 return true;
1594 }
1595
1596 return false;
1597}
1598
1599/// A form of SubstType intended specifically for instantiating the
1600/// type of a FunctionDecl. Its purpose is solely to force the
1601/// instantiation of default-argument expressions.
1602TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1603 const MultiLevelTemplateArgumentList &Args,
1604 SourceLocation Loc,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001605 DeclarationName Entity,
1606 CXXRecordDecl *ThisContext,
1607 unsigned ThisTypeQuals) {
John McCall6cd3b9f2010-04-09 17:38:44 +00001608 assert(!ActiveTemplateInstantiations.empty() &&
1609 "Cannot perform an instantiation without some context on the "
1610 "instantiation stack");
1611
1612 if (!NeedsInstantiationAsFunctionType(T))
1613 return T;
1614
1615 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1616
1617 TypeLocBuilder TLB;
1618
1619 TypeLoc TL = T->getTypeLoc();
1620 TLB.reserve(TL.getFullDataSize());
1621
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001622 QualType Result;
David Blaikie39e6ab42013-02-18 22:06:02 +00001623
1624 if (FunctionProtoTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
1625 Result = Instantiator.TransformFunctionProtoType(TLB, Proto, ThisContext,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001626 ThisTypeQuals);
1627 } else {
1628 Result = Instantiator.TransformType(TLB, TL);
1629 }
John McCall6cd3b9f2010-04-09 17:38:44 +00001630 if (Result.isNull())
1631 return 0;
1632
1633 return TLB.getTypeSourceInfo(Context, Result);
1634}
1635
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001636ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001637 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallfb44de92011-05-01 22:35:37 +00001638 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001639 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001640 bool ExpectParameterPack) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001641 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Douglas Gregor603cfb42011-01-05 23:12:31 +00001642 TypeSourceInfo *NewDI = 0;
1643
Douglas Gregor603cfb42011-01-05 23:12:31 +00001644 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00001645 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1646
Douglas Gregor603cfb42011-01-05 23:12:31 +00001647 // We have a function parameter pack. Substitute into the pattern of the
1648 // expansion.
1649 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1650 OldParm->getLocation(), OldParm->getDeclName());
1651 if (!NewDI)
1652 return 0;
1653
1654 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1655 // We still have unexpanded parameter packs, which means that
1656 // our function parameter is still a function parameter pack.
1657 // Therefore, make its type a pack expansion type.
Douglas Gregorcded4f62011-01-14 17:04:44 +00001658 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001659 NumExpansions);
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001660 } else if (ExpectParameterPack) {
1661 // We expected to get a parameter pack but didn't (because the type
1662 // itself is not a pack expansion type), so complain. This can occur when
1663 // the substitution goes through an alias template that "loses" the
1664 // pack expansion.
1665 Diag(OldParm->getLocation(),
1666 diag::err_function_parameter_pack_without_parameter_packs)
1667 << NewDI->getType();
1668 return 0;
1669 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001670 } else {
1671 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1672 OldParm->getDeclName());
1673 }
1674
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001675 if (!NewDI)
1676 return 0;
1677
1678 if (NewDI->getType()->isVoidType()) {
1679 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1680 return 0;
1681 }
1682
1683 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001684 OldParm->getInnerLocStart(),
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001685 OldParm->getLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001686 OldParm->getIdentifier(),
1687 NewDI->getType(), NewDI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001688 OldParm->getStorageClass());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001689 if (!NewParm)
1690 return 0;
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001691
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001692 // Mark the (new) default argument as uninstantiated (if any).
1693 if (OldParm->hasUninstantiatedDefaultArg()) {
1694 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1695 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor8cfb7a32010-10-12 18:23:32 +00001696 } else if (OldParm->hasUnparsedDefaultArg()) {
1697 NewParm->setUnparsedDefaultArg();
1698 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
David Blaikie57296722012-05-01 06:05:57 +00001699 } else if (Expr *Arg = OldParm->getDefaultArg())
1700 // FIXME: if we non-lazily instantiated non-dependent default args for
1701 // non-dependent parameter types we could remove a bunch of duplicate
1702 // conversion warnings for such arguments.
1703 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001704
1705 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001706
Douglas Gregor12c9c002011-01-07 16:43:16 +00001707 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smithc0536c82012-01-25 02:14:59 +00001708 // Add the new parameter to the instantiated parameter pack.
Douglas Gregor12c9c002011-01-07 16:43:16 +00001709 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1710 } else {
1711 // Introduce an Old -> New mapping
Douglas Gregor603cfb42011-01-05 23:12:31 +00001712 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregor12c9c002011-01-07 16:43:16 +00001713 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001714
Argyrios Kyrtzidise3041be2010-07-19 10:14:41 +00001715 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1716 // can be anything, is this right ?
Fariborz Jahanian55a17c02010-07-13 21:05:02 +00001717 NewParm->setDeclContext(CurContext);
John McCallfb44de92011-05-01 22:35:37 +00001718
1719 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1720 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rose09189892013-03-08 22:25:36 +00001721
1722 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1723
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001724 return NewParm;
1725}
1726
Douglas Gregora009b592011-01-07 00:20:55 +00001727/// \brief Substitute the given template arguments into the given set of
1728/// parameters, producing the set of parameter types that would be generated
1729/// from such a substitution.
1730bool Sema::SubstParmTypes(SourceLocation Loc,
1731 ParmVarDecl **Params, unsigned NumParams,
1732 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001733 SmallVectorImpl<QualType> &ParamTypes,
1734 SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregora009b592011-01-07 00:20:55 +00001735 assert(!ActiveTemplateInstantiations.empty() &&
1736 "Cannot perform an instantiation without some context on the "
1737 "instantiation stack");
1738
1739 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1740 DeclarationName());
1741 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001742 ParamTypes, OutParams);
Douglas Gregora009b592011-01-07 00:20:55 +00001743}
1744
John McCallce3ff2b2009-08-25 22:02:44 +00001745/// \brief Perform substitution on the base class specifiers of the
1746/// given class template specialization.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001747///
1748/// Produces a diagnostic and returns true on error, returns false and
1749/// attaches the instantiated base classes to the class template
1750/// specialization if successful.
Mike Stump1eb44332009-09-09 15:08:12 +00001751bool
John McCallce3ff2b2009-08-25 22:02:44 +00001752Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1753 CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001754 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001755 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001756 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Mike Stump1eb44332009-09-09 15:08:12 +00001757 for (ClassTemplateSpecializationDecl::base_class_iterator
Douglas Gregord475b8d2009-03-25 21:17:03 +00001758 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
Douglas Gregor27b152f2009-03-10 18:52:44 +00001759 Base != BaseEnd; ++Base) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001760 if (!Base->getType()->isDependentType()) {
Matt Beaumont-Gay538fccb2013-06-21 18:58:32 +00001761 if (const CXXRecordDecl *RD = Base->getType()->getAsCXXRecordDecl()) {
1762 if (RD->isInvalidDecl())
1763 Instantiation->setInvalidDecl();
1764 }
Fariborz Jahanian71c6e712009-07-22 17:41:53 +00001765 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
Douglas Gregor2943aed2009-03-03 04:44:36 +00001766 continue;
1767 }
1768
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001769 SourceLocation EllipsisLoc;
Douglas Gregor406f98f2011-03-02 02:04:06 +00001770 TypeSourceInfo *BaseTypeLoc;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001771 if (Base->isPackExpansion()) {
1772 // This is a pack expansion. See whether we should expand it now, or
1773 // wait until later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001774 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001775 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1776 Unexpanded);
1777 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00001778 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001779 Optional<unsigned> NumExpansions;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001780 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1781 Base->getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001782 Unexpanded,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001783 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00001784 RetainExpansion,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001785 NumExpansions)) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001786 Invalid = true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001787 continue;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001788 }
1789
1790 // If we should expand this pack expansion now, do so.
1791 if (ShouldExpand) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00001792 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001793 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1794
1795 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1796 TemplateArgs,
1797 Base->getSourceRange().getBegin(),
1798 DeclarationName());
1799 if (!BaseTypeLoc) {
1800 Invalid = true;
1801 continue;
1802 }
1803
1804 if (CXXBaseSpecifier *InstantiatedBase
1805 = CheckBaseSpecifier(Instantiation,
1806 Base->getSourceRange(),
1807 Base->isVirtual(),
1808 Base->getAccessSpecifierAsWritten(),
1809 BaseTypeLoc,
1810 SourceLocation()))
1811 InstantiatedBases.push_back(InstantiatedBase);
1812 else
1813 Invalid = true;
1814 }
1815
1816 continue;
1817 }
1818
1819 // The resulting base specifier will (still) be a pack expansion.
1820 EllipsisLoc = Base->getEllipsisLoc();
Douglas Gregor406f98f2011-03-02 02:04:06 +00001821 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1822 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1823 TemplateArgs,
1824 Base->getSourceRange().getBegin(),
1825 DeclarationName());
1826 } else {
1827 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1828 TemplateArgs,
1829 Base->getSourceRange().getBegin(),
1830 DeclarationName());
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001831 }
1832
Nick Lewycky56062202010-07-26 16:56:01 +00001833 if (!BaseTypeLoc) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001834 Invalid = true;
1835 continue;
1836 }
1837
1838 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregord475b8d2009-03-25 21:17:03 +00001839 = CheckBaseSpecifier(Instantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001840 Base->getSourceRange(),
1841 Base->isVirtual(),
1842 Base->getAccessSpecifierAsWritten(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001843 BaseTypeLoc,
1844 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001845 InstantiatedBases.push_back(InstantiatedBase);
1846 else
1847 Invalid = true;
1848 }
1849
Douglas Gregor27b152f2009-03-10 18:52:44 +00001850 if (!Invalid &&
Jay Foadbeaaccd2009-05-21 09:52:38 +00001851 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001852 InstantiatedBases.size()))
1853 Invalid = true;
1854
1855 return Invalid;
1856}
1857
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001858// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramer5bbc3852012-02-06 11:13:08 +00001859namespace clang {
1860 namespace sema {
1861 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1862 const MultiLevelTemplateArgumentList &TemplateArgs);
1863 }
1864}
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001865
Richard Smithf1c66b42012-03-14 23:13:10 +00001866/// Determine whether we would be unable to instantiate this template (because
1867/// it either has no definition, or is in the process of being instantiated).
1868static bool DiagnoseUninstantiableTemplate(Sema &S,
1869 SourceLocation PointOfInstantiation,
1870 TagDecl *Instantiation,
1871 bool InstantiatedFromMember,
1872 TagDecl *Pattern,
1873 TagDecl *PatternDef,
1874 TemplateSpecializationKind TSK,
1875 bool Complain = true) {
1876 if (PatternDef && !PatternDef->isBeingDefined())
1877 return false;
1878
1879 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1880 // Say nothing
1881 } else if (PatternDef) {
1882 assert(PatternDef->isBeingDefined());
1883 S.Diag(PointOfInstantiation,
1884 diag::err_template_instantiate_within_definition)
1885 << (TSK != TSK_ImplicitInstantiation)
1886 << S.Context.getTypeDeclType(Instantiation);
1887 // Not much point in noting the template declaration here, since
1888 // we're lexically inside it.
1889 Instantiation->setInvalidDecl();
1890 } else if (InstantiatedFromMember) {
1891 S.Diag(PointOfInstantiation,
1892 diag::err_implicit_instantiate_member_undefined)
1893 << S.Context.getTypeDeclType(Instantiation);
1894 S.Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1895 } else {
1896 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1897 << (TSK != TSK_ImplicitInstantiation)
1898 << S.Context.getTypeDeclType(Instantiation);
1899 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1900 }
1901
1902 // In general, Instantiation isn't marked invalid to get more than one
1903 // error for multiple undefined instantiations. But the code that does
1904 // explicit declaration -> explicit definition conversion can't handle
1905 // invalid declarations, so mark as invalid in that case.
1906 if (TSK == TSK_ExplicitInstantiationDeclaration)
1907 Instantiation->setInvalidDecl();
1908 return true;
1909}
1910
Douglas Gregord475b8d2009-03-25 21:17:03 +00001911/// \brief Instantiate the definition of a class from a given pattern.
1912///
1913/// \param PointOfInstantiation The point of instantiation within the
1914/// source code.
1915///
1916/// \param Instantiation is the declaration whose definition is being
1917/// instantiated. This will be either a class template specialization
1918/// or a member class of a class template specialization.
1919///
1920/// \param Pattern is the pattern from which the instantiation
1921/// occurs. This will be either the declaration of a class template or
1922/// the declaration of a member class of a class template.
1923///
1924/// \param TemplateArgs The template arguments to be substituted into
1925/// the pattern.
1926///
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001927/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor5842ba92009-08-24 15:23:48 +00001928///
1929/// \param Complain whether to complain if the class cannot be instantiated due
1930/// to the lack of a definition.
1931///
Douglas Gregord475b8d2009-03-25 21:17:03 +00001932/// \returns true if an error occurred, false otherwise.
1933bool
1934Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1935 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001936 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001937 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00001938 bool Complain) {
Mike Stump1eb44332009-09-09 15:08:12 +00001939 CXXRecordDecl *PatternDef
Douglas Gregor952b0172010-02-11 01:04:33 +00001940 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Richard Smithf1c66b42012-03-14 23:13:10 +00001941 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1942 Instantiation->getInstantiatedFromMemberClass(),
1943 Pattern, PatternDef, TSK, Complain))
Douglas Gregord475b8d2009-03-25 21:17:03 +00001944 return true;
Douglas Gregord475b8d2009-03-25 21:17:03 +00001945 Pattern = PatternDef;
1946
Douglas Gregor454885e2009-10-15 15:54:05 +00001947 // \brief Record the point of instantiation.
1948 if (MemberSpecializationInfo *MSInfo
1949 = Instantiation->getMemberSpecializationInfo()) {
1950 MSInfo->setTemplateSpecializationKind(TSK);
1951 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001952 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weberc7feca02011-12-20 20:32:49 +00001953 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001954 Spec->setTemplateSpecializationKind(TSK);
1955 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00001956 }
1957
Douglas Gregord048bb72009-03-25 21:23:52 +00001958 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001959 if (Inst)
1960 return true;
1961
1962 // Enter the scope of this instantiation. We don't use
1963 // PushDeclContext because we don't have a scope.
John McCallf5813822010-04-29 00:35:03 +00001964 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor9679caf2010-05-12 17:27:19 +00001965 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00001966 Sema::PotentiallyEvaluated);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001967
Douglas Gregor05030bb2010-03-24 01:33:17 +00001968 // If this is an instantiation of a local class, merge this local
1969 // instantiation scope with the enclosing scope. Otherwise, every
1970 // instantiation of a class has its own local instantiation scope.
1971 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall2a7fb272010-08-25 05:32:35 +00001972 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor05030bb2010-03-24 01:33:17 +00001973
John McCall1d8d1cc2010-08-01 02:01:53 +00001974 // Pull attributes from the pattern onto the instantiation.
1975 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1976
Douglas Gregord475b8d2009-03-25 21:17:03 +00001977 // Start the definition of this instantiation.
1978 Instantiation->startDefinition();
Douglas Gregor13c85772010-05-06 00:28:52 +00001979
1980 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001981
John McCallce3ff2b2009-08-25 22:02:44 +00001982 // Do substitution on the base class specifiers.
1983 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001984 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00001985
Douglas Gregord65587f2010-11-10 19:44:59 +00001986 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001987 SmallVector<Decl*, 4> Fields;
1988 SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
Richard Smith7a614d82011-06-11 17:19:42 +00001989 FieldsWithMemberInitializers;
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001990 // Delay instantiation of late parsed attributes.
1991 LateInstantiatedAttrVec LateAttrs;
1992 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1993
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001994 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001995 MemberEnd = Pattern->decls_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001996 Member != MemberEnd; ++Member) {
Argyrios Kyrtzidisbb5e4312010-11-04 03:18:57 +00001997 // Don't instantiate members not belonging in this semantic context.
1998 // e.g. for:
1999 // @code
2000 // template <int i> class A {
2001 // class B *g;
2002 // };
2003 // @endcode
2004 // 'class B' has the template as lexical context but semantically it is
2005 // introduced in namespace scope.
2006 if ((*Member)->getDeclContext() != Pattern)
2007 continue;
2008
Douglas Gregord65587f2010-11-10 19:44:59 +00002009 if ((*Member)->isInvalidDecl()) {
Richard Smithe3f470a2012-07-11 22:37:56 +00002010 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00002011 continue;
2012 }
2013
2014 Decl *NewMember = Instantiator.Visit(*Member);
Douglas Gregord475b8d2009-03-25 21:17:03 +00002015 if (NewMember) {
Richard Smith7a614d82011-06-11 17:19:42 +00002016 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCalld226f652010-08-21 09:40:31 +00002017 Fields.push_back(Field);
Richard Smith7a614d82011-06-11 17:19:42 +00002018 FieldDecl *OldField = cast<FieldDecl>(*Member);
2019 if (OldField->getInClassInitializer())
2020 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
2021 Field));
Richard Smith1af83c42012-03-23 03:33:32 +00002022 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2023 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2024 // specialization causes the implicit instantiation of the definitions
2025 // of unscoped member enumerations.
2026 // Record a point of instantiation for this implicit instantiation.
Richard Smith3343fad2012-03-23 23:09:08 +00002027 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2028 Enum->isCompleteDefinition()) {
Richard Smith1af83c42012-03-23 03:33:32 +00002029 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2030 assert(MSInfo && "no spec info for member enum specialization");
2031 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2032 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2033 }
Richard Smithe3f470a2012-07-11 22:37:56 +00002034 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2035 if (SA->isFailed()) {
2036 // A static_assert failed. Bail out; instantiating this
2037 // class is probably not meaningful.
2038 Instantiation->setInvalidDecl();
2039 break;
2040 }
Richard Smith1af83c42012-03-23 03:33:32 +00002041 }
2042
2043 if (NewMember->isInvalidDecl())
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002044 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002045 } else {
2046 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002047 // instantiations was a semantic disaster, and we'll want to mark the
2048 // declaration invalid.
2049 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregord475b8d2009-03-25 21:17:03 +00002050 }
2051 }
2052
2053 // Finish checking fields.
David Blaikie77b6de02011-09-22 02:58:26 +00002054 ActOnFields(0, Instantiation->getLocation(), Instantiation, Fields,
2055 SourceLocation(), SourceLocation(), 0);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002056 CheckCompletedCXXClass(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002057
2058 // Attach any in-class member initializers now the class is complete.
Richard Smithd5be2b52012-12-08 02:13:02 +00002059 // FIXME: We are supposed to defer instantiating these until they are needed.
Benjamin Kramer268efba2012-05-17 12:01:52 +00002060 if (!FieldsWithMemberInitializers.empty()) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002061 // C++11 [expr.prim.general]p4:
2062 // Otherwise, if a member-declarator declares a non-static data member
2063 // (9.2) of a class X, the expression this is a prvalue of type "pointer
2064 // to X" within the optional brace-or-equal-initializer. It shall not
2065 // appear elsewhere in the member-declarator.
2066 CXXThisScopeRAII ThisScope(*this, Instantiation, (unsigned)0);
2067
2068 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
2069 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
2070 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
2071 Expr *OldInit = OldField->getInClassInitializer();
Richard Smith7a614d82011-06-11 17:19:42 +00002072
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002073 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2074 /*CXXDirectInit=*/false);
2075 if (NewInit.isInvalid())
2076 NewField->setInvalidDecl();
2077 else {
2078 Expr *Init = NewInit.take();
2079 assert(Init && "no-argument initializer in class");
2080 assert(!isa<ParenListExpr>(Init) && "call-style init in class");
Richard Smithca523302012-06-10 03:12:00 +00002081 ActOnCXXInClassMemberInitializer(NewField, Init->getLocStart(), Init);
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002082 }
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002083 }
Richard Smith7a614d82011-06-11 17:19:42 +00002084 }
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002085 // Instantiate late parsed attributes, and attach them to their decls.
2086 // See Sema::InstantiateAttrs
2087 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2088 E = LateAttrs.end(); I != E; ++I) {
2089 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2090 CurrentInstantiationScope = I->Scope;
Richard Smithcafeb942013-06-07 02:33:37 +00002091
2092 // Allow 'this' within late-parsed attributes.
2093 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2094 CXXRecordDecl *ThisContext =
2095 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2096 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2097 ND && ND->isCXXInstanceMember());
2098
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002099 Attr *NewAttr =
2100 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2101 I->NewDecl->addAttr(NewAttr);
2102 LocalInstantiationScope::deleteScopes(I->Scope,
2103 Instantiator.getStartingScope());
2104 }
2105 Instantiator.disableLateAttributeInstantiation();
2106 LateAttrs.clear();
2107
Richard Smithb9d0b762012-07-27 04:22:15 +00002108 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002109
Abramo Bagnarae9946242011-11-18 08:08:52 +00002110 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis734bd6e2012-02-11 01:59:57 +00002111 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002112 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnara09d82122011-10-03 20:34:03 +00002113 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002114 }
Abramo Bagnara09d82122011-10-03 20:34:03 +00002115
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002116 if (!Instantiation->isInvalidDecl()) {
John McCall1f2e1a92012-08-10 03:15:35 +00002117 // Perform any dependent diagnostics from the pattern.
2118 PerformDependentDiagnostics(Pattern, TemplateArgs);
2119
Douglas Gregord65587f2010-11-10 19:44:59 +00002120 // Instantiate any out-of-line class template partial
2121 // specializations now.
2122 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2123 P = Instantiator.delayed_partial_spec_begin(),
2124 PEnd = Instantiator.delayed_partial_spec_end();
2125 P != PEnd; ++P) {
2126 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2127 P->first,
2128 P->second)) {
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002129 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00002130 break;
2131 }
2132 }
2133 }
2134
Douglas Gregord475b8d2009-03-25 21:17:03 +00002135 // Exit the scope of this instantiation.
John McCallf5813822010-04-29 00:35:03 +00002136 SavedContext.pop();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002137
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002138 if (!Instantiation->isInvalidDecl()) {
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002139 Consumer.HandleTagDeclDefinition(Instantiation);
2140
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002141 // Always emit the vtable for an explicit instantiation definition
2142 // of a polymorphic class template specialization.
2143 if (TSK == TSK_ExplicitInstantiationDefinition)
2144 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2145 }
2146
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002147 return Instantiation->isInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002148}
2149
Richard Smithf1c66b42012-03-14 23:13:10 +00002150/// \brief Instantiate the definition of an enum from a given pattern.
2151///
2152/// \param PointOfInstantiation The point of instantiation within the
2153/// source code.
2154/// \param Instantiation is the declaration whose definition is being
2155/// instantiated. This will be a member enumeration of a class
2156/// temploid specialization, or a local enumeration within a
2157/// function temploid specialization.
2158/// \param Pattern The templated declaration from which the instantiation
2159/// occurs.
2160/// \param TemplateArgs The template arguments to be substituted into
2161/// the pattern.
2162/// \param TSK The kind of implicit or explicit instantiation to perform.
2163///
2164/// \return \c true if an error occurred, \c false otherwise.
2165bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2166 EnumDecl *Instantiation, EnumDecl *Pattern,
2167 const MultiLevelTemplateArgumentList &TemplateArgs,
2168 TemplateSpecializationKind TSK) {
2169 EnumDecl *PatternDef = Pattern->getDefinition();
2170 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2171 Instantiation->getInstantiatedFromMemberEnum(),
2172 Pattern, PatternDef, TSK,/*Complain*/true))
2173 return true;
2174 Pattern = PatternDef;
2175
2176 // Record the point of instantiation.
2177 if (MemberSpecializationInfo *MSInfo
2178 = Instantiation->getMemberSpecializationInfo()) {
2179 MSInfo->setTemplateSpecializationKind(TSK);
2180 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2181 }
2182
2183 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2184 if (Inst)
2185 return true;
2186
2187 // Enter the scope of this instantiation. We don't use
2188 // PushDeclContext because we don't have a scope.
2189 ContextRAII SavedContext(*this, Instantiation);
2190 EnterExpressionEvaluationContext EvalContext(*this,
2191 Sema::PotentiallyEvaluated);
2192
2193 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2194
2195 // Pull attributes from the pattern onto the instantiation.
2196 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2197
2198 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2199 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2200
2201 // Exit the scope of this instantiation.
2202 SavedContext.pop();
2203
2204 return Instantiation->isInvalidDecl();
2205}
2206
Douglas Gregor9b623632010-10-12 23:32:35 +00002207namespace {
2208 /// \brief A partial specialization whose template arguments have matched
2209 /// a given template-id.
2210 struct PartialSpecMatchResult {
2211 ClassTemplatePartialSpecializationDecl *Partial;
2212 TemplateArgumentList *Args;
Douglas Gregor9b623632010-10-12 23:32:35 +00002213 };
2214}
2215
Mike Stump1eb44332009-09-09 15:08:12 +00002216bool
Douglas Gregor2943aed2009-03-03 04:44:36 +00002217Sema::InstantiateClassTemplateSpecialization(
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002218 SourceLocation PointOfInstantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00002219 ClassTemplateSpecializationDecl *ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002220 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002221 bool Complain) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00002222 // Perform the actual instantiation on the canonical declaration.
2223 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002224 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor2943aed2009-03-03 04:44:36 +00002225
Douglas Gregor52604ab2009-09-11 21:19:12 +00002226 // Check whether we have already instantiated or specialized this class
2227 // template specialization.
2228 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2229 if (ClassTemplateSpec->getSpecializationKind() ==
2230 TSK_ExplicitInstantiationDeclaration &&
2231 TSK == TSK_ExplicitInstantiationDefinition) {
2232 // An explicit instantiation definition follows an explicit instantiation
2233 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2234 // explicit instantiation.
2235 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002236
2237 // If this is an explicit instantiation definition, mark the
2238 // vtable as used.
Nico Weberc7feca02011-12-20 20:32:49 +00002239 if (TSK == TSK_ExplicitInstantiationDefinition &&
2240 !ClassTemplateSpec->isInvalidDecl())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002241 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2242
Douglas Gregor52604ab2009-09-11 21:19:12 +00002243 return false;
2244 }
2245
2246 // We can only instantiate something that hasn't already been
2247 // instantiated or specialized. Fail without any diagnostics: our
2248 // caller will provide an error message.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002249 return true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00002250 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002251
Douglas Gregor9eea08b2009-09-15 16:51:42 +00002252 if (ClassTemplateSpec->isInvalidDecl())
2253 return true;
2254
Douglas Gregor2943aed2009-03-03 04:44:36 +00002255 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregord6350ae2009-08-28 20:31:08 +00002256 CXXRecordDecl *Pattern = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002257
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002258 // C++ [temp.class.spec.match]p1:
2259 // When a class template is used in a context that requires an
2260 // instantiation of the class, it is necessary to determine
2261 // whether the instantiation is to be generated using the primary
2262 // template or one of the partial specializations. This is done by
2263 // matching the template arguments of the class template
2264 // specialization with the template argument lists of the partial
2265 // specializations.
Douglas Gregor9b623632010-10-12 23:32:35 +00002266 typedef PartialSpecMatchResult MatchResult;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002267 SmallVector<MatchResult, 4> Matched;
2268 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002269 Template->getPartialSpecializations(PartialSpecs);
Larisse Voufo43847122013-07-19 23:00:19 +00002270 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002271 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2272 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo43847122013-07-19 23:00:19 +00002273 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorf67875d2009-06-12 18:26:56 +00002274 if (TemplateDeductionResult Result
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002275 = DeduceTemplateArguments(Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00002276 ClassTemplateSpec->getTemplateArgs(),
2277 Info)) {
Larisse Voufo43847122013-07-19 23:00:19 +00002278 // Store the failed-deduction information for use in diagnostics, later.
2279 // TODO: Actually use the failed-deduction info?
2280 FailedCandidates.addCandidate()
2281 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorf67875d2009-06-12 18:26:56 +00002282 (void)Result;
2283 } else {
Douglas Gregor9b623632010-10-12 23:32:35 +00002284 Matched.push_back(PartialSpecMatchResult());
2285 Matched.back().Partial = Partial;
2286 Matched.back().Args = Info.take();
Douglas Gregorf67875d2009-06-12 18:26:56 +00002287 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002288 }
2289
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002290 // If we're dealing with a member template where the template parameters
2291 // have been instantiated, this provides the original template parameters
2292 // from which the member template's parameters were instantiated.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002293 SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002294
Douglas Gregored9c0f92009-10-29 00:04:11 +00002295 if (Matched.size() >= 1) {
Craig Topper09d19ef2013-07-04 03:08:24 +00002296 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002297 if (Matched.size() == 1) {
2298 // -- If exactly one matching specialization is found, the
2299 // instantiation is generated from that specialization.
2300 // We don't need to do anything for this.
2301 } else {
2302 // -- If more than one matching specialization is found, the
2303 // partial order rules (14.5.4.2) are used to determine
2304 // whether one of the specializations is more specialized
2305 // than the others. If none of the specializations is more
2306 // specialized than all of the other matching
2307 // specializations, then the use of the class template is
2308 // ambiguous and the program is ill-formed.
Craig Topper09d19ef2013-07-04 03:08:24 +00002309 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2310 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002311 P != PEnd; ++P) {
Douglas Gregor9b623632010-10-12 23:32:35 +00002312 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002313 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002314 == P->Partial)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002315 Best = P;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002316 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002317
Douglas Gregored9c0f92009-10-29 00:04:11 +00002318 // Determine if the best partial specialization is more specialized than
2319 // the others.
2320 bool Ambiguous = false;
Craig Topper09d19ef2013-07-04 03:08:24 +00002321 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2322 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002323 P != PEnd; ++P) {
2324 if (P != Best &&
Douglas Gregor9b623632010-10-12 23:32:35 +00002325 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002326 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002327 != Best->Partial) {
Douglas Gregored9c0f92009-10-29 00:04:11 +00002328 Ambiguous = true;
2329 break;
2330 }
2331 }
2332
2333 if (Ambiguous) {
2334 // Partial ordering did not produce a clear winner. Complain.
2335 ClassTemplateSpec->setInvalidDecl();
2336 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2337 << ClassTemplateSpec;
2338
2339 // Print the matching partial specializations.
Craig Topper09d19ef2013-07-04 03:08:24 +00002340 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2341 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002342 P != PEnd; ++P)
Douglas Gregor9b623632010-10-12 23:32:35 +00002343 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2344 << getTemplateArgumentBindingsText(
2345 P->Partial->getTemplateParameters(),
2346 *P->Args);
Douglas Gregord6350ae2009-08-28 20:31:08 +00002347
Douglas Gregored9c0f92009-10-29 00:04:11 +00002348 return true;
2349 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002350 }
2351
2352 // Instantiate using the best class template partial specialization.
Douglas Gregor9b623632010-10-12 23:32:35 +00002353 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002354 while (OrigPartialSpec->getInstantiatedFromMember()) {
2355 // If we've found an explicit specialization of this class template,
2356 // stop here and use that as the pattern.
2357 if (OrigPartialSpec->isMemberSpecialization())
2358 break;
2359
2360 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2361 }
2362
2363 Pattern = OrigPartialSpec;
Douglas Gregor9b623632010-10-12 23:32:35 +00002364 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002365 } else {
2366 // -- If no matches are found, the instantiation is generated
2367 // from the primary template.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002368 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002369 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2370 // If we've found an explicit specialization of this class template,
2371 // stop here and use that as the pattern.
2372 if (OrigTemplate->isMemberSpecialization())
2373 break;
2374
Douglas Gregord6350ae2009-08-28 20:31:08 +00002375 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002376 }
2377
Douglas Gregord6350ae2009-08-28 20:31:08 +00002378 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002379 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002380
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002381 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2382 Pattern,
2383 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002384 TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002385 Complain);
Mike Stump1eb44332009-09-09 15:08:12 +00002386
Douglas Gregor199d9912009-06-05 00:53:49 +00002387 return Result;
Douglas Gregor2943aed2009-03-03 04:44:36 +00002388}
Douglas Gregor5953d8b2009-03-19 17:26:29 +00002389
John McCallce3ff2b2009-08-25 22:02:44 +00002390/// \brief Instantiates the definitions of all of the member
2391/// of the given class, which is an instantiation of a class template
2392/// or a member class of a template.
Douglas Gregora58861f2009-05-13 20:28:22 +00002393void
2394Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002395 CXXRecordDecl *Instantiation,
2396 const MultiLevelTemplateArgumentList &TemplateArgs,
2397 TemplateSpecializationKind TSK) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002398 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
2399 DEnd = Instantiation->decls_end();
Douglas Gregora58861f2009-05-13 20:28:22 +00002400 D != DEnd; ++D) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002401 bool SuppressNew = false;
Douglas Gregora58861f2009-05-13 20:28:22 +00002402 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002403 if (FunctionDecl *Pattern
2404 = Function->getInstantiatedFromMemberFunction()) {
2405 MemberSpecializationInfo *MSInfo
2406 = Function->getMemberSpecializationInfo();
2407 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002408 if (MSInfo->getTemplateSpecializationKind()
2409 == TSK_ExplicitSpecialization)
2410 continue;
2411
Douglas Gregor0d035142009-10-27 18:42:08 +00002412 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2413 Function,
2414 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002415 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002416 SuppressNew) ||
2417 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002418 continue;
2419
Sean Hunt10620eb2011-05-06 20:44:56 +00002420 if (Function->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002421 continue;
2422
2423 if (TSK == TSK_ExplicitInstantiationDefinition) {
2424 // C++0x [temp.explicit]p8:
2425 // An explicit instantiation definition that names a class template
2426 // specialization explicitly instantiates the class template
2427 // specialization and is only an explicit instantiation definition
2428 // of members whose definition is visible at the point of
2429 // instantiation.
Sean Hunt10620eb2011-05-06 20:44:56 +00002430 if (!Pattern->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002431 continue;
2432
2433 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2434
2435 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2436 } else {
2437 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2438 }
Douglas Gregorf6b11852009-10-08 15:14:33 +00002439 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002440 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002441 if (Var->isStaticDataMember()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002442 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2443 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002444 if (MSInfo->getTemplateSpecializationKind()
2445 == TSK_ExplicitSpecialization)
2446 continue;
2447
Douglas Gregor0d035142009-10-27 18:42:08 +00002448 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2449 Var,
2450 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002451 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002452 SuppressNew) ||
2453 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002454 continue;
2455
Douglas Gregor0d035142009-10-27 18:42:08 +00002456 if (TSK == TSK_ExplicitInstantiationDefinition) {
2457 // C++0x [temp.explicit]p8:
2458 // An explicit instantiation definition that names a class template
2459 // specialization explicitly instantiates the class template
2460 // specialization and is only an explicit instantiation definition
2461 // of members whose definition is visible at the point of
2462 // instantiation.
2463 if (!Var->getInstantiatedFromStaticDataMember()
2464 ->getOutOfLineDefinition())
2465 continue;
2466
2467 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002468 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor0d035142009-10-27 18:42:08 +00002469 } else {
2470 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2471 }
2472 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002473 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
Douglas Gregora77eaa92010-04-18 18:11:38 +00002474 // Always skip the injected-class-name, along with any
2475 // redeclarations of nested classes, since both would cause us
2476 // to try to instantiate the members of a class twice.
Douglas Gregoref96ee02012-01-14 16:38:05 +00002477 if (Record->isInjectedClassName() || Record->getPreviousDecl())
Douglas Gregor2db32322009-10-07 23:56:10 +00002478 continue;
2479
Douglas Gregor0d035142009-10-27 18:42:08 +00002480 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2481 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002482
2483 if (MSInfo->getTemplateSpecializationKind()
2484 == TSK_ExplicitSpecialization)
2485 continue;
Nico Weberc956b6e2010-09-27 21:02:09 +00002486
Douglas Gregor0d035142009-10-27 18:42:08 +00002487 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2488 Record,
2489 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002490 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002491 SuppressNew) ||
2492 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002493 continue;
2494
Douglas Gregor0d035142009-10-27 18:42:08 +00002495 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2496 assert(Pattern && "Missing instantiated-from-template information");
2497
Douglas Gregor952b0172010-02-11 01:04:33 +00002498 if (!Record->getDefinition()) {
2499 if (!Pattern->getDefinition()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002500 // C++0x [temp.explicit]p8:
2501 // An explicit instantiation definition that names a class template
2502 // specialization explicitly instantiates the class template
2503 // specialization and is only an explicit instantiation definition
2504 // of members whose definition is visible at the point of
2505 // instantiation.
2506 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2507 MSInfo->setTemplateSpecializationKind(TSK);
2508 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2509 }
2510
2511 continue;
2512 }
2513
2514 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002515 TemplateArgs,
2516 TSK);
Nico Weberc956b6e2010-09-27 21:02:09 +00002517 } else {
2518 if (TSK == TSK_ExplicitInstantiationDefinition &&
2519 Record->getTemplateSpecializationKind() ==
2520 TSK_ExplicitInstantiationDeclaration) {
2521 Record->setTemplateSpecializationKind(TSK);
2522 MarkVTableUsed(PointOfInstantiation, Record, true);
2523 }
Douglas Gregor0d035142009-10-27 18:42:08 +00002524 }
Douglas Gregore9374d52009-10-08 01:19:17 +00002525
Douglas Gregor952b0172010-02-11 01:04:33 +00002526 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00002527 if (Pattern)
2528 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2529 TSK);
Richard Smithf1c66b42012-03-14 23:13:10 +00002530 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(*D)) {
2531 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2532 assert(MSInfo && "No member specialization information?");
2533
2534 if (MSInfo->getTemplateSpecializationKind()
2535 == TSK_ExplicitSpecialization)
2536 continue;
2537
2538 if (CheckSpecializationInstantiationRedecl(
2539 PointOfInstantiation, TSK, Enum,
2540 MSInfo->getTemplateSpecializationKind(),
2541 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2542 SuppressNew)
2543 continue;
2544
2545 if (Enum->getDefinition())
2546 continue;
2547
2548 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2549 assert(Pattern && "Missing instantiated-from-template information");
2550
2551 if (TSK == TSK_ExplicitInstantiationDefinition) {
2552 if (!Pattern->getDefinition())
2553 continue;
2554
2555 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2556 } else {
2557 MSInfo->setTemplateSpecializationKind(TSK);
2558 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2559 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002560 }
2561 }
2562}
2563
2564/// \brief Instantiate the definitions of all of the members of the
2565/// given class template specialization, which was named as part of an
2566/// explicit instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +00002567void
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002568Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregora58861f2009-05-13 20:28:22 +00002569 SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002570 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2571 TemplateSpecializationKind TSK) {
Douglas Gregora58861f2009-05-13 20:28:22 +00002572 // C++0x [temp.explicit]p7:
2573 // An explicit instantiation that names a class template
2574 // specialization is an explicit instantion of the same kind
2575 // (declaration or definition) of each of its members (not
2576 // including members inherited from base classes) that has not
2577 // been previously explicitly specialized in the translation unit
2578 // containing the explicit instantiation, except as described
2579 // below.
2580 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002581 getTemplateInstantiationArgs(ClassTemplateSpec),
2582 TSK);
Douglas Gregora58861f2009-05-13 20:28:22 +00002583}
2584
John McCall60d7b3a2010-08-24 06:29:42 +00002585StmtResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002586Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor43959a92009-08-20 07:17:43 +00002587 if (!S)
2588 return Owned(S);
2589
2590 TemplateInstantiator Instantiator(*this, TemplateArgs,
2591 SourceLocation(),
2592 DeclarationName());
2593 return Instantiator.TransformStmt(S);
2594}
2595
John McCall60d7b3a2010-08-24 06:29:42 +00002596ExprResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002597Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorb98b1992009-08-11 05:31:07 +00002598 if (!E)
2599 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002600
Douglas Gregorb98b1992009-08-11 05:31:07 +00002601 TemplateInstantiator Instantiator(*this, TemplateArgs,
2602 SourceLocation(),
2603 DeclarationName());
2604 return Instantiator.TransformExpr(E);
2605}
2606
Richard Smithc83c2302012-12-19 01:39:02 +00002607ExprResult Sema::SubstInitializer(Expr *Init,
2608 const MultiLevelTemplateArgumentList &TemplateArgs,
2609 bool CXXDirectInit) {
2610 TemplateInstantiator Instantiator(*this, TemplateArgs,
2611 SourceLocation(),
2612 DeclarationName());
2613 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2614}
2615
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002616bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2617 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002618 SmallVectorImpl<Expr *> &Outputs) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002619 if (NumExprs == 0)
2620 return false;
Richard Smithc83c2302012-12-19 01:39:02 +00002621
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002622 TemplateInstantiator Instantiator(*this, TemplateArgs,
2623 SourceLocation(),
2624 DeclarationName());
2625 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2626}
2627
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002628NestedNameSpecifierLoc
2629Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2630 const MultiLevelTemplateArgumentList &TemplateArgs) {
2631 if (!NNS)
2632 return NestedNameSpecifierLoc();
2633
2634 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2635 DeclarationName());
2636 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2637}
2638
Abramo Bagnara25777432010-08-11 22:01:17 +00002639/// \brief Do template substitution on declaration name info.
2640DeclarationNameInfo
2641Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2642 const MultiLevelTemplateArgumentList &TemplateArgs) {
2643 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2644 NameInfo.getName());
2645 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2646}
2647
Douglas Gregorde650ae2009-03-31 18:38:02 +00002648TemplateName
Douglas Gregor1d752d72011-03-02 18:46:51 +00002649Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2650 TemplateName Name, SourceLocation Loc,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002651 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord1067e52009-08-06 06:41:21 +00002652 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2653 DeclarationName());
Douglas Gregor1d752d72011-03-02 18:46:51 +00002654 CXXScopeSpec SS;
2655 SS.Adopt(QualifierLoc);
2656 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregorde650ae2009-03-31 18:38:02 +00002657}
Douglas Gregor91333002009-06-11 00:06:24 +00002658
Douglas Gregore02e2622010-12-22 21:19:48 +00002659bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2660 TemplateArgumentListInfo &Result,
John McCall833ca992009-10-29 08:12:44 +00002661 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor670444e2009-08-04 22:27:00 +00002662 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2663 DeclarationName());
Douglas Gregore02e2622010-12-22 21:19:48 +00002664
2665 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregor91333002009-06-11 00:06:24 +00002666}
Douglas Gregor895162d2010-04-30 18:55:50 +00002667
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002668
2669static const Decl* getCanonicalParmVarDecl(const Decl *D) {
2670 // When storing ParmVarDecls in the local instantiation scope, we always
2671 // want to use the ParmVarDecl from the canonical function declaration,
2672 // since the map is then valid for any redeclaration or definition of that
2673 // function.
2674 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2675 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2676 unsigned i = PV->getFunctionScopeIndex();
2677 return FD->getCanonicalDecl()->getParamDecl(i);
2678 }
2679 }
2680 return D;
2681}
2682
2683
Douglas Gregor12c9c002011-01-07 16:43:16 +00002684llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2685LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002686 D = getCanonicalParmVarDecl(D);
Chris Lattner57ad3782011-02-17 20:34:02 +00002687 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor895162d2010-04-30 18:55:50 +00002688 Current = Current->Outer) {
Chris Lattner57ad3782011-02-17 20:34:02 +00002689
Douglas Gregor895162d2010-04-30 18:55:50 +00002690 // Check if we found something within this scope.
Douglas Gregorebb1c562010-12-21 21:22:51 +00002691 const Decl *CheckD = D;
2692 do {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002693 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregorebb1c562010-12-21 21:22:51 +00002694 if (Found != Current->LocalDecls.end())
Douglas Gregor12c9c002011-01-07 16:43:16 +00002695 return &Found->second;
Douglas Gregorebb1c562010-12-21 21:22:51 +00002696
2697 // If this is a tag declaration, it's possible that we need to look for
2698 // a previous declaration.
2699 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregoref96ee02012-01-14 16:38:05 +00002700 CheckD = Tag->getPreviousDecl();
Douglas Gregorebb1c562010-12-21 21:22:51 +00002701 else
2702 CheckD = 0;
2703 } while (CheckD);
2704
Douglas Gregor895162d2010-04-30 18:55:50 +00002705 // If we aren't combined with our outer scope, we're done.
2706 if (!Current->CombineWithOuterScope)
2707 break;
2708 }
Chris Lattner57ad3782011-02-17 20:34:02 +00002709
Serge Pavlovdc49d522013-07-15 06:14:07 +00002710 // If we're performing a partial substitution during template argument
2711 // deduction, we may not have values for template parameters yet.
2712 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2713 isa<TemplateTemplateParmDecl>(D))
2714 return 0;
2715
Chris Lattner57ad3782011-02-17 20:34:02 +00002716 // If we didn't find the decl, then we either have a sema bug, or we have a
2717 // forward reference to a label declaration. Return null to indicate that
2718 // we have an uninstantiated label.
2719 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Douglas Gregor895162d2010-04-30 18:55:50 +00002720 return 0;
2721}
2722
John McCall2a7fb272010-08-25 05:32:35 +00002723void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002724 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002725 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregord3731192011-01-10 07:32:04 +00002726 if (Stored.isNull())
2727 Stored = Inst;
Benjamin Kramer3bbffd52013-04-12 15:22:25 +00002728 else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>())
2729 Pack->push_back(Inst);
2730 else
Douglas Gregord3731192011-01-10 07:32:04 +00002731 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Douglas Gregor895162d2010-04-30 18:55:50 +00002732}
Douglas Gregor12c9c002011-01-07 16:43:16 +00002733
2734void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2735 Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002736 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002737 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2738 Pack->push_back(Inst);
2739}
2740
2741void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002742 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002743 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2744 assert(Stored.isNull() && "Already instantiated this local");
2745 DeclArgumentPack *Pack = new DeclArgumentPack;
2746 Stored = Pack;
2747 ArgumentPacks.push_back(Pack);
2748}
2749
Douglas Gregord3731192011-01-10 07:32:04 +00002750void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2751 const TemplateArgument *ExplicitArgs,
2752 unsigned NumExplicitArgs) {
2753 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2754 "Already have a partially-substituted pack");
2755 assert((!PartiallySubstitutedPack
2756 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2757 "Wrong number of arguments in partially-substituted pack");
2758 PartiallySubstitutedPack = Pack;
2759 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2760 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2761}
2762
2763NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2764 const TemplateArgument **ExplicitArgs,
2765 unsigned *NumExplicitArgs) const {
2766 if (ExplicitArgs)
2767 *ExplicitArgs = 0;
2768 if (NumExplicitArgs)
2769 *NumExplicitArgs = 0;
2770
2771 for (const LocalInstantiationScope *Current = this; Current;
2772 Current = Current->Outer) {
2773 if (Current->PartiallySubstitutedPack) {
2774 if (ExplicitArgs)
2775 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2776 if (NumExplicitArgs)
2777 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2778
2779 return Current->PartiallySubstitutedPack;
2780 }
2781
2782 if (!Current->CombineWithOuterScope)
2783 break;
2784 }
2785
2786 return 0;
2787}