blob: 073d64407a15098796ebead492c8b41ae8ed603c [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"
John McCall19510852010-08-20 18:27:03 +000015#include "clang/Sema/DeclSpec.h"
Richard Smith7a614d82011-06-11 17:19:42 +000016#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Lookup.h"
John McCall7cd088e2010-08-24 07:21:54 +000018#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000019#include "clang/Sema/TemplateDeduction.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000020#include "clang/AST/ASTConsumer.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000021#include "clang/AST/ASTContext.h"
22#include "clang/AST/Expr.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000023#include "clang/AST/DeclTemplate.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000024#include "clang/Basic/LangOptions.h"
25
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)
75 Result.addOuterTemplateArguments(0, 0);
76 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.
119 std::pair<const TemplateArgument *, unsigned>
120 Injected = FunTmpl->getInjectedTemplateArgs();
121 Result.addOuterTemplateArguments(Injected.first, Injected.second);
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000122 }
123
John McCallf181d8a2009-08-29 03:16:09 +0000124 // If this is a friend declaration and it declares an entity at
125 // namespace scope, take arguments from its lexical parent
Douglas Gregore7089b02010-05-03 23:29:10 +0000126 // instead of its semantic parent, unless of course the pattern we're
127 // instantiating actually comes from the file's context!
John McCallf181d8a2009-08-29 03:16:09 +0000128 if (Function->getFriendObjectKind() &&
Douglas Gregore7089b02010-05-03 23:29:10 +0000129 Function->getDeclContext()->isFileContext() &&
130 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCallf181d8a2009-08-29 03:16:09 +0000131 Ctx = Function->getLexicalDeclContext();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000132 RelativeToPrimary = false;
John McCallf181d8a2009-08-29 03:16:09 +0000133 continue;
134 }
Douglas Gregor24bae922010-07-08 18:37:38 +0000135 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
136 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
137 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
138 const TemplateSpecializationType *TST
139 = cast<TemplateSpecializationType>(Context.getCanonicalType(T));
140 Result.addOuterTemplateArguments(TST->getArgs(), TST->getNumArgs());
141 if (ClassTemplate->isMemberSpecialization())
142 break;
143 }
Douglas Gregord1102432009-08-28 17:37:35 +0000144 }
John McCallf181d8a2009-08-29 03:16:09 +0000145
146 Ctx = Ctx->getParent();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000147 RelativeToPrimary = false;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000148 }
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Douglas Gregord1102432009-08-28 17:37:35 +0000150 return Result;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000151}
152
Douglas Gregorf35f8282009-11-11 21:54:23 +0000153bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
154 switch (Kind) {
155 case TemplateInstantiation:
156 case DefaultTemplateArgumentInstantiation:
157 case DefaultFunctionArgumentInstantiation:
158 return true;
159
160 case ExplicitTemplateArgumentSubstitution:
161 case DeducedTemplateArgumentSubstitution:
162 case PriorTemplateArgumentSubstitution:
163 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;
Douglas Gregordf667e72009-03-10 20:44:00 +0000184 Inst.Entity = reinterpret_cast<uintptr_t>(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
Mike Stump1eb44332009-09-09 15:08:12 +0000193Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregordf667e72009-03-10 20:44:00 +0000194 SourceLocation PointOfInstantiation,
195 TemplateDecl *Template,
196 const TemplateArgument *TemplateArgs,
197 unsigned NumTemplateArgs,
198 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000199 : SemaRef(SemaRef),
200 SavedInNonInstantiationSFINAEContext(
201 SemaRef.InNonInstantiationSFINAEContext)
202{
Douglas Gregordf667e72009-03-10 20:44:00 +0000203 Invalid = CheckInstantiationDepth(PointOfInstantiation,
204 InstantiationRange);
205 if (!Invalid) {
206 ActiveTemplateInstantiation Inst;
Mike Stump1eb44332009-09-09 15:08:12 +0000207 Inst.Kind
Douglas Gregordf667e72009-03-10 20:44:00 +0000208 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
209 Inst.PointOfInstantiation = PointOfInstantiation;
210 Inst.Entity = reinterpret_cast<uintptr_t>(Template);
211 Inst.TemplateArgs = TemplateArgs;
212 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor26dce442009-03-10 00:06:19 +0000213 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000214 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor26dce442009-03-10 00:06:19 +0000215 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor26dce442009-03-10 00:06:19 +0000216 }
217}
218
Mike Stump1eb44332009-09-09 15:08:12 +0000219Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregor637a4092009-06-10 23:47:09 +0000220 SourceLocation PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000221 FunctionTemplateDecl *FunctionTemplate,
222 const TemplateArgument *TemplateArgs,
223 unsigned NumTemplateArgs,
224 ActiveTemplateInstantiation::InstantiationKind Kind,
Douglas Gregor9b623632010-10-12 23:32:35 +0000225 sema::TemplateDeductionInfo &DeductionInfo,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000226 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000227 : SemaRef(SemaRef),
228 SavedInNonInstantiationSFINAEContext(
229 SemaRef.InNonInstantiationSFINAEContext)
230{
Douglas Gregorcca9e962009-07-01 22:01:06 +0000231 Invalid = CheckInstantiationDepth(PointOfInstantiation,
232 InstantiationRange);
233 if (!Invalid) {
234 ActiveTemplateInstantiation Inst;
235 Inst.Kind = Kind;
236 Inst.PointOfInstantiation = PointOfInstantiation;
237 Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
238 Inst.TemplateArgs = TemplateArgs;
239 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor9b623632010-10-12 23:32:35 +0000240 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000241 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000242 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000243 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregorf35f8282009-11-11 21:54:23 +0000244
245 if (!Inst.isInstantiationRecord())
246 ++SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000247 }
248}
249
Mike Stump1eb44332009-09-09 15:08:12 +0000250Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000251 SourceLocation PointOfInstantiation,
Douglas Gregor637a4092009-06-10 23:47:09 +0000252 ClassTemplatePartialSpecializationDecl *PartialSpec,
253 const TemplateArgument *TemplateArgs,
254 unsigned NumTemplateArgs,
Douglas Gregor9b623632010-10-12 23:32:35 +0000255 sema::TemplateDeductionInfo &DeductionInfo,
Douglas Gregor637a4092009-06-10 23:47:09 +0000256 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000257 : SemaRef(SemaRef),
258 SavedInNonInstantiationSFINAEContext(
259 SemaRef.InNonInstantiationSFINAEContext)
260{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000261 Invalid = false;
262
263 ActiveTemplateInstantiation Inst;
264 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
265 Inst.PointOfInstantiation = PointOfInstantiation;
266 Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
267 Inst.TemplateArgs = TemplateArgs;
268 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor9b623632010-10-12 23:32:35 +0000269 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000270 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000271 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000272 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
273
274 assert(!Inst.isInstantiationRecord());
275 ++SemaRef.NonInstantiationEntries;
Douglas Gregor637a4092009-06-10 23:47:09 +0000276}
277
Mike Stump1eb44332009-09-09 15:08:12 +0000278Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000279 SourceLocation PointOfInstantiation,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000280 ParmVarDecl *Param,
281 const TemplateArgument *TemplateArgs,
282 unsigned NumTemplateArgs,
283 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000284 : SemaRef(SemaRef),
285 SavedInNonInstantiationSFINAEContext(
286 SemaRef.InNonInstantiationSFINAEContext)
287{
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000288 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000289
290 if (!Invalid) {
291 ActiveTemplateInstantiation Inst;
292 Inst.Kind
293 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000294 Inst.PointOfInstantiation = PointOfInstantiation;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000295 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
296 Inst.TemplateArgs = TemplateArgs;
297 Inst.NumTemplateArgs = NumTemplateArgs;
298 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000299 SemaRef.InNonInstantiationSFINAEContext = false;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000300 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000301 }
302}
303
304Sema::InstantiatingTemplate::
305InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000306 NamedDecl *Template,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000307 NonTypeTemplateParmDecl *Param,
308 const TemplateArgument *TemplateArgs,
309 unsigned NumTemplateArgs,
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000310 SourceRange InstantiationRange)
311 : SemaRef(SemaRef),
312 SavedInNonInstantiationSFINAEContext(
313 SemaRef.InNonInstantiationSFINAEContext)
314{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000315 Invalid = false;
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000316
Douglas Gregorf35f8282009-11-11 21:54:23 +0000317 ActiveTemplateInstantiation Inst;
318 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
319 Inst.PointOfInstantiation = PointOfInstantiation;
320 Inst.Template = Template;
321 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
322 Inst.TemplateArgs = TemplateArgs;
323 Inst.NumTemplateArgs = NumTemplateArgs;
324 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000325 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000326 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
327
328 assert(!Inst.isInstantiationRecord());
329 ++SemaRef.NonInstantiationEntries;
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000330}
331
332Sema::InstantiatingTemplate::
333InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000334 NamedDecl *Template,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000335 TemplateTemplateParmDecl *Param,
336 const TemplateArgument *TemplateArgs,
337 unsigned NumTemplateArgs,
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000338 SourceRange InstantiationRange)
339 : SemaRef(SemaRef),
340 SavedInNonInstantiationSFINAEContext(
341 SemaRef.InNonInstantiationSFINAEContext)
342{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000343 Invalid = false;
344 ActiveTemplateInstantiation Inst;
345 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
346 Inst.PointOfInstantiation = PointOfInstantiation;
347 Inst.Template = Template;
348 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
349 Inst.TemplateArgs = TemplateArgs;
350 Inst.NumTemplateArgs = NumTemplateArgs;
351 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000352 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000353 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000354
Douglas Gregorf35f8282009-11-11 21:54:23 +0000355 assert(!Inst.isInstantiationRecord());
356 ++SemaRef.NonInstantiationEntries;
357}
358
359Sema::InstantiatingTemplate::
360InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
361 TemplateDecl *Template,
362 NamedDecl *Param,
363 const TemplateArgument *TemplateArgs,
364 unsigned NumTemplateArgs,
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000365 SourceRange InstantiationRange)
366 : SemaRef(SemaRef),
367 SavedInNonInstantiationSFINAEContext(
368 SemaRef.InNonInstantiationSFINAEContext)
369{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000370 Invalid = false;
371
372 ActiveTemplateInstantiation Inst;
373 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
374 Inst.PointOfInstantiation = PointOfInstantiation;
375 Inst.Template = Template;
376 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
377 Inst.TemplateArgs = TemplateArgs;
378 Inst.NumTemplateArgs = NumTemplateArgs;
379 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000380 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000381 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
382
383 assert(!Inst.isInstantiationRecord());
384 ++SemaRef.NonInstantiationEntries;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000385}
386
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000387void Sema::InstantiatingTemplate::Clear() {
388 if (!Invalid) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000389 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
390 assert(SemaRef.NonInstantiationEntries > 0);
391 --SemaRef.NonInstantiationEntries;
392 }
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000393 SemaRef.InNonInstantiationSFINAEContext
394 = SavedInNonInstantiationSFINAEContext;
Douglas Gregor26dce442009-03-10 00:06:19 +0000395 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000396 Invalid = true;
397 }
Douglas Gregor26dce442009-03-10 00:06:19 +0000398}
399
Douglas Gregordf667e72009-03-10 20:44:00 +0000400bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
401 SourceLocation PointOfInstantiation,
402 SourceRange InstantiationRange) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000403 assert(SemaRef.NonInstantiationEntries <=
404 SemaRef.ActiveTemplateInstantiations.size());
405 if ((SemaRef.ActiveTemplateInstantiations.size() -
406 SemaRef.NonInstantiationEntries)
407 <= SemaRef.getLangOptions().InstantiationDepth)
Douglas Gregordf667e72009-03-10 20:44:00 +0000408 return false;
409
Mike Stump1eb44332009-09-09 15:08:12 +0000410 SemaRef.Diag(PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000411 diag::err_template_recursion_depth_exceeded)
412 << SemaRef.getLangOptions().InstantiationDepth
413 << InstantiationRange;
414 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
415 << SemaRef.getLangOptions().InstantiationDepth;
416 return true;
417}
418
Douglas Gregoree1828a2009-03-10 18:03:33 +0000419/// \brief Prints the current instantiation stack through a series of
420/// notes.
421void Sema::PrintInstantiationStack() {
Douglas Gregor575cf372010-04-20 07:18:24 +0000422 // Determine which template instantiations to skip, if any.
423 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
424 unsigned Limit = Diags.getTemplateBacktraceLimit();
425 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
426 SkipStart = Limit / 2 + Limit % 2;
427 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
428 }
429
Douglas Gregorcca9e962009-07-01 22:01:06 +0000430 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregor575cf372010-04-20 07:18:24 +0000431 unsigned InstantiationIdx = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000432 for (SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
Douglas Gregoree1828a2009-03-10 18:03:33 +0000433 Active = ActiveTemplateInstantiations.rbegin(),
434 ActiveEnd = ActiveTemplateInstantiations.rend();
435 Active != ActiveEnd;
Douglas Gregor575cf372010-04-20 07:18:24 +0000436 ++Active, ++InstantiationIdx) {
437 // Skip this instantiation?
438 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
439 if (InstantiationIdx == SkipStart) {
440 // Note that we're skipping instantiations.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000441 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor575cf372010-04-20 07:18:24 +0000442 diag::note_instantiation_contexts_suppressed)
443 << unsigned(ActiveTemplateInstantiations.size() - Limit);
444 }
445 continue;
446 }
447
Douglas Gregordf667e72009-03-10 20:44:00 +0000448 switch (Active->Kind) {
449 case ActiveTemplateInstantiation::TemplateInstantiation: {
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000450 Decl *D = reinterpret_cast<Decl *>(Active->Entity);
451 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
452 unsigned DiagID = diag::note_template_member_class_here;
453 if (isa<ClassTemplateSpecializationDecl>(Record))
454 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000455 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000456 << Context.getTypeDeclType(Record)
457 << Active->InstantiationRange;
Douglas Gregor7caa6822009-07-24 20:34:43 +0000458 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1637be72009-06-26 00:10:03 +0000459 unsigned DiagID;
460 if (Function->getPrimaryTemplate())
461 DiagID = diag::note_function_template_spec_here;
462 else
463 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000464 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000465 << Function
466 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000467 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000468 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor7caa6822009-07-24 20:34:43 +0000469 diag::note_template_static_data_member_def_here)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000470 << VD
471 << Active->InstantiationRange;
472 } else {
473 Diags.Report(Active->PointOfInstantiation,
474 diag::note_template_type_alias_instantiation_here)
475 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregor7caa6822009-07-24 20:34:43 +0000476 << Active->InstantiationRange;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000477 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000478 break;
479 }
480
481 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
482 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
483 std::string TemplateArgsStr
Douglas Gregor7532dc62009-03-30 22:58:21 +0000484 = TemplateSpecializationType::PrintTemplateArgumentList(
Mike Stump1eb44332009-09-09 15:08:12 +0000485 Active->TemplateArgs,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000486 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000487 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000488 Diags.Report(Active->PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000489 diag::note_default_arg_instantiation_here)
490 << (Template->getNameAsString() + TemplateArgsStr)
491 << Active->InstantiationRange;
492 break;
493 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000494
Douglas Gregorcca9e962009-07-01 22:01:06 +0000495 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Mike Stump1eb44332009-09-09 15:08:12 +0000496 FunctionTemplateDecl *FnTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +0000497 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000498 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000499 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000500 << FnTmpl
501 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
502 Active->TemplateArgs,
503 Active->NumTemplateArgs)
504 << Active->InstantiationRange;
Douglas Gregor637a4092009-06-10 23:47:09 +0000505 break;
506 }
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Douglas Gregorcca9e962009-07-01 22:01:06 +0000508 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
509 if (ClassTemplatePartialSpecializationDecl *PartialSpec
510 = dyn_cast<ClassTemplatePartialSpecializationDecl>(
511 (Decl *)Active->Entity)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000512 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000513 diag::note_partial_spec_deduct_instantiation_here)
514 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor5e402912010-03-30 20:35:20 +0000515 << getTemplateArgumentBindingsText(
516 PartialSpec->getTemplateParameters(),
517 Active->TemplateArgs,
518 Active->NumTemplateArgs)
Douglas Gregorcca9e962009-07-01 22:01:06 +0000519 << Active->InstantiationRange;
520 } else {
521 FunctionTemplateDecl *FnTmpl
522 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000523 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000524 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000525 << FnTmpl
526 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
527 Active->TemplateArgs,
528 Active->NumTemplateArgs)
529 << Active->InstantiationRange;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000530 }
531 break;
Douglas Gregor637a4092009-06-10 23:47:09 +0000532
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000533 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
534 ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity);
535 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000537 std::string TemplateArgsStr
538 = TemplateSpecializationType::PrintTemplateArgumentList(
Mike Stump1eb44332009-09-09 15:08:12 +0000539 Active->TemplateArgs,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000540 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000541 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000542 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000543 diag::note_default_function_arg_instantiation_here)
Anders Carlsson6bc107b2009-09-05 05:38:54 +0000544 << (FD->getNameAsString() + TemplateArgsStr)
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000545 << Active->InstantiationRange;
546 break;
547 }
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000549 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
550 NamedDecl *Parm = cast<NamedDecl>((Decl *)Active->Entity);
551 std::string Name;
552 if (!Parm->getName().empty())
553 Name = std::string(" '") + Parm->getName().str() + "'";
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000554
555 TemplateParameterList *TemplateParams = 0;
556 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
557 TemplateParams = Template->getTemplateParameters();
558 else
559 TemplateParams =
560 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
561 ->getTemplateParameters();
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000562 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000563 diag::note_prior_template_arg_substitution)
564 << isa<TemplateTemplateParmDecl>(Parm)
565 << Name
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000566 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000567 Active->TemplateArgs,
568 Active->NumTemplateArgs)
569 << Active->InstantiationRange;
570 break;
571 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000572
573 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000574 TemplateParameterList *TemplateParams = 0;
575 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
576 TemplateParams = Template->getTemplateParameters();
577 else
578 TemplateParams =
579 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
580 ->getTemplateParameters();
581
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000582 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000583 diag::note_template_default_arg_checking)
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000584 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000585 Active->TemplateArgs,
586 Active->NumTemplateArgs)
587 << Active->InstantiationRange;
588 break;
589 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000590 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000591 }
592}
593
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000594llvm::Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000595 if (InNonInstantiationSFINAEContext)
596 return llvm::Optional<TemplateDeductionInfo *>(0);
597
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000598 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
599 Active = ActiveTemplateInstantiations.rbegin(),
600 ActiveEnd = ActiveTemplateInstantiations.rend();
601 Active != ActiveEnd;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000602 ++Active)
603 {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000604 switch(Active->Kind) {
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000605 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000606 case ActiveTemplateInstantiation::TemplateInstantiation:
Douglas Gregorcca9e962009-07-01 22:01:06 +0000607 // This is a template instantiation, so there is no SFINAE.
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000608 return llvm::Optional<TemplateDeductionInfo *>();
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000610 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000611 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000612 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000613 // A default template argument instantiation and substitution into
614 // template parameters with arguments for prior parameters may or may
615 // not be a SFINAE context; look further up the stack.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000616 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Douglas Gregorcca9e962009-07-01 22:01:06 +0000618 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
619 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
620 // We're either substitution explicitly-specified template arguments
621 // or deduced template arguments, so SFINAE applies.
Douglas Gregor9b623632010-10-12 23:32:35 +0000622 assert(Active->DeductionInfo && "Missing deduction info pointer");
623 return Active->DeductionInfo;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000624 }
625 }
626
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000627 return llvm::Optional<TemplateDeductionInfo *>();
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000628}
629
Douglas Gregord3731192011-01-10 07:32:04 +0000630/// \brief Retrieve the depth and index of a parameter pack.
631static std::pair<unsigned, unsigned>
632getDepthAndIndex(NamedDecl *ND) {
633 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
634 return std::make_pair(TTP->getDepth(), TTP->getIndex());
635
636 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
637 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
638
639 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
640 return std::make_pair(TTP->getDepth(), TTP->getIndex());
641}
642
Douglas Gregor99ebf652009-02-27 19:31:52 +0000643//===----------------------------------------------------------------------===/
644// Template Instantiation for Types
645//===----------------------------------------------------------------------===/
Douglas Gregorcd281c32009-02-28 00:25:32 +0000646namespace {
Douglas Gregor895162d2010-04-30 18:55:50 +0000647 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000648 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000649 SourceLocation Loc;
650 DeclarationName Entity;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000651
Douglas Gregorcd281c32009-02-28 00:25:32 +0000652 public:
Douglas Gregor43959a92009-08-20 07:17:43 +0000653 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump1eb44332009-09-09 15:08:12 +0000654
655 TemplateInstantiator(Sema &SemaRef,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000656 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor577f75a2009-08-04 16:50:30 +0000657 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000658 DeclarationName Entity)
659 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregor43959a92009-08-20 07:17:43 +0000660 Entity(Entity) { }
Douglas Gregorcd281c32009-02-28 00:25:32 +0000661
Mike Stump1eb44332009-09-09 15:08:12 +0000662 /// \brief Determine whether the given type \p T has already been
Douglas Gregor577f75a2009-08-04 16:50:30 +0000663 /// transformed.
664 ///
665 /// For the purposes of template instantiation, a type has already been
666 /// transformed if it is NULL or if it is not dependent.
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000667 bool AlreadyTransformed(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Douglas Gregor577f75a2009-08-04 16:50:30 +0000669 /// \brief Returns the location of the entity being instantiated, if known.
670 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +0000671
Douglas Gregor577f75a2009-08-04 16:50:30 +0000672 /// \brief Returns the name of the entity being instantiated, if any.
673 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +0000674
Douglas Gregor972e6ce2009-10-27 06:26:26 +0000675 /// \brief Sets the "base" location and entity when that
676 /// information is known based on another transformation.
677 void setBase(SourceLocation Loc, DeclarationName Entity) {
678 this->Loc = Loc;
679 this->Entity = Entity;
680 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000681
682 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
683 SourceRange PatternRange,
David Blaikiea71f9d02011-09-22 02:34:54 +0000684 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000685 bool &ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000686 bool &RetainExpansion,
Douglas Gregorcded4f62011-01-14 17:04:44 +0000687 llvm::Optional<unsigned> &NumExpansions) {
Douglas Gregorb99268b2010-12-21 00:52:54 +0000688 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
689 PatternRange, Unexpanded,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000690 TemplateArgs,
691 ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000692 RetainExpansion,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000693 NumExpansions);
694 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000695
Douglas Gregor12c9c002011-01-07 16:43:16 +0000696 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
697 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
698 }
699
Douglas Gregord3731192011-01-10 07:32:04 +0000700 TemplateArgument ForgetPartiallySubstitutedPack() {
701 TemplateArgument Result;
702 if (NamedDecl *PartialPack
703 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
704 MultiLevelTemplateArgumentList &TemplateArgs
705 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
706 unsigned Depth, Index;
707 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
708 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
709 Result = TemplateArgs(Depth, Index);
710 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
711 }
712 }
713
714 return Result;
715 }
716
717 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
718 if (Arg.isNull())
719 return;
720
721 if (NamedDecl *PartialPack
722 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
723 MultiLevelTemplateArgumentList &TemplateArgs
724 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
725 unsigned Depth, Index;
726 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
727 TemplateArgs.setArgument(Depth, Index, Arg);
728 }
729 }
730
Douglas Gregor577f75a2009-08-04 16:50:30 +0000731 /// \brief Transform the given declaration by instantiating a reference to
732 /// this declaration.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000733 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregorb98b1992009-08-11 05:31:07 +0000734
Douglas Gregordfca6f52012-02-13 22:00:16 +0000735 void transformAttrs(Decl *Old, Decl *New) {
736 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
737 }
738
739 void transformedLocalDecl(Decl *Old, Decl *New) {
740 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
741 }
742
Mike Stump1eb44332009-09-09 15:08:12 +0000743 /// \brief Transform the definition of the given declaration by
Douglas Gregor43959a92009-08-20 07:17:43 +0000744 /// instantiating it.
Douglas Gregoraac571c2010-03-01 17:25:41 +0000745 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Douglas Gregor6cd21982009-10-20 05:58:46 +0000747 /// \bried Transform the first qualifier within a scope by instantiating the
748 /// declaration.
749 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
750
Douglas Gregor43959a92009-08-20 07:17:43 +0000751 /// \brief Rebuild the exception declaration and register the declaration
752 /// as an instantiated local.
Douglas Gregor83cb9422010-09-09 17:09:21 +0000753 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000754 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000755 SourceLocation StartLoc,
756 SourceLocation NameLoc,
757 IdentifierInfo *Name);
Mike Stump1eb44332009-09-09 15:08:12 +0000758
Douglas Gregorbe270a02010-04-26 17:57:08 +0000759 /// \brief Rebuild the Objective-C exception declaration and register the
760 /// declaration as an instantiated local.
761 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
762 TypeSourceInfo *TSInfo, QualType T);
763
John McCallc4e70192009-09-11 04:59:25 +0000764 /// \brief Check for tag mismatches when instantiating an
765 /// elaborated type.
John McCall21e413f2010-11-04 19:04:38 +0000766 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
767 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000768 NestedNameSpecifierLoc QualifierLoc,
769 QualType T);
John McCallc4e70192009-09-11 04:59:25 +0000770
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000771 TemplateName TransformTemplateName(CXXScopeSpec &SS,
772 TemplateName Name,
773 SourceLocation NameLoc,
774 QualType ObjectType = QualType(),
775 NamedDecl *FirstQualifierInScope = 0);
776
John McCall60d7b3a2010-08-24 06:29:42 +0000777 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
778 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
779 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
780 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor56bc9832010-12-24 00:15:10 +0000781 NonTypeTemplateParmDecl *D);
Douglas Gregorc7793c72011-01-15 01:15:58 +0000782 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
783 SubstNonTypeTemplateParmPackExpr *E);
784
Douglas Gregor895162d2010-04-30 18:55:50 +0000785 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000786 FunctionProtoTypeLoc TL);
Douglas Gregor6a24bfd2011-01-14 22:40:04 +0000787 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +0000788 int indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +0000789 llvm::Optional<unsigned> NumExpansions,
790 bool ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +0000791
Mike Stump1eb44332009-09-09 15:08:12 +0000792 /// \brief Transforms a template type parameter type by performing
Douglas Gregor577f75a2009-08-04 16:50:30 +0000793 /// substitution of the corresponding template type argument.
John McCalla2becad2009-10-21 00:40:46 +0000794 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000795 TemplateTypeParmTypeLoc TL);
Nick Lewycky03d98c52010-07-06 19:51:49 +0000796
Douglas Gregorc3069d62011-01-14 02:55:32 +0000797 /// \brief Transforms an already-substituted template type parameter pack
798 /// into either itself (if we aren't substituting into its pack expansion)
799 /// or the appropriate substituted argument.
800 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
801 SubstTemplateTypeParmPackTypeLoc TL);
802
John McCall60d7b3a2010-08-24 06:29:42 +0000803 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewycky03d98c52010-07-06 19:51:49 +0000804 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCall60d7b3a2010-08-24 06:29:42 +0000805 ExprResult Result =
Nick Lewycky03d98c52010-07-06 19:51:49 +0000806 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
807 getSema().CallsUndergoingInstantiation.pop_back();
808 return move(Result);
809 }
John McCall91a57552011-07-15 05:09:51 +0000810
811 private:
812 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
813 SourceLocation loc,
814 const TemplateArgument &arg);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000815 };
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000816}
817
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000818bool TemplateInstantiator::AlreadyTransformed(QualType T) {
819 if (T.isNull())
820 return true;
821
Douglas Gregor561f8122011-07-01 01:22:09 +0000822 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000823 return false;
824
825 getSema().MarkDeclarationsReferencedInType(Loc, T);
826 return true;
827}
828
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000829Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregorc68afe22009-09-03 21:38:09 +0000830 if (!D)
831 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Douglas Gregorc68afe22009-09-03 21:38:09 +0000833 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000834 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor6d3e6272010-02-05 19:54:12 +0000835 // If the corresponding template argument is NULL or non-existent, it's
836 // because we are performing instantiation from explicitly-specified
837 // template arguments in a function template, but there were some
838 // arguments left unspecified.
839 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
840 TTP->getPosition()))
841 return D;
842
Douglas Gregor61c4d282011-01-05 15:48:55 +0000843 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
844
845 if (TTP->isParameterPack()) {
846 assert(Arg.getKind() == TemplateArgument::Pack &&
847 "Missing argument pack");
848
Douglas Gregor1aee05d2011-01-15 06:45:20 +0000849 assert(getSema().ArgumentPackSubstitutionIndex >= 0);
Douglas Gregord3731192011-01-10 07:32:04 +0000850 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000851 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
852 }
853
854 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor788cd062009-11-11 01:00:40 +0000855 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregord6350ae2009-08-28 20:31:08 +0000856 "Wrong kind of template template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000857 return Template.getAsTemplateDecl();
Douglas Gregord6350ae2009-08-28 20:31:08 +0000858 }
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Douglas Gregor788cd062009-11-11 01:00:40 +0000860 // Fall through to find the instantiated declaration for this template
861 // template parameter.
Douglas Gregord1067e52009-08-06 06:41:21 +0000862 }
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000864 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000865}
866
Douglas Gregoraac571c2010-03-01 17:25:41 +0000867Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000868 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregor43959a92009-08-20 07:17:43 +0000869 if (!Inst)
870 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000871
Douglas Gregor43959a92009-08-20 07:17:43 +0000872 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
873 return Inst;
874}
875
Douglas Gregor6cd21982009-10-20 05:58:46 +0000876NamedDecl *
877TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
878 SourceLocation Loc) {
879 // If the first part of the nested-name-specifier was a template type
880 // parameter, instantiate that type parameter down to a tag type.
881 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
882 const TemplateTypeParmType *TTP
883 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor984a58b2010-12-20 22:48:17 +0000884
Douglas Gregor6cd21982009-10-20 05:58:46 +0000885 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor984a58b2010-12-20 22:48:17 +0000886 // FIXME: This needs testing w/ member access expressions.
887 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
888
889 if (TTP->isParameterPack()) {
890 assert(Arg.getKind() == TemplateArgument::Pack &&
891 "Missing argument pack");
892
Douglas Gregor2be29f42011-01-14 23:41:42 +0000893 if (getSema().ArgumentPackSubstitutionIndex == -1)
Douglas Gregor984a58b2010-12-20 22:48:17 +0000894 return 0;
Douglas Gregor984a58b2010-12-20 22:48:17 +0000895
Douglas Gregord3731192011-01-10 07:32:04 +0000896 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor984a58b2010-12-20 22:48:17 +0000897 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
898 }
899
900 QualType T = Arg.getAsType();
Douglas Gregor6cd21982009-10-20 05:58:46 +0000901 if (T.isNull())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000902 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000903
904 if (const TagType *Tag = T->getAs<TagType>())
905 return Tag->getDecl();
906
907 // The resulting type is not a tag; complain.
908 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
909 return 0;
910 }
911 }
912
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000913 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000914}
915
Douglas Gregor43959a92009-08-20 07:17:43 +0000916VarDecl *
917TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000918 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000919 SourceLocation StartLoc,
920 SourceLocation NameLoc,
921 IdentifierInfo *Name) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000922 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000923 StartLoc, NameLoc, Name);
Douglas Gregorbe270a02010-04-26 17:57:08 +0000924 if (Var)
925 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
926 return Var;
927}
928
929VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
930 TypeSourceInfo *TSInfo,
931 QualType T) {
932 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
933 if (Var)
Douglas Gregor43959a92009-08-20 07:17:43 +0000934 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
935 return Var;
936}
937
John McCallc4e70192009-09-11 04:59:25 +0000938QualType
John McCall21e413f2010-11-04 19:04:38 +0000939TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
940 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000941 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000942 QualType T) {
John McCallc4e70192009-09-11 04:59:25 +0000943 if (const TagType *TT = T->getAs<TagType>()) {
944 TagDecl* TD = TT->getDecl();
945
John McCall21e413f2010-11-04 19:04:38 +0000946 SourceLocation TagLocation = KeywordLoc;
John McCallc4e70192009-09-11 04:59:25 +0000947
948 // FIXME: type might be anonymous.
949 IdentifierInfo *Id = TD->getIdentifier();
950
951 // TODO: should we even warn on struct/class mismatches for this? Seems
952 // like it's likely to produce a lot of spurious errors.
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000953 if (Keyword != ETK_None && Keyword != ETK_Typename) {
954 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieubbf34c02011-06-10 03:11:26 +0000955 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
956 TagLocation, *Id)) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000957 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
958 << Id
959 << FixItHint::CreateReplacement(SourceRange(TagLocation),
960 TD->getKindName());
961 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
962 }
John McCallc4e70192009-09-11 04:59:25 +0000963 }
964 }
965
John McCall21e413f2010-11-04 19:04:38 +0000966 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
967 Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000968 QualifierLoc,
969 T);
John McCallc4e70192009-09-11 04:59:25 +0000970}
971
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000972TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
973 TemplateName Name,
974 SourceLocation NameLoc,
975 QualType ObjectType,
976 NamedDecl *FirstQualifierInScope) {
977 if (TemplateTemplateParmDecl *TTP
978 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
979 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
980 // If the corresponding template argument is NULL or non-existent, it's
981 // because we are performing instantiation from explicitly-specified
982 // template arguments in a function template, but there were some
983 // arguments left unspecified.
984 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
985 TTP->getPosition()))
986 return Name;
987
988 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
989
990 if (TTP->isParameterPack()) {
991 assert(Arg.getKind() == TemplateArgument::Pack &&
992 "Missing argument pack");
993
994 if (getSema().ArgumentPackSubstitutionIndex == -1) {
995 // We have the template argument pack to substitute, but we're not
996 // actually expanding the enclosing pack expansion yet. So, just
997 // keep the entire argument pack.
998 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
999 }
1000
1001 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1002 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1003 }
1004
1005 TemplateName Template = Arg.getAsTemplate();
Richard Smith3e4c6c42011-05-05 21:57:07 +00001006 assert(!Template.isNull() && "Null template template argument");
John McCall14606042011-06-30 08:33:18 +00001007
Douglas Gregor58750382011-03-05 20:06:51 +00001008 // We don't ever want to substitute for a qualified template name, since
1009 // the qualifier is handled separately. So, look through the qualified
1010 // template name to its underlying declaration.
1011 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1012 Template = TemplateName(QTN->getTemplateDecl());
John McCall14606042011-06-30 08:33:18 +00001013
1014 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001015 return Template;
1016 }
1017 }
1018
1019 if (SubstTemplateTemplateParmPackStorage *SubstPack
1020 = Name.getAsSubstTemplateTemplateParmPack()) {
1021 if (getSema().ArgumentPackSubstitutionIndex == -1)
1022 return Name;
1023
1024 const TemplateArgument &ArgPack = SubstPack->getArgumentPack();
1025 assert(getSema().ArgumentPackSubstitutionIndex < (int)ArgPack.pack_size() &&
1026 "Pack substitution index out-of-range");
1027 return ArgPack.pack_begin()[getSema().ArgumentPackSubstitutionIndex]
1028 .getAsTemplate();
1029 }
1030
1031 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1032 FirstQualifierInScope);
1033}
1034
John McCall60d7b3a2010-08-24 06:29:42 +00001035ExprResult
John McCall454feb92009-12-08 09:21:05 +00001036TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson773f3972009-09-11 01:22:35 +00001037 if (!E->isTypeDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00001038 return SemaRef.Owned(E);
Anders Carlsson773f3972009-09-11 01:22:35 +00001039
1040 FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
1041 assert(currentDecl && "Must have current function declaration when "
1042 "instantiating.");
1043
1044 PredefinedExpr::IdentType IT = E->getIdentType();
1045
Anders Carlsson848fa642010-02-11 18:20:28 +00001046 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Anders Carlsson773f3972009-09-11 01:22:35 +00001047
1048 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001049 QualType ResTy = getSema().Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001050 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
1051 ArrayType::Normal, 0);
1052 PredefinedExpr *PE =
1053 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
1054 return getSema().Owned(PE);
1055}
1056
John McCall60d7b3a2010-08-24 06:29:42 +00001057ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001058TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregordcee9802010-02-08 23:41:45 +00001059 NonTypeTemplateParmDecl *NTTP) {
John McCallb8fc0532010-02-06 08:42:39 +00001060 // If the corresponding template argument is NULL or non-existent, it's
1061 // because we are performing instantiation from explicitly-specified
1062 // template arguments in a function template, but there were some
1063 // arguments left unspecified.
1064 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1065 NTTP->getPosition()))
John McCall3fa5cae2010-10-26 07:05:15 +00001066 return SemaRef.Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Douglas Gregor56bc9832010-12-24 00:15:10 +00001068 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1069 if (NTTP->isParameterPack()) {
1070 assert(Arg.getKind() == TemplateArgument::Pack &&
1071 "Missing argument pack");
1072
1073 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc7793c72011-01-15 01:15:58 +00001074 // We have an argument pack, but we can't select a particular argument
1075 // out of it yet. Therefore, we'll build an expression to hold on to that
1076 // argument pack.
1077 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1078 E->getLocation(),
1079 NTTP->getDeclName());
1080 if (TargetType.isNull())
1081 return ExprError();
1082
1083 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1084 NTTP,
1085 E->getLocation(),
1086 Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001087 }
1088
Douglas Gregord3731192011-01-10 07:32:04 +00001089 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor56bc9832010-12-24 00:15:10 +00001090 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1091 }
Mike Stump1eb44332009-09-09 15:08:12 +00001092
John McCall91a57552011-07-15 05:09:51 +00001093 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1094}
1095
1096ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1097 NonTypeTemplateParmDecl *parm,
1098 SourceLocation loc,
1099 const TemplateArgument &arg) {
1100 ExprResult result;
1101 QualType type;
1102
John McCallb8fc0532010-02-06 08:42:39 +00001103 // The template argument itself might be an expression, in which
1104 // case we just return that expression.
John McCall91a57552011-07-15 05:09:51 +00001105 if (arg.getKind() == TemplateArgument::Expression) {
1106 Expr *argExpr = arg.getAsExpr();
1107 result = SemaRef.Owned(argExpr);
1108 type = argExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001109
John McCall91a57552011-07-15 05:09:51 +00001110 } else if (arg.getKind() == TemplateArgument::Declaration) {
1111 ValueDecl *VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001112
John McCall645cf442010-02-06 10:23:53 +00001113 // Find the instantiation of the template argument. This is
1114 // required for nested templates.
John McCallb8fc0532010-02-06 08:42:39 +00001115 VD = cast_or_null<ValueDecl>(
John McCall91a57552011-07-15 05:09:51 +00001116 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
John McCallb8fc0532010-02-06 08:42:39 +00001117 if (!VD)
John McCallf312b1e2010-08-26 23:41:50 +00001118 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001119
John McCall645cf442010-02-06 10:23:53 +00001120 // Derive the type we want the substituted decl to have. This had
1121 // better be non-dependent, or these checks will have serious problems.
John McCall91a57552011-07-15 05:09:51 +00001122 if (parm->isExpandedParameterPack()) {
1123 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1124 } else if (parm->isParameterPack() &&
1125 isa<PackExpansionType>(parm->getType())) {
1126 type = SemaRef.SubstType(
1127 cast<PackExpansionType>(parm->getType())->getPattern(),
1128 TemplateArgs, loc, parm->getDeclName());
1129 } else {
1130 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1131 loc, parm->getDeclName());
1132 }
1133 assert(!type.isNull() && "type substitution failed for param type");
1134 assert(!type->isDependentType() && "param type still dependent");
1135 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCallb8fc0532010-02-06 08:42:39 +00001136
John McCall91a57552011-07-15 05:09:51 +00001137 if (!result.isInvalid()) type = result.get()->getType();
1138 } else {
1139 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1140
1141 // Note that this type can be different from the type of 'result',
1142 // e.g. if it's an enum type.
1143 type = arg.getIntegralType();
1144 }
1145 if (result.isInvalid()) return ExprError();
1146
1147 Expr *resultExpr = result.take();
1148 return SemaRef.Owned(new (SemaRef.Context)
1149 SubstNonTypeTemplateParmExpr(type,
1150 resultExpr->getValueKind(),
1151 loc, parm, resultExpr));
John McCallb8fc0532010-02-06 08:42:39 +00001152}
1153
Douglas Gregorc7793c72011-01-15 01:15:58 +00001154ExprResult
1155TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1156 SubstNonTypeTemplateParmPackExpr *E) {
1157 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1158 // We aren't expanding the parameter pack, so just return ourselves.
1159 return getSema().Owned(E);
1160 }
1161
Douglas Gregorc7793c72011-01-15 01:15:58 +00001162 const TemplateArgument &ArgPack = E->getArgumentPack();
1163 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1164 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1165
1166 const TemplateArgument &Arg = ArgPack.pack_begin()[Index];
John McCall91a57552011-07-15 05:09:51 +00001167 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1168 E->getParameterPackLocation(),
1169 Arg);
Douglas Gregorc7793c72011-01-15 01:15:58 +00001170}
John McCallb8fc0532010-02-06 08:42:39 +00001171
John McCall60d7b3a2010-08-24 06:29:42 +00001172ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001173TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1174 NamedDecl *D = E->getDecl();
1175 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1176 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1177 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001178
1179 // We have a non-type template parameter that isn't fully substituted;
1180 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregorb98b1992009-08-11 05:31:07 +00001181 }
Mike Stump1eb44332009-09-09 15:08:12 +00001182
John McCall454feb92009-12-08 09:21:05 +00001183 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregorb98b1992009-08-11 05:31:07 +00001184}
1185
John McCall60d7b3a2010-08-24 06:29:42 +00001186ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall454feb92009-12-08 09:21:05 +00001187 CXXDefaultArgExpr *E) {
Sebastian Redla29e51b2009-11-08 13:56:19 +00001188 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1189 getDescribedFunctionTemplate() &&
1190 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor036aed12009-12-23 23:03:06 +00001191 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1192 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1193 E->getParam());
Sebastian Redla29e51b2009-11-08 13:56:19 +00001194}
1195
Douglas Gregor895162d2010-04-30 18:55:50 +00001196QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001197 FunctionProtoTypeLoc TL) {
Douglas Gregor895162d2010-04-30 18:55:50 +00001198 // We need a local instantiation scope for this function prototype.
John McCall2a7fb272010-08-25 05:32:35 +00001199 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
John McCall43fed0d2010-11-12 08:19:04 +00001200 return inherited::TransformFunctionProtoType(TLB, TL);
John McCall21ef0fa2010-03-11 09:03:00 +00001201}
1202
1203ParmVarDecl *
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001204TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +00001205 int indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001206 llvm::Optional<unsigned> NumExpansions,
1207 bool ExpectParameterPack) {
John McCallfb44de92011-05-01 22:35:37 +00001208 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001209 NumExpansions, ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +00001210}
1211
Mike Stump1eb44332009-09-09 15:08:12 +00001212QualType
John McCalla2becad2009-10-21 00:40:46 +00001213TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001214 TemplateTypeParmTypeLoc TL) {
John McCallf4c73712011-01-19 06:33:43 +00001215 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001216 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor99ebf652009-02-27 19:31:52 +00001217 // Replace the template type parameter with its corresponding
1218 // template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00001219
1220 // If the corresponding template argument is NULL or doesn't exist, it's
1221 // because we are performing instantiation from explicitly-specified
1222 // template arguments in a function template class, but there were some
Douglas Gregor16134c62009-07-01 00:28:38 +00001223 // arguments left unspecified.
John McCalla2becad2009-10-21 00:40:46 +00001224 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1225 TemplateTypeParmTypeLoc NewTL
1226 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1227 NewTL.setNameLoc(TL.getNameLoc());
1228 return TL.getType();
1229 }
Mike Stump1eb44332009-09-09 15:08:12 +00001230
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001231 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1232
1233 if (T->isParameterPack()) {
1234 assert(Arg.getKind() == TemplateArgument::Pack &&
1235 "Missing argument pack");
1236
1237 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc3069d62011-01-14 02:55:32 +00001238 // We have the template argument pack, but we're not expanding the
1239 // enclosing pack expansion yet. Just save the template argument
1240 // pack for later substitution.
1241 QualType Result
1242 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1243 SubstTemplateTypeParmPackTypeLoc NewTL
1244 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1245 NewTL.setNameLoc(TL.getNameLoc());
1246 return Result;
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001247 }
1248
Douglas Gregord3731192011-01-10 07:32:04 +00001249 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001250 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1251 }
1252
1253 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregor99ebf652009-02-27 19:31:52 +00001254 "Template argument kind mismatch");
Douglas Gregord6350ae2009-08-28 20:31:08 +00001255
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001256 QualType Replacement = Arg.getAsType();
John McCall49a832b2009-10-18 09:09:24 +00001257
1258 // TODO: only do this uniquing once, at the start of instantiation.
John McCalla2becad2009-10-21 00:40:46 +00001259 QualType Result
1260 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1261 SubstTemplateTypeParmTypeLoc NewTL
1262 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1263 NewTL.setNameLoc(TL.getNameLoc());
1264 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001265 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001266
1267 // The template type parameter comes from an inner template (e.g.,
1268 // the template parameter list of a member template inside the
1269 // template we are instantiating). Create a new template type
1270 // parameter with the template "level" reduced by one.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001271 TemplateTypeParmDecl *NewTTPDecl = 0;
1272 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1273 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1274 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1275
John McCalla2becad2009-10-21 00:40:46 +00001276 QualType Result
1277 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1278 - TemplateArgs.getNumLevels(),
1279 T->getIndex(),
1280 T->isParameterPack(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001281 NewTTPDecl);
John McCalla2becad2009-10-21 00:40:46 +00001282 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1283 NewTL.setNameLoc(TL.getNameLoc());
1284 return Result;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001285}
Douglas Gregor99ebf652009-02-27 19:31:52 +00001286
Douglas Gregorc3069d62011-01-14 02:55:32 +00001287QualType
1288TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1289 TypeLocBuilder &TLB,
1290 SubstTemplateTypeParmPackTypeLoc TL) {
1291 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1292 // We aren't expanding the parameter pack, so just return ourselves.
1293 SubstTemplateTypeParmPackTypeLoc NewTL
1294 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1295 NewTL.setNameLoc(TL.getNameLoc());
1296 return TL.getType();
1297 }
1298
1299 const TemplateArgument &ArgPack = TL.getTypePtr()->getArgumentPack();
1300 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1301 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1302
1303 QualType Result = ArgPack.pack_begin()[Index].getAsType();
1304 Result = getSema().Context.getSubstTemplateTypeParmType(
1305 TL.getTypePtr()->getReplacedParameter(),
1306 Result);
1307 SubstTemplateTypeParmTypeLoc NewTL
1308 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1309 NewTL.setNameLoc(TL.getNameLoc());
1310 return Result;
1311}
1312
John McCallce3ff2b2009-08-25 22:02:44 +00001313/// \brief Perform substitution on the type T with a given set of template
1314/// arguments.
Douglas Gregor99ebf652009-02-27 19:31:52 +00001315///
1316/// This routine substitutes the given template arguments into the
1317/// type T and produces the instantiated type.
1318///
1319/// \param T the type into which the template arguments will be
1320/// substituted. If this type is not dependent, it will be returned
1321/// immediately.
1322///
1323/// \param TemplateArgs the template arguments that will be
1324/// substituted for the top-level template parameters within T.
1325///
Douglas Gregor99ebf652009-02-27 19:31:52 +00001326/// \param Loc the location in the source code where this substitution
1327/// is being performed. It will typically be the location of the
1328/// declarator (if we're instantiating the type of some declaration)
1329/// or the location of the type in the source code (if, e.g., we're
1330/// instantiating the type of a cast expression).
1331///
1332/// \param Entity the name of the entity associated with a declaration
1333/// being instantiated (if any). May be empty to indicate that there
1334/// is no such entity (if, e.g., this is a type that occurs as part of
1335/// a cast expression) or that the entity has no name (e.g., an
1336/// unnamed function parameter).
1337///
1338/// \returns If the instantiation succeeds, the instantiated
1339/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCalla93c9342009-12-07 02:54:59 +00001340TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCallcd7ba1c2009-10-21 00:58:09 +00001341 const MultiLevelTemplateArgumentList &Args,
1342 SourceLocation Loc,
1343 DeclarationName Entity) {
1344 assert(!ActiveTemplateInstantiations.empty() &&
1345 "Cannot perform an instantiation without some context on the "
1346 "instantiation stack");
1347
Douglas Gregor561f8122011-07-01 01:22:09 +00001348 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor836adf62010-05-24 17:22:01 +00001349 !T->getType()->isVariablyModifiedType())
John McCallcd7ba1c2009-10-21 00:58:09 +00001350 return T;
1351
1352 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1353 return Instantiator.TransformType(T);
1354}
1355
Douglas Gregor603cfb42011-01-05 23:12:31 +00001356TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1357 const MultiLevelTemplateArgumentList &Args,
1358 SourceLocation Loc,
1359 DeclarationName Entity) {
1360 assert(!ActiveTemplateInstantiations.empty() &&
1361 "Cannot perform an instantiation without some context on the "
1362 "instantiation stack");
1363
1364 if (TL.getType().isNull())
1365 return 0;
1366
Douglas Gregor561f8122011-07-01 01:22:09 +00001367 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor603cfb42011-01-05 23:12:31 +00001368 !TL.getType()->isVariablyModifiedType()) {
1369 // FIXME: Make a copy of the TypeLoc data here, so that we can
1370 // return a new TypeSourceInfo. Inefficient!
1371 TypeLocBuilder TLB;
1372 TLB.pushFullCopy(TL);
1373 return TLB.getTypeSourceInfo(Context, TL.getType());
1374 }
1375
1376 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1377 TypeLocBuilder TLB;
1378 TLB.reserve(TL.getFullDataSize());
1379 QualType Result = Instantiator.TransformType(TLB, TL);
1380 if (Result.isNull())
1381 return 0;
1382
1383 return TLB.getTypeSourceInfo(Context, Result);
1384}
1385
John McCallcd7ba1c2009-10-21 00:58:09 +00001386/// Deprecated form of the above.
Mike Stump1eb44332009-09-09 15:08:12 +00001387QualType Sema::SubstType(QualType T,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001388 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallce3ff2b2009-08-25 22:02:44 +00001389 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregordf667e72009-03-10 20:44:00 +00001390 assert(!ActiveTemplateInstantiations.empty() &&
1391 "Cannot perform an instantiation without some context on the "
1392 "instantiation stack");
1393
Douglas Gregor836adf62010-05-24 17:22:01 +00001394 // If T is not a dependent type or a variably-modified type, there
1395 // is nothing to do.
Douglas Gregor561f8122011-07-01 01:22:09 +00001396 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregor99ebf652009-02-27 19:31:52 +00001397 return T;
1398
Douglas Gregor577f75a2009-08-04 16:50:30 +00001399 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1400 return Instantiator.TransformType(T);
Douglas Gregor99ebf652009-02-27 19:31:52 +00001401}
Douglas Gregor2943aed2009-03-03 04:44:36 +00001402
John McCall6cd3b9f2010-04-09 17:38:44 +00001403static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor561f8122011-07-01 01:22:09 +00001404 if (T->getType()->isInstantiationDependentType() ||
1405 T->getType()->isVariablyModifiedType())
John McCall6cd3b9f2010-04-09 17:38:44 +00001406 return true;
1407
Abramo Bagnara723df242010-12-14 22:11:44 +00001408 TypeLoc TL = T->getTypeLoc().IgnoreParens();
John McCall6cd3b9f2010-04-09 17:38:44 +00001409 if (!isa<FunctionProtoTypeLoc>(TL))
1410 return false;
1411
1412 FunctionProtoTypeLoc FP = cast<FunctionProtoTypeLoc>(TL);
1413 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1414 ParmVarDecl *P = FP.getArg(I);
1415
Douglas Gregorc056c172011-05-09 20:45:16 +00001416 // The parameter's type as written might be dependent even if the
1417 // decayed type was not dependent.
1418 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
Douglas Gregor561f8122011-07-01 01:22:09 +00001419 if (TSInfo->getType()->isInstantiationDependentType())
Douglas Gregorc056c172011-05-09 20:45:16 +00001420 return true;
1421
John McCall6cd3b9f2010-04-09 17:38:44 +00001422 // TODO: currently we always rebuild expressions. When we
1423 // properly get lazier about this, we should use the same
1424 // logic to avoid rebuilding prototypes here.
Douglas Gregor7b1cf302011-01-05 21:14:17 +00001425 if (P->hasDefaultArg())
John McCall6cd3b9f2010-04-09 17:38:44 +00001426 return true;
1427 }
1428
1429 return false;
1430}
1431
1432/// A form of SubstType intended specifically for instantiating the
1433/// type of a FunctionDecl. Its purpose is solely to force the
1434/// instantiation of default-argument expressions.
1435TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1436 const MultiLevelTemplateArgumentList &Args,
1437 SourceLocation Loc,
1438 DeclarationName Entity) {
1439 assert(!ActiveTemplateInstantiations.empty() &&
1440 "Cannot perform an instantiation without some context on the "
1441 "instantiation stack");
1442
1443 if (!NeedsInstantiationAsFunctionType(T))
1444 return T;
1445
1446 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1447
1448 TypeLocBuilder TLB;
1449
1450 TypeLoc TL = T->getTypeLoc();
1451 TLB.reserve(TL.getFullDataSize());
1452
John McCall43fed0d2010-11-12 08:19:04 +00001453 QualType Result = Instantiator.TransformType(TLB, TL);
John McCall6cd3b9f2010-04-09 17:38:44 +00001454 if (Result.isNull())
1455 return 0;
1456
1457 return TLB.getTypeSourceInfo(Context, Result);
1458}
1459
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001460ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001461 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallfb44de92011-05-01 22:35:37 +00001462 int indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001463 llvm::Optional<unsigned> NumExpansions,
1464 bool ExpectParameterPack) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001465 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Douglas Gregor603cfb42011-01-05 23:12:31 +00001466 TypeSourceInfo *NewDI = 0;
1467
Douglas Gregor603cfb42011-01-05 23:12:31 +00001468 TypeLoc OldTL = OldDI->getTypeLoc();
1469 if (isa<PackExpansionTypeLoc>(OldTL)) {
1470 PackExpansionTypeLoc ExpansionTL = cast<PackExpansionTypeLoc>(OldTL);
Douglas Gregor603cfb42011-01-05 23:12:31 +00001471
1472 // We have a function parameter pack. Substitute into the pattern of the
1473 // expansion.
1474 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1475 OldParm->getLocation(), OldParm->getDeclName());
1476 if (!NewDI)
1477 return 0;
1478
1479 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1480 // We still have unexpanded parameter packs, which means that
1481 // our function parameter is still a function parameter pack.
1482 // Therefore, make its type a pack expansion type.
Douglas Gregorcded4f62011-01-14 17:04:44 +00001483 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001484 NumExpansions);
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001485 } else if (ExpectParameterPack) {
1486 // We expected to get a parameter pack but didn't (because the type
1487 // itself is not a pack expansion type), so complain. This can occur when
1488 // the substitution goes through an alias template that "loses" the
1489 // pack expansion.
1490 Diag(OldParm->getLocation(),
1491 diag::err_function_parameter_pack_without_parameter_packs)
1492 << NewDI->getType();
1493 return 0;
1494 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001495 } else {
1496 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1497 OldParm->getDeclName());
1498 }
1499
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001500 if (!NewDI)
1501 return 0;
1502
1503 if (NewDI->getType()->isVoidType()) {
1504 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1505 return 0;
1506 }
1507
1508 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001509 OldParm->getInnerLocStart(),
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001510 OldParm->getLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001511 OldParm->getIdentifier(),
1512 NewDI->getType(), NewDI,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001513 OldParm->getStorageClass(),
1514 OldParm->getStorageClassAsWritten());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001515 if (!NewParm)
1516 return 0;
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001517
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001518 // Mark the (new) default argument as uninstantiated (if any).
1519 if (OldParm->hasUninstantiatedDefaultArg()) {
1520 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1521 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor8cfb7a32010-10-12 18:23:32 +00001522 } else if (OldParm->hasUnparsedDefaultArg()) {
1523 NewParm->setUnparsedDefaultArg();
1524 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001525 } else if (Expr *Arg = OldParm->getDefaultArg())
1526 NewParm->setUninstantiatedDefaultArg(Arg);
1527
1528 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001529
Douglas Gregor12c9c002011-01-07 16:43:16 +00001530 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smithc0536c82012-01-25 02:14:59 +00001531 // Add the new parameter to the instantiated parameter pack.
Douglas Gregor12c9c002011-01-07 16:43:16 +00001532 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1533 } else {
1534 // Introduce an Old -> New mapping
Douglas Gregor603cfb42011-01-05 23:12:31 +00001535 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregor12c9c002011-01-07 16:43:16 +00001536 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001537
Argyrios Kyrtzidise3041be2010-07-19 10:14:41 +00001538 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1539 // can be anything, is this right ?
Fariborz Jahanian55a17c02010-07-13 21:05:02 +00001540 NewParm->setDeclContext(CurContext);
John McCallfb44de92011-05-01 22:35:37 +00001541
1542 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1543 OldParm->getFunctionScopeIndex() + indexAdjustment);
Fariborz Jahaniane7ffbe22010-07-13 20:05:58 +00001544
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001545 return NewParm;
1546}
1547
Douglas Gregora009b592011-01-07 00:20:55 +00001548/// \brief Substitute the given template arguments into the given set of
1549/// parameters, producing the set of parameter types that would be generated
1550/// from such a substitution.
1551bool Sema::SubstParmTypes(SourceLocation Loc,
1552 ParmVarDecl **Params, unsigned NumParams,
1553 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001554 SmallVectorImpl<QualType> &ParamTypes,
1555 SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregora009b592011-01-07 00:20:55 +00001556 assert(!ActiveTemplateInstantiations.empty() &&
1557 "Cannot perform an instantiation without some context on the "
1558 "instantiation stack");
1559
1560 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1561 DeclarationName());
1562 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001563 ParamTypes, OutParams);
Douglas Gregora009b592011-01-07 00:20:55 +00001564}
1565
John McCallce3ff2b2009-08-25 22:02:44 +00001566/// \brief Perform substitution on the base class specifiers of the
1567/// given class template specialization.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001568///
1569/// Produces a diagnostic and returns true on error, returns false and
1570/// attaches the instantiated base classes to the class template
1571/// specialization if successful.
Mike Stump1eb44332009-09-09 15:08:12 +00001572bool
John McCallce3ff2b2009-08-25 22:02:44 +00001573Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1574 CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001575 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001576 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001577 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Mike Stump1eb44332009-09-09 15:08:12 +00001578 for (ClassTemplateSpecializationDecl::base_class_iterator
Douglas Gregord475b8d2009-03-25 21:17:03 +00001579 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
Douglas Gregor27b152f2009-03-10 18:52:44 +00001580 Base != BaseEnd; ++Base) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001581 if (!Base->getType()->isDependentType()) {
Fariborz Jahanian71c6e712009-07-22 17:41:53 +00001582 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
Douglas Gregor2943aed2009-03-03 04:44:36 +00001583 continue;
1584 }
1585
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001586 SourceLocation EllipsisLoc;
Douglas Gregor406f98f2011-03-02 02:04:06 +00001587 TypeSourceInfo *BaseTypeLoc;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001588 if (Base->isPackExpansion()) {
1589 // This is a pack expansion. See whether we should expand it now, or
1590 // wait until later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001591 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001592 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1593 Unexpanded);
1594 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00001595 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00001596 llvm::Optional<unsigned> NumExpansions;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001597 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1598 Base->getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001599 Unexpanded,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001600 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00001601 RetainExpansion,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001602 NumExpansions)) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001603 Invalid = true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001604 continue;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001605 }
1606
1607 // If we should expand this pack expansion now, do so.
1608 if (ShouldExpand) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00001609 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001610 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1611
1612 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1613 TemplateArgs,
1614 Base->getSourceRange().getBegin(),
1615 DeclarationName());
1616 if (!BaseTypeLoc) {
1617 Invalid = true;
1618 continue;
1619 }
1620
1621 if (CXXBaseSpecifier *InstantiatedBase
1622 = CheckBaseSpecifier(Instantiation,
1623 Base->getSourceRange(),
1624 Base->isVirtual(),
1625 Base->getAccessSpecifierAsWritten(),
1626 BaseTypeLoc,
1627 SourceLocation()))
1628 InstantiatedBases.push_back(InstantiatedBase);
1629 else
1630 Invalid = true;
1631 }
1632
1633 continue;
1634 }
1635
1636 // The resulting base specifier will (still) be a pack expansion.
1637 EllipsisLoc = Base->getEllipsisLoc();
Douglas Gregor406f98f2011-03-02 02:04:06 +00001638 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1639 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1640 TemplateArgs,
1641 Base->getSourceRange().getBegin(),
1642 DeclarationName());
1643 } else {
1644 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1645 TemplateArgs,
1646 Base->getSourceRange().getBegin(),
1647 DeclarationName());
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001648 }
1649
Nick Lewycky56062202010-07-26 16:56:01 +00001650 if (!BaseTypeLoc) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001651 Invalid = true;
1652 continue;
1653 }
1654
1655 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregord475b8d2009-03-25 21:17:03 +00001656 = CheckBaseSpecifier(Instantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001657 Base->getSourceRange(),
1658 Base->isVirtual(),
1659 Base->getAccessSpecifierAsWritten(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001660 BaseTypeLoc,
1661 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001662 InstantiatedBases.push_back(InstantiatedBase);
1663 else
1664 Invalid = true;
1665 }
1666
Douglas Gregor27b152f2009-03-10 18:52:44 +00001667 if (!Invalid &&
Jay Foadbeaaccd2009-05-21 09:52:38 +00001668 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001669 InstantiatedBases.size()))
1670 Invalid = true;
1671
1672 return Invalid;
1673}
1674
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001675// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramer5bbc3852012-02-06 11:13:08 +00001676namespace clang {
1677 namespace sema {
1678 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1679 const MultiLevelTemplateArgumentList &TemplateArgs);
1680 }
1681}
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001682
Douglas Gregord475b8d2009-03-25 21:17:03 +00001683/// \brief Instantiate the definition of a class from a given pattern.
1684///
1685/// \param PointOfInstantiation The point of instantiation within the
1686/// source code.
1687///
1688/// \param Instantiation is the declaration whose definition is being
1689/// instantiated. This will be either a class template specialization
1690/// or a member class of a class template specialization.
1691///
1692/// \param Pattern is the pattern from which the instantiation
1693/// occurs. This will be either the declaration of a class template or
1694/// the declaration of a member class of a class template.
1695///
1696/// \param TemplateArgs The template arguments to be substituted into
1697/// the pattern.
1698///
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001699/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor5842ba92009-08-24 15:23:48 +00001700///
1701/// \param Complain whether to complain if the class cannot be instantiated due
1702/// to the lack of a definition.
1703///
Douglas Gregord475b8d2009-03-25 21:17:03 +00001704/// \returns true if an error occurred, false otherwise.
1705bool
1706Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1707 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001708 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001709 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00001710 bool Complain) {
Douglas Gregord475b8d2009-03-25 21:17:03 +00001711 bool Invalid = false;
John McCalle29ba202009-08-20 01:44:21 +00001712
Mike Stump1eb44332009-09-09 15:08:12 +00001713 CXXRecordDecl *PatternDef
Douglas Gregor952b0172010-02-11 01:04:33 +00001714 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
John McCalld46a1122011-04-27 06:46:31 +00001715 if (!PatternDef || PatternDef->isBeingDefined()) {
1716 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001717 // Say nothing
John McCalld46a1122011-04-27 06:46:31 +00001718 } else if (PatternDef) {
1719 assert(PatternDef->isBeingDefined());
1720 Diag(PointOfInstantiation,
1721 diag::err_template_instantiate_within_definition)
1722 << (TSK != TSK_ImplicitInstantiation)
1723 << Context.getTypeDeclType(Instantiation);
1724 // Not much point in noting the template declaration here, since
1725 // we're lexically inside it.
1726 Instantiation->setInvalidDecl();
Douglas Gregor5842ba92009-08-24 15:23:48 +00001727 } else if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
Douglas Gregord475b8d2009-03-25 21:17:03 +00001728 Diag(PointOfInstantiation,
1729 diag::err_implicit_instantiate_member_undefined)
1730 << Context.getTypeDeclType(Instantiation);
1731 Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1732 } else {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00001733 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001734 << (TSK != TSK_ImplicitInstantiation)
Douglas Gregord475b8d2009-03-25 21:17:03 +00001735 << Context.getTypeDeclType(Instantiation);
1736 Diag(Pattern->getLocation(), diag::note_template_decl_here);
1737 }
Nico Weberc7feca02011-12-20 20:32:49 +00001738
1739 // In general, Instantiation isn't marked invalid to get more than one
1740 // error for multiple undefined instantiations. But the code that does
1741 // explicit declaration -> explicit definition conversion can't handle
1742 // invalid declarations, so mark as invalid in that case.
1743 if (TSK == TSK_ExplicitInstantiationDeclaration)
1744 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00001745 return true;
1746 }
1747 Pattern = PatternDef;
1748
Douglas Gregor454885e2009-10-15 15:54:05 +00001749 // \brief Record the point of instantiation.
1750 if (MemberSpecializationInfo *MSInfo
1751 = Instantiation->getMemberSpecializationInfo()) {
1752 MSInfo->setTemplateSpecializationKind(TSK);
1753 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001754 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weberc7feca02011-12-20 20:32:49 +00001755 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001756 Spec->setTemplateSpecializationKind(TSK);
1757 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00001758 }
1759
Douglas Gregord048bb72009-03-25 21:23:52 +00001760 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001761 if (Inst)
1762 return true;
1763
1764 // Enter the scope of this instantiation. We don't use
1765 // PushDeclContext because we don't have a scope.
John McCallf5813822010-04-29 00:35:03 +00001766 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor9679caf2010-05-12 17:27:19 +00001767 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00001768 Sema::PotentiallyEvaluated);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001769
Douglas Gregor05030bb2010-03-24 01:33:17 +00001770 // If this is an instantiation of a local class, merge this local
1771 // instantiation scope with the enclosing scope. Otherwise, every
1772 // instantiation of a class has its own local instantiation scope.
1773 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall2a7fb272010-08-25 05:32:35 +00001774 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor05030bb2010-03-24 01:33:17 +00001775
John McCall1d8d1cc2010-08-01 02:01:53 +00001776 // Pull attributes from the pattern onto the instantiation.
1777 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1778
Douglas Gregord475b8d2009-03-25 21:17:03 +00001779 // Start the definition of this instantiation.
1780 Instantiation->startDefinition();
Douglas Gregor13c85772010-05-06 00:28:52 +00001781
1782 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001783
John McCallce3ff2b2009-08-25 22:02:44 +00001784 // Do substitution on the base class specifiers.
1785 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregord475b8d2009-03-25 21:17:03 +00001786 Invalid = true;
1787
Douglas Gregord65587f2010-11-10 19:44:59 +00001788 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001789 SmallVector<Decl*, 4> Fields;
1790 SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
Richard Smith7a614d82011-06-11 17:19:42 +00001791 FieldsWithMemberInitializers;
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001792 // Delay instantiation of late parsed attributes.
1793 LateInstantiatedAttrVec LateAttrs;
1794 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1795
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001796 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001797 MemberEnd = Pattern->decls_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001798 Member != MemberEnd; ++Member) {
Argyrios Kyrtzidisbb5e4312010-11-04 03:18:57 +00001799 // Don't instantiate members not belonging in this semantic context.
1800 // e.g. for:
1801 // @code
1802 // template <int i> class A {
1803 // class B *g;
1804 // };
1805 // @endcode
1806 // 'class B' has the template as lexical context but semantically it is
1807 // introduced in namespace scope.
1808 if ((*Member)->getDeclContext() != Pattern)
1809 continue;
1810
Douglas Gregord65587f2010-11-10 19:44:59 +00001811 if ((*Member)->isInvalidDecl()) {
1812 Invalid = true;
1813 continue;
1814 }
1815
1816 Decl *NewMember = Instantiator.Visit(*Member);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001817 if (NewMember) {
Richard Smith7a614d82011-06-11 17:19:42 +00001818 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCalld226f652010-08-21 09:40:31 +00001819 Fields.push_back(Field);
Richard Smith7a614d82011-06-11 17:19:42 +00001820 FieldDecl *OldField = cast<FieldDecl>(*Member);
1821 if (OldField->getInClassInitializer())
1822 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
1823 Field));
1824 } else if (NewMember->isInvalidDecl())
Eli Friedman721e77d2009-12-07 00:22:08 +00001825 Invalid = true;
Douglas Gregord475b8d2009-03-25 21:17:03 +00001826 } else {
1827 // FIXME: Eventually, a NULL return will mean that one of the
Mike Stump390b4cc2009-05-16 07:39:55 +00001828 // instantiations was a semantic disaster, and we'll want to set Invalid =
1829 // true. For now, we expect to skip some members that we can't yet handle.
Douglas Gregord475b8d2009-03-25 21:17:03 +00001830 }
1831 }
1832
1833 // Finish checking fields.
David Blaikie77b6de02011-09-22 02:58:26 +00001834 ActOnFields(0, Instantiation->getLocation(), Instantiation, Fields,
1835 SourceLocation(), SourceLocation(), 0);
Douglas Gregor23c94db2010-07-02 17:43:08 +00001836 CheckCompletedCXXClass(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00001837
1838 // Attach any in-class member initializers now the class is complete.
1839 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
1840 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
1841 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
1842 Expr *OldInit = OldField->getInClassInitializer();
Richard Smith7a614d82011-06-11 17:19:42 +00001843
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001844 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
1845 /*CXXDirectInit=*/false);
1846 if (NewInit.isInvalid())
Richard Smith7a614d82011-06-11 17:19:42 +00001847 NewField->setInvalidDecl();
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001848 else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001849 Expr *Init = NewInit.take();
1850 assert(Init && "no-argument initializer in class");
1851 assert(!isa<ParenListExpr>(Init) && "call-style init in class");
1852 ActOnCXXInClassMemberInitializer(NewField,
1853 Init->getSourceRange().getBegin(), Init);
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001854 }
Richard Smith7a614d82011-06-11 17:19:42 +00001855 }
1856
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001857 // Instantiate late parsed attributes, and attach them to their decls.
1858 // See Sema::InstantiateAttrs
1859 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
1860 E = LateAttrs.end(); I != E; ++I) {
1861 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
1862 CurrentInstantiationScope = I->Scope;
1863 Attr *NewAttr =
1864 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
1865 I->NewDecl->addAttr(NewAttr);
1866 LocalInstantiationScope::deleteScopes(I->Scope,
1867 Instantiator.getStartingScope());
1868 }
1869 Instantiator.disableLateAttributeInstantiation();
1870 LateAttrs.clear();
1871
Richard Smith7a614d82011-06-11 17:19:42 +00001872 if (!FieldsWithMemberInitializers.empty())
1873 ActOnFinishDelayedMemberInitializers(Instantiation);
1874
Abramo Bagnarae9946242011-11-18 08:08:52 +00001875 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis734bd6e2012-02-11 01:59:57 +00001876 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnarae9946242011-11-18 08:08:52 +00001877 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnara09d82122011-10-03 20:34:03 +00001878 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnarae9946242011-11-18 08:08:52 +00001879 }
Abramo Bagnara09d82122011-10-03 20:34:03 +00001880
Douglas Gregor663b5a02009-10-14 20:14:33 +00001881 if (Instantiation->isInvalidDecl())
1882 Invalid = true;
Douglas Gregord65587f2010-11-10 19:44:59 +00001883 else {
1884 // Instantiate any out-of-line class template partial
1885 // specializations now.
1886 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
1887 P = Instantiator.delayed_partial_spec_begin(),
1888 PEnd = Instantiator.delayed_partial_spec_end();
1889 P != PEnd; ++P) {
1890 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
1891 P->first,
1892 P->second)) {
1893 Invalid = true;
1894 break;
1895 }
1896 }
1897 }
1898
Douglas Gregord475b8d2009-03-25 21:17:03 +00001899 // Exit the scope of this instantiation.
John McCallf5813822010-04-29 00:35:03 +00001900 SavedContext.pop();
Douglas Gregord475b8d2009-03-25 21:17:03 +00001901
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001902 if (!Invalid) {
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001903 Consumer.HandleTagDeclDefinition(Instantiation);
1904
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001905 // Always emit the vtable for an explicit instantiation definition
1906 // of a polymorphic class template specialization.
1907 if (TSK == TSK_ExplicitInstantiationDefinition)
1908 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
1909 }
1910
Douglas Gregord475b8d2009-03-25 21:17:03 +00001911 return Invalid;
1912}
1913
Douglas Gregor9b623632010-10-12 23:32:35 +00001914namespace {
1915 /// \brief A partial specialization whose template arguments have matched
1916 /// a given template-id.
1917 struct PartialSpecMatchResult {
1918 ClassTemplatePartialSpecializationDecl *Partial;
1919 TemplateArgumentList *Args;
Douglas Gregor9b623632010-10-12 23:32:35 +00001920 };
1921}
1922
Mike Stump1eb44332009-09-09 15:08:12 +00001923bool
Douglas Gregor2943aed2009-03-03 04:44:36 +00001924Sema::InstantiateClassTemplateSpecialization(
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001925 SourceLocation PointOfInstantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001926 ClassTemplateSpecializationDecl *ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001927 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00001928 bool Complain) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001929 // Perform the actual instantiation on the canonical declaration.
1930 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001931 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001932
Douglas Gregor52604ab2009-09-11 21:19:12 +00001933 // Check whether we have already instantiated or specialized this class
1934 // template specialization.
1935 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
1936 if (ClassTemplateSpec->getSpecializationKind() ==
1937 TSK_ExplicitInstantiationDeclaration &&
1938 TSK == TSK_ExplicitInstantiationDefinition) {
1939 // An explicit instantiation definition follows an explicit instantiation
1940 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
1941 // explicit instantiation.
1942 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001943
1944 // If this is an explicit instantiation definition, mark the
1945 // vtable as used.
Nico Weberc7feca02011-12-20 20:32:49 +00001946 if (TSK == TSK_ExplicitInstantiationDefinition &&
1947 !ClassTemplateSpec->isInvalidDecl())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001948 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
1949
Douglas Gregor52604ab2009-09-11 21:19:12 +00001950 return false;
1951 }
1952
1953 // We can only instantiate something that hasn't already been
1954 // instantiated or specialized. Fail without any diagnostics: our
1955 // caller will provide an error message.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001956 return true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00001957 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001958
Douglas Gregor9eea08b2009-09-15 16:51:42 +00001959 if (ClassTemplateSpec->isInvalidDecl())
1960 return true;
1961
Douglas Gregor2943aed2009-03-03 04:44:36 +00001962 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001963 CXXRecordDecl *Pattern = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00001964
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001965 // C++ [temp.class.spec.match]p1:
1966 // When a class template is used in a context that requires an
1967 // instantiation of the class, it is necessary to determine
1968 // whether the instantiation is to be generated using the primary
1969 // template or one of the partial specializations. This is done by
1970 // matching the template arguments of the class template
1971 // specialization with the template argument lists of the partial
1972 // specializations.
Douglas Gregor9b623632010-10-12 23:32:35 +00001973 typedef PartialSpecMatchResult MatchResult;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001974 SmallVector<MatchResult, 4> Matched;
1975 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001976 Template->getPartialSpecializations(PartialSpecs);
1977 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
1978 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
John McCall5769d612010-02-08 23:07:23 +00001979 TemplateDeductionInfo Info(Context, PointOfInstantiation);
Douglas Gregorf67875d2009-06-12 18:26:56 +00001980 if (TemplateDeductionResult Result
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001981 = DeduceTemplateArguments(Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001982 ClassTemplateSpec->getTemplateArgs(),
1983 Info)) {
1984 // FIXME: Store the failed-deduction information for use in
1985 // diagnostics, later.
1986 (void)Result;
1987 } else {
Douglas Gregor9b623632010-10-12 23:32:35 +00001988 Matched.push_back(PartialSpecMatchResult());
1989 Matched.back().Partial = Partial;
1990 Matched.back().Args = Info.take();
Douglas Gregorf67875d2009-06-12 18:26:56 +00001991 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00001992 }
1993
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001994 // If we're dealing with a member template where the template parameters
1995 // have been instantiated, this provides the original template parameters
1996 // from which the member template's parameters were instantiated.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001997 SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001998
Douglas Gregored9c0f92009-10-29 00:04:11 +00001999 if (Matched.size() >= 1) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002000 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002001 if (Matched.size() == 1) {
2002 // -- If exactly one matching specialization is found, the
2003 // instantiation is generated from that specialization.
2004 // We don't need to do anything for this.
2005 } else {
2006 // -- If more than one matching specialization is found, the
2007 // partial order rules (14.5.4.2) are used to determine
2008 // whether one of the specializations is more specialized
2009 // than the others. If none of the specializations is more
2010 // specialized than all of the other matching
2011 // specializations, then the use of the class template is
2012 // ambiguous and the program is ill-formed.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002013 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002014 PEnd = Matched.end();
2015 P != PEnd; ++P) {
Douglas Gregor9b623632010-10-12 23:32:35 +00002016 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002017 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002018 == P->Partial)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002019 Best = P;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002020 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002021
Douglas Gregored9c0f92009-10-29 00:04:11 +00002022 // Determine if the best partial specialization is more specialized than
2023 // the others.
2024 bool Ambiguous = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002025 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002026 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002027 P != PEnd; ++P) {
2028 if (P != Best &&
Douglas Gregor9b623632010-10-12 23:32:35 +00002029 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002030 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002031 != Best->Partial) {
Douglas Gregored9c0f92009-10-29 00:04:11 +00002032 Ambiguous = true;
2033 break;
2034 }
2035 }
2036
2037 if (Ambiguous) {
2038 // Partial ordering did not produce a clear winner. Complain.
2039 ClassTemplateSpec->setInvalidDecl();
2040 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2041 << ClassTemplateSpec;
2042
2043 // Print the matching partial specializations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002044 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002045 PEnd = Matched.end();
2046 P != PEnd; ++P)
Douglas Gregor9b623632010-10-12 23:32:35 +00002047 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2048 << getTemplateArgumentBindingsText(
2049 P->Partial->getTemplateParameters(),
2050 *P->Args);
Douglas Gregord6350ae2009-08-28 20:31:08 +00002051
Douglas Gregored9c0f92009-10-29 00:04:11 +00002052 return true;
2053 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002054 }
2055
2056 // Instantiate using the best class template partial specialization.
Douglas Gregor9b623632010-10-12 23:32:35 +00002057 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002058 while (OrigPartialSpec->getInstantiatedFromMember()) {
2059 // If we've found an explicit specialization of this class template,
2060 // stop here and use that as the pattern.
2061 if (OrigPartialSpec->isMemberSpecialization())
2062 break;
2063
2064 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2065 }
2066
2067 Pattern = OrigPartialSpec;
Douglas Gregor9b623632010-10-12 23:32:35 +00002068 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002069 } else {
2070 // -- If no matches are found, the instantiation is generated
2071 // from the primary template.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002072 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002073 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2074 // If we've found an explicit specialization of this class template,
2075 // stop here and use that as the pattern.
2076 if (OrigTemplate->isMemberSpecialization())
2077 break;
2078
Douglas Gregord6350ae2009-08-28 20:31:08 +00002079 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002080 }
2081
Douglas Gregord6350ae2009-08-28 20:31:08 +00002082 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002083 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002084
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002085 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2086 Pattern,
2087 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002088 TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002089 Complain);
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Douglas Gregor199d9912009-06-05 00:53:49 +00002091 return Result;
Douglas Gregor2943aed2009-03-03 04:44:36 +00002092}
Douglas Gregor5953d8b2009-03-19 17:26:29 +00002093
John McCallce3ff2b2009-08-25 22:02:44 +00002094/// \brief Instantiates the definitions of all of the member
2095/// of the given class, which is an instantiation of a class template
2096/// or a member class of a template.
Douglas Gregora58861f2009-05-13 20:28:22 +00002097void
2098Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002099 CXXRecordDecl *Instantiation,
2100 const MultiLevelTemplateArgumentList &TemplateArgs,
2101 TemplateSpecializationKind TSK) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002102 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
2103 DEnd = Instantiation->decls_end();
Douglas Gregora58861f2009-05-13 20:28:22 +00002104 D != DEnd; ++D) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002105 bool SuppressNew = false;
Douglas Gregora58861f2009-05-13 20:28:22 +00002106 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002107 if (FunctionDecl *Pattern
2108 = Function->getInstantiatedFromMemberFunction()) {
2109 MemberSpecializationInfo *MSInfo
2110 = Function->getMemberSpecializationInfo();
2111 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002112 if (MSInfo->getTemplateSpecializationKind()
2113 == TSK_ExplicitSpecialization)
2114 continue;
2115
Douglas Gregor0d035142009-10-27 18:42:08 +00002116 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2117 Function,
2118 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002119 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002120 SuppressNew) ||
2121 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002122 continue;
2123
Sean Hunt10620eb2011-05-06 20:44:56 +00002124 if (Function->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002125 continue;
2126
2127 if (TSK == TSK_ExplicitInstantiationDefinition) {
2128 // C++0x [temp.explicit]p8:
2129 // An explicit instantiation definition that names a class template
2130 // specialization explicitly instantiates the class template
2131 // specialization and is only an explicit instantiation definition
2132 // of members whose definition is visible at the point of
2133 // instantiation.
Sean Hunt10620eb2011-05-06 20:44:56 +00002134 if (!Pattern->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002135 continue;
2136
2137 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2138
2139 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2140 } else {
2141 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2142 }
Douglas Gregorf6b11852009-10-08 15:14:33 +00002143 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002144 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002145 if (Var->isStaticDataMember()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002146 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2147 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002148 if (MSInfo->getTemplateSpecializationKind()
2149 == TSK_ExplicitSpecialization)
2150 continue;
2151
Douglas Gregor0d035142009-10-27 18:42:08 +00002152 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2153 Var,
2154 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002155 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002156 SuppressNew) ||
2157 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002158 continue;
2159
Douglas Gregor0d035142009-10-27 18:42:08 +00002160 if (TSK == TSK_ExplicitInstantiationDefinition) {
2161 // C++0x [temp.explicit]p8:
2162 // An explicit instantiation definition that names a class template
2163 // specialization explicitly instantiates the class template
2164 // specialization and is only an explicit instantiation definition
2165 // of members whose definition is visible at the point of
2166 // instantiation.
2167 if (!Var->getInstantiatedFromStaticDataMember()
2168 ->getOutOfLineDefinition())
2169 continue;
2170
2171 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002172 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor0d035142009-10-27 18:42:08 +00002173 } else {
2174 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2175 }
2176 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002177 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
Douglas Gregora77eaa92010-04-18 18:11:38 +00002178 // Always skip the injected-class-name, along with any
2179 // redeclarations of nested classes, since both would cause us
2180 // to try to instantiate the members of a class twice.
Douglas Gregoref96ee02012-01-14 16:38:05 +00002181 if (Record->isInjectedClassName() || Record->getPreviousDecl())
Douglas Gregor2db32322009-10-07 23:56:10 +00002182 continue;
2183
Douglas Gregor0d035142009-10-27 18:42:08 +00002184 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2185 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002186
2187 if (MSInfo->getTemplateSpecializationKind()
2188 == TSK_ExplicitSpecialization)
2189 continue;
Nico Weberc956b6e2010-09-27 21:02:09 +00002190
Douglas Gregor0d035142009-10-27 18:42:08 +00002191 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2192 Record,
2193 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002194 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002195 SuppressNew) ||
2196 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002197 continue;
2198
Douglas Gregor0d035142009-10-27 18:42:08 +00002199 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2200 assert(Pattern && "Missing instantiated-from-template information");
2201
Douglas Gregor952b0172010-02-11 01:04:33 +00002202 if (!Record->getDefinition()) {
2203 if (!Pattern->getDefinition()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002204 // C++0x [temp.explicit]p8:
2205 // An explicit instantiation definition that names a class template
2206 // specialization explicitly instantiates the class template
2207 // specialization and is only an explicit instantiation definition
2208 // of members whose definition is visible at the point of
2209 // instantiation.
2210 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2211 MSInfo->setTemplateSpecializationKind(TSK);
2212 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2213 }
2214
2215 continue;
2216 }
2217
2218 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002219 TemplateArgs,
2220 TSK);
Nico Weberc956b6e2010-09-27 21:02:09 +00002221 } else {
2222 if (TSK == TSK_ExplicitInstantiationDefinition &&
2223 Record->getTemplateSpecializationKind() ==
2224 TSK_ExplicitInstantiationDeclaration) {
2225 Record->setTemplateSpecializationKind(TSK);
2226 MarkVTableUsed(PointOfInstantiation, Record, true);
2227 }
Douglas Gregor0d035142009-10-27 18:42:08 +00002228 }
Douglas Gregore9374d52009-10-08 01:19:17 +00002229
Douglas Gregor952b0172010-02-11 01:04:33 +00002230 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00002231 if (Pattern)
2232 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2233 TSK);
Douglas Gregora58861f2009-05-13 20:28:22 +00002234 }
2235 }
2236}
2237
2238/// \brief Instantiate the definitions of all of the members of the
2239/// given class template specialization, which was named as part of an
2240/// explicit instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +00002241void
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002242Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregora58861f2009-05-13 20:28:22 +00002243 SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002244 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2245 TemplateSpecializationKind TSK) {
Douglas Gregora58861f2009-05-13 20:28:22 +00002246 // C++0x [temp.explicit]p7:
2247 // An explicit instantiation that names a class template
2248 // specialization is an explicit instantion of the same kind
2249 // (declaration or definition) of each of its members (not
2250 // including members inherited from base classes) that has not
2251 // been previously explicitly specialized in the translation unit
2252 // containing the explicit instantiation, except as described
2253 // below.
2254 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002255 getTemplateInstantiationArgs(ClassTemplateSpec),
2256 TSK);
Douglas Gregora58861f2009-05-13 20:28:22 +00002257}
2258
John McCall60d7b3a2010-08-24 06:29:42 +00002259StmtResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002260Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor43959a92009-08-20 07:17:43 +00002261 if (!S)
2262 return Owned(S);
2263
2264 TemplateInstantiator Instantiator(*this, TemplateArgs,
2265 SourceLocation(),
2266 DeclarationName());
2267 return Instantiator.TransformStmt(S);
2268}
2269
John McCall60d7b3a2010-08-24 06:29:42 +00002270ExprResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002271Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorb98b1992009-08-11 05:31:07 +00002272 if (!E)
2273 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002274
Douglas Gregorb98b1992009-08-11 05:31:07 +00002275 TemplateInstantiator Instantiator(*this, TemplateArgs,
2276 SourceLocation(),
2277 DeclarationName());
2278 return Instantiator.TransformExpr(E);
2279}
2280
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002281bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2282 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002283 SmallVectorImpl<Expr *> &Outputs) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002284 if (NumExprs == 0)
2285 return false;
2286
2287 TemplateInstantiator Instantiator(*this, TemplateArgs,
2288 SourceLocation(),
2289 DeclarationName());
2290 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2291}
2292
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002293NestedNameSpecifierLoc
2294Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2295 const MultiLevelTemplateArgumentList &TemplateArgs) {
2296 if (!NNS)
2297 return NestedNameSpecifierLoc();
2298
2299 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2300 DeclarationName());
2301 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2302}
2303
Abramo Bagnara25777432010-08-11 22:01:17 +00002304/// \brief Do template substitution on declaration name info.
2305DeclarationNameInfo
2306Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2307 const MultiLevelTemplateArgumentList &TemplateArgs) {
2308 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2309 NameInfo.getName());
2310 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2311}
2312
Douglas Gregorde650ae2009-03-31 18:38:02 +00002313TemplateName
Douglas Gregor1d752d72011-03-02 18:46:51 +00002314Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2315 TemplateName Name, SourceLocation Loc,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002316 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord1067e52009-08-06 06:41:21 +00002317 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2318 DeclarationName());
Douglas Gregor1d752d72011-03-02 18:46:51 +00002319 CXXScopeSpec SS;
2320 SS.Adopt(QualifierLoc);
2321 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregorde650ae2009-03-31 18:38:02 +00002322}
Douglas Gregor91333002009-06-11 00:06:24 +00002323
Douglas Gregore02e2622010-12-22 21:19:48 +00002324bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2325 TemplateArgumentListInfo &Result,
John McCall833ca992009-10-29 08:12:44 +00002326 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor670444e2009-08-04 22:27:00 +00002327 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2328 DeclarationName());
Douglas Gregore02e2622010-12-22 21:19:48 +00002329
2330 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregor91333002009-06-11 00:06:24 +00002331}
Douglas Gregor895162d2010-04-30 18:55:50 +00002332
Douglas Gregor12c9c002011-01-07 16:43:16 +00002333llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2334LocalInstantiationScope::findInstantiationOf(const Decl *D) {
Chris Lattner57ad3782011-02-17 20:34:02 +00002335 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor895162d2010-04-30 18:55:50 +00002336 Current = Current->Outer) {
Chris Lattner57ad3782011-02-17 20:34:02 +00002337
Douglas Gregor895162d2010-04-30 18:55:50 +00002338 // Check if we found something within this scope.
Douglas Gregorebb1c562010-12-21 21:22:51 +00002339 const Decl *CheckD = D;
2340 do {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002341 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregorebb1c562010-12-21 21:22:51 +00002342 if (Found != Current->LocalDecls.end())
Douglas Gregor12c9c002011-01-07 16:43:16 +00002343 return &Found->second;
Douglas Gregorebb1c562010-12-21 21:22:51 +00002344
2345 // If this is a tag declaration, it's possible that we need to look for
2346 // a previous declaration.
2347 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregoref96ee02012-01-14 16:38:05 +00002348 CheckD = Tag->getPreviousDecl();
Douglas Gregorebb1c562010-12-21 21:22:51 +00002349 else
2350 CheckD = 0;
2351 } while (CheckD);
2352
Douglas Gregor895162d2010-04-30 18:55:50 +00002353 // If we aren't combined with our outer scope, we're done.
2354 if (!Current->CombineWithOuterScope)
2355 break;
2356 }
Chris Lattner57ad3782011-02-17 20:34:02 +00002357
2358 // If we didn't find the decl, then we either have a sema bug, or we have a
2359 // forward reference to a label declaration. Return null to indicate that
2360 // we have an uninstantiated label.
2361 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Douglas Gregor895162d2010-04-30 18:55:50 +00002362 return 0;
2363}
2364
John McCall2a7fb272010-08-25 05:32:35 +00002365void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002366 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregord3731192011-01-10 07:32:04 +00002367 if (Stored.isNull())
2368 Stored = Inst;
2369 else if (Stored.is<Decl *>()) {
2370 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2371 Stored = Inst;
2372 } else
2373 LocalDecls[D].get<DeclArgumentPack *>()->push_back(Inst);
Douglas Gregor895162d2010-04-30 18:55:50 +00002374}
Douglas Gregor12c9c002011-01-07 16:43:16 +00002375
2376void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2377 Decl *Inst) {
2378 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2379 Pack->push_back(Inst);
2380}
2381
2382void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2383 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2384 assert(Stored.isNull() && "Already instantiated this local");
2385 DeclArgumentPack *Pack = new DeclArgumentPack;
2386 Stored = Pack;
2387 ArgumentPacks.push_back(Pack);
2388}
2389
Douglas Gregord3731192011-01-10 07:32:04 +00002390void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2391 const TemplateArgument *ExplicitArgs,
2392 unsigned NumExplicitArgs) {
2393 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2394 "Already have a partially-substituted pack");
2395 assert((!PartiallySubstitutedPack
2396 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2397 "Wrong number of arguments in partially-substituted pack");
2398 PartiallySubstitutedPack = Pack;
2399 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2400 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2401}
2402
2403NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2404 const TemplateArgument **ExplicitArgs,
2405 unsigned *NumExplicitArgs) const {
2406 if (ExplicitArgs)
2407 *ExplicitArgs = 0;
2408 if (NumExplicitArgs)
2409 *NumExplicitArgs = 0;
2410
2411 for (const LocalInstantiationScope *Current = this; Current;
2412 Current = Current->Outer) {
2413 if (Current->PartiallySubstitutedPack) {
2414 if (ExplicitArgs)
2415 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2416 if (NumExplicitArgs)
2417 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2418
2419 return Current->PartiallySubstitutedPack;
2420 }
2421
2422 if (!Current->CombineWithOuterScope)
2423 break;
2424 }
2425
2426 return 0;
2427}