blob: 69e592ee2535cd675610a26126556b9124124893 [file] [log] [blame]
Douglas Gregorfe1e1102009-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 McCall83024632010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregord6ff3322009-08-04 16:50:30 +000014#include "TreeTransform.h"
John McCall8b0666c2010-08-20 18:27:03 +000015#include "clang/Sema/DeclSpec.h"
Richard Smith938f40b2011-06-11 17:19:42 +000016#include "clang/Sema/Initialization.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Lookup.h"
John McCallde6836a2010-08-24 07:21:54 +000018#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000019#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor28ad4b52009-05-26 20:50:29 +000020#include "clang/AST/ASTConsumer.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000021#include "clang/AST/ASTContext.h"
22#include "clang/AST/Expr.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000023#include "clang/AST/DeclTemplate.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000024#include "clang/Basic/LangOptions.h"
25
26using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000027using namespace sema;
Douglas Gregorfe1e1102009-02-27 19:31:52 +000028
Douglas Gregor4ea568f2009-03-10 18:03:33 +000029//===----------------------------------------------------------------------===/
30// Template Instantiation Support
31//===----------------------------------------------------------------------===/
32
Douglas Gregor01afeef2009-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 Gregor36d7c5f2009-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 Gregor8c702532010-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 Gregor1bd7a942010-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 Gregora654dd82009-08-28 17:37:35 +000050MultiLevelTemplateArgumentList
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000051Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor8c702532010-02-05 07:33:43 +000052 const TemplateArgumentList *Innermost,
Douglas Gregor1bd7a942010-05-03 23:29:10 +000053 bool RelativeToPrimary,
54 const FunctionDecl *Pattern) {
Douglas Gregora654dd82009-08-28 17:37:35 +000055 // Accumulate the set of template argument lists in this structure.
56 MultiLevelTemplateArgumentList Result;
Mike Stump11289f42009-09-09 15:08:12 +000057
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000058 if (Innermost)
59 Result.addOuterTemplateArguments(Innermost);
60
Douglas Gregora654dd82009-08-28 17:37:35 +000061 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregora51c9cc2011-05-22 00:21:10 +000062 if (!Ctx) {
Douglas Gregora654dd82009-08-28 17:37:35 +000063 Ctx = D->getDeclContext();
Douglas Gregora51c9cc2011-05-22 00:21:10 +000064
Douglas Gregor55462622011-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 Gregora51c9cc2011-05-22 00:21:10 +000079 }
80
John McCall970d5302009-08-29 03:16:09 +000081 while (!Ctx->isFileContext()) {
Douglas Gregora654dd82009-08-28 17:37:35 +000082 // Add template arguments from a class template instantiation.
Mike Stump11289f42009-09-09 15:08:12 +000083 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregora654dd82009-08-28 17:37:35 +000084 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
85 // We're done when we hit an explicit specialization.
Douglas Gregor9961ce92010-07-08 18:37:38 +000086 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
87 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregora654dd82009-08-28 17:37:35 +000088 break;
Mike Stump11289f42009-09-09 15:08:12 +000089
Douglas Gregora654dd82009-08-28 17:37:35 +000090 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorcf915552009-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 Stump11289f42009-09-09 15:08:12 +000097 }
Douglas Gregora654dd82009-08-28 17:37:35 +000098 // Add template arguments from a function template specialization.
John McCall970d5302009-08-29 03:16:09 +000099 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor8c702532010-02-05 07:33:43 +0000100 if (!RelativeToPrimary &&
101 Function->getTemplateSpecializationKind()
102 == TSK_ExplicitSpecialization)
Douglas Gregorcf915552009-10-13 16:30:37 +0000103 break;
104
Douglas Gregora654dd82009-08-28 17:37:35 +0000105 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorcf915552009-10-13 16:30:37 +0000106 = Function->getTemplateSpecializationArgs()) {
107 // Add the template arguments for this specialization.
Douglas Gregora654dd82009-08-28 17:37:35 +0000108 Result.addOuterTemplateArguments(TemplateArgs);
John McCall970d5302009-08-29 03:16:09 +0000109
Douglas Gregorcf915552009-10-13 16:30:37 +0000110 // If this function was instantiated from a specialized member that is
111 // a function template, we're done.
112 assert(Function->getPrimaryTemplate() && "No function template?");
113 if (Function->getPrimaryTemplate()->isMemberSpecialization())
114 break;
Douglas Gregor43669f82011-03-05 17:54:25 +0000115 } else if (FunctionTemplateDecl *FunTmpl
116 = Function->getDescribedFunctionTemplate()) {
117 // Add the "injected" template arguments.
118 std::pair<const TemplateArgument *, unsigned>
119 Injected = FunTmpl->getInjectedTemplateArgs();
120 Result.addOuterTemplateArguments(Injected.first, Injected.second);
Douglas Gregorcf915552009-10-13 16:30:37 +0000121 }
122
John McCall970d5302009-08-29 03:16:09 +0000123 // If this is a friend declaration and it declares an entity at
124 // namespace scope, take arguments from its lexical parent
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000125 // instead of its semantic parent, unless of course the pattern we're
126 // instantiating actually comes from the file's context!
John McCall970d5302009-08-29 03:16:09 +0000127 if (Function->getFriendObjectKind() &&
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000128 Function->getDeclContext()->isFileContext() &&
129 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCall970d5302009-08-29 03:16:09 +0000130 Ctx = Function->getLexicalDeclContext();
Douglas Gregor8c702532010-02-05 07:33:43 +0000131 RelativeToPrimary = false;
John McCall970d5302009-08-29 03:16:09 +0000132 continue;
133 }
Douglas Gregor9961ce92010-07-08 18:37:38 +0000134 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
135 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
136 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
137 const TemplateSpecializationType *TST
138 = cast<TemplateSpecializationType>(Context.getCanonicalType(T));
139 Result.addOuterTemplateArguments(TST->getArgs(), TST->getNumArgs());
140 if (ClassTemplate->isMemberSpecialization())
141 break;
142 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000143 }
John McCall970d5302009-08-29 03:16:09 +0000144
145 Ctx = Ctx->getParent();
Douglas Gregor8c702532010-02-05 07:33:43 +0000146 RelativeToPrimary = false;
Douglas Gregorb4850462009-05-14 23:26:13 +0000147 }
Mike Stump11289f42009-09-09 15:08:12 +0000148
Douglas Gregora654dd82009-08-28 17:37:35 +0000149 return Result;
Douglas Gregorb4850462009-05-14 23:26:13 +0000150}
151
Douglas Gregor84d49a22009-11-11 21:54:23 +0000152bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
153 switch (Kind) {
154 case TemplateInstantiation:
155 case DefaultTemplateArgumentInstantiation:
156 case DefaultFunctionArgumentInstantiation:
157 return true;
158
159 case ExplicitTemplateArgumentSubstitution:
160 case DeducedTemplateArgumentSubstitution:
161 case PriorTemplateArgumentSubstitution:
162 case DefaultTemplateArgumentChecking:
163 return false;
164 }
165
166 return true;
167}
168
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000169Sema::InstantiatingTemplate::
170InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregor85673582009-05-18 17:01:57 +0000171 Decl *Entity,
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000172 SourceRange InstantiationRange)
Douglas Gregoredb76852011-01-27 22:31:44 +0000173 : SemaRef(SemaRef),
174 SavedInNonInstantiationSFINAEContext(
175 SemaRef.InNonInstantiationSFINAEContext)
176{
Douglas Gregor79cf6032009-03-10 20:44:00 +0000177 Invalid = CheckInstantiationDepth(PointOfInstantiation,
178 InstantiationRange);
179 if (!Invalid) {
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000180 ActiveTemplateInstantiation Inst;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000181 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000182 Inst.PointOfInstantiation = PointOfInstantiation;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000183 Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
Douglas Gregorc9220832009-03-12 18:36:18 +0000184 Inst.TemplateArgs = 0;
185 Inst.NumTemplateArgs = 0;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000186 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000187 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000188 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor79cf6032009-03-10 20:44:00 +0000189 }
190}
191
Mike Stump11289f42009-09-09 15:08:12 +0000192Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000193 SourceLocation PointOfInstantiation,
194 TemplateDecl *Template,
195 const TemplateArgument *TemplateArgs,
196 unsigned NumTemplateArgs,
197 SourceRange InstantiationRange)
Douglas Gregoredb76852011-01-27 22:31:44 +0000198 : SemaRef(SemaRef),
199 SavedInNonInstantiationSFINAEContext(
200 SemaRef.InNonInstantiationSFINAEContext)
201{
Douglas Gregor79cf6032009-03-10 20:44:00 +0000202 Invalid = CheckInstantiationDepth(PointOfInstantiation,
203 InstantiationRange);
204 if (!Invalid) {
205 ActiveTemplateInstantiation Inst;
Mike Stump11289f42009-09-09 15:08:12 +0000206 Inst.Kind
Douglas Gregor79cf6032009-03-10 20:44:00 +0000207 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
208 Inst.PointOfInstantiation = PointOfInstantiation;
209 Inst.Entity = reinterpret_cast<uintptr_t>(Template);
210 Inst.TemplateArgs = TemplateArgs;
211 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000212 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000213 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000214 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000215 }
216}
217
Mike Stump11289f42009-09-09 15:08:12 +0000218Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregor637d9982009-06-10 23:47:09 +0000219 SourceLocation PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000220 FunctionTemplateDecl *FunctionTemplate,
221 const TemplateArgument *TemplateArgs,
222 unsigned NumTemplateArgs,
223 ActiveTemplateInstantiation::InstantiationKind Kind,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000224 sema::TemplateDeductionInfo &DeductionInfo,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000225 SourceRange InstantiationRange)
Douglas Gregoredb76852011-01-27 22:31:44 +0000226 : SemaRef(SemaRef),
227 SavedInNonInstantiationSFINAEContext(
228 SemaRef.InNonInstantiationSFINAEContext)
229{
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000230 Invalid = CheckInstantiationDepth(PointOfInstantiation,
231 InstantiationRange);
232 if (!Invalid) {
233 ActiveTemplateInstantiation Inst;
234 Inst.Kind = Kind;
235 Inst.PointOfInstantiation = PointOfInstantiation;
236 Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
237 Inst.TemplateArgs = TemplateArgs;
238 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000239 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000240 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000241 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000242 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor84d49a22009-11-11 21:54:23 +0000243
244 if (!Inst.isInstantiationRecord())
245 ++SemaRef.NonInstantiationEntries;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000246 }
247}
248
Mike Stump11289f42009-09-09 15:08:12 +0000249Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000250 SourceLocation PointOfInstantiation,
Douglas Gregor637d9982009-06-10 23:47:09 +0000251 ClassTemplatePartialSpecializationDecl *PartialSpec,
252 const TemplateArgument *TemplateArgs,
253 unsigned NumTemplateArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000254 sema::TemplateDeductionInfo &DeductionInfo,
Douglas Gregor637d9982009-06-10 23:47:09 +0000255 SourceRange InstantiationRange)
Douglas Gregoredb76852011-01-27 22:31:44 +0000256 : SemaRef(SemaRef),
257 SavedInNonInstantiationSFINAEContext(
258 SemaRef.InNonInstantiationSFINAEContext)
259{
Douglas Gregor84d49a22009-11-11 21:54:23 +0000260 Invalid = false;
261
262 ActiveTemplateInstantiation Inst;
263 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
264 Inst.PointOfInstantiation = PointOfInstantiation;
265 Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
266 Inst.TemplateArgs = TemplateArgs;
267 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000268 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000269 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000270 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000271 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
272
273 assert(!Inst.isInstantiationRecord());
274 ++SemaRef.NonInstantiationEntries;
Douglas Gregor637d9982009-06-10 23:47:09 +0000275}
276
Mike Stump11289f42009-09-09 15:08:12 +0000277Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000278 SourceLocation PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000279 ParmVarDecl *Param,
280 const TemplateArgument *TemplateArgs,
281 unsigned NumTemplateArgs,
282 SourceRange InstantiationRange)
Douglas Gregoredb76852011-01-27 22:31:44 +0000283 : SemaRef(SemaRef),
284 SavedInNonInstantiationSFINAEContext(
285 SemaRef.InNonInstantiationSFINAEContext)
286{
Douglas Gregore62e6a02009-11-11 19:13:48 +0000287 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Anders Carlsson657bad42009-09-05 05:14:19 +0000288
289 if (!Invalid) {
290 ActiveTemplateInstantiation Inst;
291 Inst.Kind
292 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
Douglas Gregore62e6a02009-11-11 19:13:48 +0000293 Inst.PointOfInstantiation = PointOfInstantiation;
Anders Carlsson657bad42009-09-05 05:14:19 +0000294 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
295 Inst.TemplateArgs = TemplateArgs;
296 Inst.NumTemplateArgs = NumTemplateArgs;
297 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000298 SemaRef.InNonInstantiationSFINAEContext = false;
Anders Carlsson657bad42009-09-05 05:14:19 +0000299 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000300 }
301}
302
303Sema::InstantiatingTemplate::
304InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorca4686d2011-01-04 23:35:54 +0000305 NamedDecl *Template,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000306 NonTypeTemplateParmDecl *Param,
307 const TemplateArgument *TemplateArgs,
308 unsigned NumTemplateArgs,
Douglas Gregoredb76852011-01-27 22:31:44 +0000309 SourceRange InstantiationRange)
310 : SemaRef(SemaRef),
311 SavedInNonInstantiationSFINAEContext(
312 SemaRef.InNonInstantiationSFINAEContext)
313{
Douglas Gregor84d49a22009-11-11 21:54:23 +0000314 Invalid = false;
Douglas Gregore62e6a02009-11-11 19:13:48 +0000315
Douglas Gregor84d49a22009-11-11 21:54:23 +0000316 ActiveTemplateInstantiation Inst;
317 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
318 Inst.PointOfInstantiation = PointOfInstantiation;
319 Inst.Template = Template;
320 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
321 Inst.TemplateArgs = TemplateArgs;
322 Inst.NumTemplateArgs = NumTemplateArgs;
323 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000324 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000325 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
326
327 assert(!Inst.isInstantiationRecord());
328 ++SemaRef.NonInstantiationEntries;
Douglas Gregore62e6a02009-11-11 19:13:48 +0000329}
330
331Sema::InstantiatingTemplate::
332InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorca4686d2011-01-04 23:35:54 +0000333 NamedDecl *Template,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000334 TemplateTemplateParmDecl *Param,
335 const TemplateArgument *TemplateArgs,
336 unsigned NumTemplateArgs,
Douglas Gregoredb76852011-01-27 22:31:44 +0000337 SourceRange InstantiationRange)
338 : SemaRef(SemaRef),
339 SavedInNonInstantiationSFINAEContext(
340 SemaRef.InNonInstantiationSFINAEContext)
341{
Douglas Gregor84d49a22009-11-11 21:54:23 +0000342 Invalid = false;
343 ActiveTemplateInstantiation Inst;
344 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
345 Inst.PointOfInstantiation = PointOfInstantiation;
346 Inst.Template = Template;
347 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
348 Inst.TemplateArgs = TemplateArgs;
349 Inst.NumTemplateArgs = NumTemplateArgs;
350 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000351 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000352 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000353
Douglas Gregor84d49a22009-11-11 21:54:23 +0000354 assert(!Inst.isInstantiationRecord());
355 ++SemaRef.NonInstantiationEntries;
356}
357
358Sema::InstantiatingTemplate::
359InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
360 TemplateDecl *Template,
361 NamedDecl *Param,
362 const TemplateArgument *TemplateArgs,
363 unsigned NumTemplateArgs,
Douglas Gregoredb76852011-01-27 22:31:44 +0000364 SourceRange InstantiationRange)
365 : SemaRef(SemaRef),
366 SavedInNonInstantiationSFINAEContext(
367 SemaRef.InNonInstantiationSFINAEContext)
368{
Douglas Gregor84d49a22009-11-11 21:54:23 +0000369 Invalid = false;
370
371 ActiveTemplateInstantiation Inst;
372 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
373 Inst.PointOfInstantiation = PointOfInstantiation;
374 Inst.Template = Template;
375 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
376 Inst.TemplateArgs = TemplateArgs;
377 Inst.NumTemplateArgs = NumTemplateArgs;
378 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000379 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000380 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
381
382 assert(!Inst.isInstantiationRecord());
383 ++SemaRef.NonInstantiationEntries;
Anders Carlsson657bad42009-09-05 05:14:19 +0000384}
385
Douglas Gregor85673582009-05-18 17:01:57 +0000386void Sema::InstantiatingTemplate::Clear() {
387 if (!Invalid) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000388 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
389 assert(SemaRef.NonInstantiationEntries > 0);
390 --SemaRef.NonInstantiationEntries;
391 }
Douglas Gregoredb76852011-01-27 22:31:44 +0000392 SemaRef.InNonInstantiationSFINAEContext
393 = SavedInNonInstantiationSFINAEContext;
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000394 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregor85673582009-05-18 17:01:57 +0000395 Invalid = true;
396 }
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000397}
398
Douglas Gregor79cf6032009-03-10 20:44:00 +0000399bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
400 SourceLocation PointOfInstantiation,
401 SourceRange InstantiationRange) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000402 assert(SemaRef.NonInstantiationEntries <=
403 SemaRef.ActiveTemplateInstantiations.size());
404 if ((SemaRef.ActiveTemplateInstantiations.size() -
405 SemaRef.NonInstantiationEntries)
406 <= SemaRef.getLangOptions().InstantiationDepth)
Douglas Gregor79cf6032009-03-10 20:44:00 +0000407 return false;
408
Mike Stump11289f42009-09-09 15:08:12 +0000409 SemaRef.Diag(PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000410 diag::err_template_recursion_depth_exceeded)
411 << SemaRef.getLangOptions().InstantiationDepth
412 << InstantiationRange;
413 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
414 << SemaRef.getLangOptions().InstantiationDepth;
415 return true;
416}
417
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000418/// \brief Prints the current instantiation stack through a series of
419/// notes.
420void Sema::PrintInstantiationStack() {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000421 // Determine which template instantiations to skip, if any.
422 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
423 unsigned Limit = Diags.getTemplateBacktraceLimit();
424 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
425 SkipStart = Limit / 2 + Limit % 2;
426 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
427 }
428
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000429 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000430 unsigned InstantiationIdx = 0;
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000431 for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
432 Active = ActiveTemplateInstantiations.rbegin(),
433 ActiveEnd = ActiveTemplateInstantiations.rend();
434 Active != ActiveEnd;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000435 ++Active, ++InstantiationIdx) {
436 // Skip this instantiation?
437 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
438 if (InstantiationIdx == SkipStart) {
439 // Note that we're skipping instantiations.
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000440 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000441 diag::note_instantiation_contexts_suppressed)
442 << unsigned(ActiveTemplateInstantiations.size() - Limit);
443 }
444 continue;
445 }
446
Douglas Gregor79cf6032009-03-10 20:44:00 +0000447 switch (Active->Kind) {
448 case ActiveTemplateInstantiation::TemplateInstantiation: {
Douglas Gregor85673582009-05-18 17:01:57 +0000449 Decl *D = reinterpret_cast<Decl *>(Active->Entity);
450 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
451 unsigned DiagID = diag::note_template_member_class_here;
452 if (isa<ClassTemplateSpecializationDecl>(Record))
453 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000454 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000455 << Context.getTypeDeclType(Record)
456 << Active->InstantiationRange;
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000457 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +0000458 unsigned DiagID;
459 if (Function->getPrimaryTemplate())
460 DiagID = diag::note_function_template_spec_here;
461 else
462 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000463 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000464 << Function
465 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000466 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000467 Diags.Report(Active->PointOfInstantiation,
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000468 diag::note_template_static_data_member_def_here)
Richard Smith3f1b5d02011-05-05 21:57:07 +0000469 << VD
470 << Active->InstantiationRange;
471 } else {
472 Diags.Report(Active->PointOfInstantiation,
473 diag::note_template_type_alias_instantiation_here)
474 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000475 << Active->InstantiationRange;
Douglas Gregor85673582009-05-18 17:01:57 +0000476 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000477 break;
478 }
479
480 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
481 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
482 std::string TemplateArgsStr
Douglas Gregordc572a32009-03-30 22:58:21 +0000483 = TemplateSpecializationType::PrintTemplateArgumentList(
Mike Stump11289f42009-09-09 15:08:12 +0000484 Active->TemplateArgs,
Douglas Gregor7de59662009-05-29 20:38:28 +0000485 Active->NumTemplateArgs,
486 Context.PrintingPolicy);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000487 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000488 diag::note_default_arg_instantiation_here)
489 << (Template->getNameAsString() + TemplateArgsStr)
490 << Active->InstantiationRange;
491 break;
492 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000493
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000494 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Mike Stump11289f42009-09-09 15:08:12 +0000495 FunctionTemplateDecl *FnTmpl
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000496 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000497 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000498 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000499 << FnTmpl
500 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
501 Active->TemplateArgs,
502 Active->NumTemplateArgs)
503 << Active->InstantiationRange;
Douglas Gregor637d9982009-06-10 23:47:09 +0000504 break;
505 }
Mike Stump11289f42009-09-09 15:08:12 +0000506
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000507 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
508 if (ClassTemplatePartialSpecializationDecl *PartialSpec
509 = dyn_cast<ClassTemplatePartialSpecializationDecl>(
510 (Decl *)Active->Entity)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000511 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000512 diag::note_partial_spec_deduct_instantiation_here)
513 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor607f1412010-03-30 20:35:20 +0000514 << getTemplateArgumentBindingsText(
515 PartialSpec->getTemplateParameters(),
516 Active->TemplateArgs,
517 Active->NumTemplateArgs)
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000518 << Active->InstantiationRange;
519 } else {
520 FunctionTemplateDecl *FnTmpl
521 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000522 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000523 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000524 << FnTmpl
525 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
526 Active->TemplateArgs,
527 Active->NumTemplateArgs)
528 << Active->InstantiationRange;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000529 }
530 break;
Douglas Gregor637d9982009-06-10 23:47:09 +0000531
Anders Carlsson657bad42009-09-05 05:14:19 +0000532 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
533 ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity);
534 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +0000535
Anders Carlsson657bad42009-09-05 05:14:19 +0000536 std::string TemplateArgsStr
537 = TemplateSpecializationType::PrintTemplateArgumentList(
Mike Stump11289f42009-09-09 15:08:12 +0000538 Active->TemplateArgs,
Anders Carlsson657bad42009-09-05 05:14:19 +0000539 Active->NumTemplateArgs,
540 Context.PrintingPolicy);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000541 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000542 diag::note_default_function_arg_instantiation_here)
Anders Carlssondc6d2c32009-09-05 05:38:54 +0000543 << (FD->getNameAsString() + TemplateArgsStr)
Anders Carlsson657bad42009-09-05 05:14:19 +0000544 << Active->InstantiationRange;
545 break;
546 }
Mike Stump11289f42009-09-09 15:08:12 +0000547
Douglas Gregore62e6a02009-11-11 19:13:48 +0000548 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
549 NamedDecl *Parm = cast<NamedDecl>((Decl *)Active->Entity);
550 std::string Name;
551 if (!Parm->getName().empty())
552 Name = std::string(" '") + Parm->getName().str() + "'";
Douglas Gregorca4686d2011-01-04 23:35:54 +0000553
554 TemplateParameterList *TemplateParams = 0;
555 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
556 TemplateParams = Template->getTemplateParameters();
557 else
558 TemplateParams =
559 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
560 ->getTemplateParameters();
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000561 Diags.Report(Active->PointOfInstantiation,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000562 diag::note_prior_template_arg_substitution)
563 << isa<TemplateTemplateParmDecl>(Parm)
564 << Name
Douglas Gregorca4686d2011-01-04 23:35:54 +0000565 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000566 Active->TemplateArgs,
567 Active->NumTemplateArgs)
568 << Active->InstantiationRange;
569 break;
570 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000571
572 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Douglas Gregorca4686d2011-01-04 23:35:54 +0000573 TemplateParameterList *TemplateParams = 0;
574 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
575 TemplateParams = Template->getTemplateParameters();
576 else
577 TemplateParams =
578 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
579 ->getTemplateParameters();
580
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000581 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000582 diag::note_template_default_arg_checking)
Douglas Gregorca4686d2011-01-04 23:35:54 +0000583 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000584 Active->TemplateArgs,
585 Active->NumTemplateArgs)
586 << Active->InstantiationRange;
587 break;
588 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000589 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000590 }
591}
592
Douglas Gregoredb76852011-01-27 22:31:44 +0000593llvm::Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregor33834512009-06-14 07:33:30 +0000594 using llvm::SmallVector;
Douglas Gregoredb76852011-01-27 22:31:44 +0000595 if (InNonInstantiationSFINAEContext)
596 return llvm::Optional<TemplateDeductionInfo *>(0);
597
Douglas Gregor33834512009-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 Gregor84d49a22009-11-11 21:54:23 +0000602 ++Active)
603 {
Douglas Gregor33834512009-06-14 07:33:30 +0000604 switch(Active->Kind) {
Anders Carlsson657bad42009-09-05 05:14:19 +0000605 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Douglas Gregoredb76852011-01-27 22:31:44 +0000606 case ActiveTemplateInstantiation::TemplateInstantiation:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000607 // This is a template instantiation, so there is no SFINAE.
Douglas Gregoredb76852011-01-27 22:31:44 +0000608 return llvm::Optional<TemplateDeductionInfo *>();
Mike Stump11289f42009-09-09 15:08:12 +0000609
Douglas Gregor33834512009-06-14 07:33:30 +0000610 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000611 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000612 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-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 Gregor33834512009-06-14 07:33:30 +0000616 break;
Mike Stump11289f42009-09-09 15:08:12 +0000617
Douglas Gregorff6cbdf2009-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 Gregor5bb5e4a2010-10-12 23:32:35 +0000622 assert(Active->DeductionInfo && "Missing deduction info pointer");
623 return Active->DeductionInfo;
Douglas Gregor33834512009-06-14 07:33:30 +0000624 }
625 }
626
Douglas Gregoredb76852011-01-27 22:31:44 +0000627 return llvm::Optional<TemplateDeductionInfo *>();
Douglas Gregor33834512009-06-14 07:33:30 +0000628}
629
Douglas Gregora8bac7f2011-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 Gregorfe1e1102009-02-27 19:31:52 +0000643//===----------------------------------------------------------------------===/
644// Template Instantiation for Types
645//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000646namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000647 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000648 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000649 SourceLocation Loc;
650 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000651
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000652 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000653 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000654
655 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000656 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000657 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000658 DeclarationName Entity)
659 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000660 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000661
Mike Stump11289f42009-09-09 15:08:12 +0000662 /// \brief Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-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 Gregor5597ab42010-05-07 23:12:07 +0000667 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000668
Douglas Gregord6ff3322009-08-04 16:50:30 +0000669 /// \brief Returns the location of the entity being instantiated, if known.
670 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000671
Douglas Gregord6ff3322009-08-04 16:50:30 +0000672 /// \brief Returns the name of the entity being instantiated, if any.
673 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000674
Douglas Gregoref6ab412009-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 Gregor840bd6c2010-12-20 22:05:00 +0000681
682 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
683 SourceRange PatternRange,
684 const UnexpandedParameterPack *Unexpanded,
685 unsigned NumUnexpanded,
686 bool &ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000687 bool &RetainExpansion,
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000688 llvm::Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000689 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
690 PatternRange, Unexpanded,
691 NumUnexpanded,
692 TemplateArgs,
693 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000694 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000695 NumExpansions);
696 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000697
Douglas Gregorf3010112011-01-07 16:43:16 +0000698 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
699 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
700 }
701
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000702 TemplateArgument ForgetPartiallySubstitutedPack() {
703 TemplateArgument Result;
704 if (NamedDecl *PartialPack
705 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
706 MultiLevelTemplateArgumentList &TemplateArgs
707 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
708 unsigned Depth, Index;
709 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
710 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
711 Result = TemplateArgs(Depth, Index);
712 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
713 }
714 }
715
716 return Result;
717 }
718
719 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
720 if (Arg.isNull())
721 return;
722
723 if (NamedDecl *PartialPack
724 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
725 MultiLevelTemplateArgumentList &TemplateArgs
726 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
727 unsigned Depth, Index;
728 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
729 TemplateArgs.setArgument(Depth, Index, Arg);
730 }
731 }
732
Douglas Gregord6ff3322009-08-04 16:50:30 +0000733 /// \brief Transform the given declaration by instantiating a reference to
734 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000735 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000736
Mike Stump11289f42009-09-09 15:08:12 +0000737 /// \brief Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000738 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000739 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000740
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000741 /// \bried Transform the first qualifier within a scope by instantiating the
742 /// declaration.
743 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
744
Douglas Gregorebe10102009-08-20 07:17:43 +0000745 /// \brief Rebuild the exception declaration and register the declaration
746 /// as an instantiated local.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000747 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000748 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000749 SourceLocation StartLoc,
750 SourceLocation NameLoc,
751 IdentifierInfo *Name);
Mike Stump11289f42009-09-09 15:08:12 +0000752
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000753 /// \brief Rebuild the Objective-C exception declaration and register the
754 /// declaration as an instantiated local.
755 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
756 TypeSourceInfo *TSInfo, QualType T);
757
John McCall7f41d982009-09-11 04:59:25 +0000758 /// \brief Check for tag mismatches when instantiating an
759 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000760 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
761 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000762 NestedNameSpecifierLoc QualifierLoc,
763 QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000764
Douglas Gregor9db53502011-03-02 18:07:45 +0000765 TemplateName TransformTemplateName(CXXScopeSpec &SS,
766 TemplateName Name,
767 SourceLocation NameLoc,
768 QualType ObjectType = QualType(),
769 NamedDecl *FirstQualifierInScope = 0);
770
John McCalldadc5752010-08-24 06:29:42 +0000771 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
772 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
773 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
774 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000775 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000776 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
777 SubstNonTypeTemplateParmPackExpr *E);
778
Douglas Gregor14cf7522010-04-30 18:55:50 +0000779 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000780 FunctionProtoTypeLoc TL);
Douglas Gregor715e4612011-01-14 22:40:04 +0000781 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +0000782 int indexAdjustment,
Douglas Gregor715e4612011-01-14 22:40:04 +0000783 llvm::Optional<unsigned> NumExpansions);
John McCall58f10c32010-03-11 09:03:00 +0000784
Mike Stump11289f42009-09-09 15:08:12 +0000785 /// \brief Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +0000786 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +0000787 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000788 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000789
Douglas Gregorada4b792011-01-14 02:55:32 +0000790 /// \brief Transforms an already-substituted template type parameter pack
791 /// into either itself (if we aren't substituting into its pack expansion)
792 /// or the appropriate substituted argument.
793 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
794 SubstTemplateTypeParmPackTypeLoc TL);
795
John McCalldadc5752010-08-24 06:29:42 +0000796 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000797 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCalldadc5752010-08-24 06:29:42 +0000798 ExprResult Result =
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000799 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
800 getSema().CallsUndergoingInstantiation.pop_back();
801 return move(Result);
802 }
Douglas Gregord6ff3322009-08-04 16:50:30 +0000803 };
Douglas Gregor04318252009-07-06 15:59:29 +0000804}
805
Douglas Gregor5597ab42010-05-07 23:12:07 +0000806bool TemplateInstantiator::AlreadyTransformed(QualType T) {
807 if (T.isNull())
808 return true;
809
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000810 if (T->isDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +0000811 return false;
812
813 getSema().MarkDeclarationsReferencedInType(Loc, T);
814 return true;
815}
816
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000817Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000818 if (!D)
819 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000820
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000821 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000822 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +0000823 // If the corresponding template argument is NULL or non-existent, it's
824 // because we are performing instantiation from explicitly-specified
825 // template arguments in a function template, but there were some
826 // arguments left unspecified.
827 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
828 TTP->getPosition()))
829 return D;
830
Douglas Gregorf5500772011-01-05 15:48:55 +0000831 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
832
833 if (TTP->isParameterPack()) {
834 assert(Arg.getKind() == TemplateArgument::Pack &&
835 "Missing argument pack");
836
Douglas Gregor5590be02011-01-15 06:45:20 +0000837 assert(getSema().ArgumentPackSubstitutionIndex >= 0);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000838 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregorf5500772011-01-05 15:48:55 +0000839 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
840 }
841
842 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000843 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +0000844 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000845 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +0000846 }
Mike Stump11289f42009-09-09 15:08:12 +0000847
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000848 // Fall through to find the instantiated declaration for this template
849 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +0000850 }
Mike Stump11289f42009-09-09 15:08:12 +0000851
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000852 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000853}
854
Douglas Gregor25289362010-03-01 17:25:41 +0000855Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +0000856 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +0000857 if (!Inst)
858 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000859
Douglas Gregorebe10102009-08-20 07:17:43 +0000860 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
861 return Inst;
862}
863
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000864NamedDecl *
865TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
866 SourceLocation Loc) {
867 // If the first part of the nested-name-specifier was a template type
868 // parameter, instantiate that type parameter down to a tag type.
869 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
870 const TemplateTypeParmType *TTP
871 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000872
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000873 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000874 // FIXME: This needs testing w/ member access expressions.
875 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
876
877 if (TTP->isParameterPack()) {
878 assert(Arg.getKind() == TemplateArgument::Pack &&
879 "Missing argument pack");
880
Douglas Gregore1d60df2011-01-14 23:41:42 +0000881 if (getSema().ArgumentPackSubstitutionIndex == -1)
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000882 return 0;
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000883
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000884 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000885 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
886 }
887
888 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000889 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000890 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000891
892 if (const TagType *Tag = T->getAs<TagType>())
893 return Tag->getDecl();
894
895 // The resulting type is not a tag; complain.
896 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
897 return 0;
898 }
899 }
900
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000901 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000902}
903
Douglas Gregorebe10102009-08-20 07:17:43 +0000904VarDecl *
905TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000906 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000907 SourceLocation StartLoc,
908 SourceLocation NameLoc,
909 IdentifierInfo *Name) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000910 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000911 StartLoc, NameLoc, Name);
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000912 if (Var)
913 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
914 return Var;
915}
916
917VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
918 TypeSourceInfo *TSInfo,
919 QualType T) {
920 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
921 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +0000922 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
923 return Var;
924}
925
John McCall7f41d982009-09-11 04:59:25 +0000926QualType
John McCall954b5de2010-11-04 19:04:38 +0000927TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
928 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000929 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara6150c882010-05-11 21:36:43 +0000930 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +0000931 if (const TagType *TT = T->getAs<TagType>()) {
932 TagDecl* TD = TT->getDecl();
933
John McCall954b5de2010-11-04 19:04:38 +0000934 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +0000935
936 // FIXME: type might be anonymous.
937 IdentifierInfo *Id = TD->getIdentifier();
938
939 // TODO: should we even warn on struct/class mismatches for this? Seems
940 // like it's likely to produce a lot of spurious errors.
Abramo Bagnara6150c882010-05-11 21:36:43 +0000941 if (Keyword != ETK_None && Keyword != ETK_Typename) {
942 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieucaa33d32011-06-10 03:11:26 +0000943 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
944 TagLocation, *Id)) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000945 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
946 << Id
947 << FixItHint::CreateReplacement(SourceRange(TagLocation),
948 TD->getKindName());
949 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
950 }
John McCall7f41d982009-09-11 04:59:25 +0000951 }
952 }
953
John McCall954b5de2010-11-04 19:04:38 +0000954 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
955 Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000956 QualifierLoc,
957 T);
John McCall7f41d982009-09-11 04:59:25 +0000958}
959
Douglas Gregor9db53502011-03-02 18:07:45 +0000960TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
961 TemplateName Name,
962 SourceLocation NameLoc,
963 QualType ObjectType,
964 NamedDecl *FirstQualifierInScope) {
965 if (TemplateTemplateParmDecl *TTP
966 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
967 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
968 // If the corresponding template argument is NULL or non-existent, it's
969 // because we are performing instantiation from explicitly-specified
970 // template arguments in a function template, but there were some
971 // arguments left unspecified.
972 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
973 TTP->getPosition()))
974 return Name;
975
976 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
977
978 if (TTP->isParameterPack()) {
979 assert(Arg.getKind() == TemplateArgument::Pack &&
980 "Missing argument pack");
981
982 if (getSema().ArgumentPackSubstitutionIndex == -1) {
983 // We have the template argument pack to substitute, but we're not
984 // actually expanding the enclosing pack expansion yet. So, just
985 // keep the entire argument pack.
986 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
987 }
988
989 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
990 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
991 }
992
993 TemplateName Template = Arg.getAsTemplate();
Richard Smith3f1b5d02011-05-05 21:57:07 +0000994 assert(!Template.isNull() && "Null template template argument");
Douglas Gregor9d9f8db2011-03-05 20:06:51 +0000995
996 // We don't ever want to substitute for a qualified template name, since
997 // the qualifier is handled separately. So, look through the qualified
998 // template name to its underlying declaration.
999 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1000 Template = TemplateName(QTN->getTemplateDecl());
1001
Douglas Gregor9db53502011-03-02 18:07:45 +00001002 return Template;
1003 }
1004 }
1005
1006 if (SubstTemplateTemplateParmPackStorage *SubstPack
1007 = Name.getAsSubstTemplateTemplateParmPack()) {
1008 if (getSema().ArgumentPackSubstitutionIndex == -1)
1009 return Name;
1010
1011 const TemplateArgument &ArgPack = SubstPack->getArgumentPack();
1012 assert(getSema().ArgumentPackSubstitutionIndex < (int)ArgPack.pack_size() &&
1013 "Pack substitution index out-of-range");
1014 return ArgPack.pack_begin()[getSema().ArgumentPackSubstitutionIndex]
1015 .getAsTemplate();
1016 }
1017
1018 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1019 FirstQualifierInScope);
1020}
1021
John McCalldadc5752010-08-24 06:29:42 +00001022ExprResult
John McCall47f29ea2009-12-08 09:21:05 +00001023TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +00001024 if (!E->isTypeDependent())
John McCallc3007a22010-10-26 07:05:15 +00001025 return SemaRef.Owned(E);
Anders Carlsson0b209a82009-09-11 01:22:35 +00001026
1027 FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
1028 assert(currentDecl && "Must have current function declaration when "
1029 "instantiating.");
1030
1031 PredefinedExpr::IdentType IT = E->getIdentType();
1032
Anders Carlsson5bd8d192010-02-11 18:20:28 +00001033 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001034
1035 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00001036 QualType ResTy = getSema().Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001037 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
1038 ArrayType::Normal, 0);
1039 PredefinedExpr *PE =
1040 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
1041 return getSema().Owned(PE);
1042}
1043
John McCalldadc5752010-08-24 06:29:42 +00001044ExprResult
John McCall13481c52010-02-06 08:42:39 +00001045TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001046 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +00001047 // If the corresponding template argument is NULL or non-existent, it's
1048 // because we are performing instantiation from explicitly-specified
1049 // template arguments in a function template, but there were some
1050 // arguments left unspecified.
1051 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1052 NTTP->getPosition()))
John McCallc3007a22010-10-26 07:05:15 +00001053 return SemaRef.Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00001054
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001055 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1056 if (NTTP->isParameterPack()) {
1057 assert(Arg.getKind() == TemplateArgument::Pack &&
1058 "Missing argument pack");
1059
1060 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001061 // We have an argument pack, but we can't select a particular argument
1062 // out of it yet. Therefore, we'll build an expression to hold on to that
1063 // argument pack.
1064 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1065 E->getLocation(),
1066 NTTP->getDeclName());
1067 if (TargetType.isNull())
1068 return ExprError();
1069
1070 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1071 NTTP,
1072 E->getLocation(),
1073 Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001074 }
1075
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001076 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001077 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1078 }
Mike Stump11289f42009-09-09 15:08:12 +00001079
John McCall13481c52010-02-06 08:42:39 +00001080 // The template argument itself might be an expression, in which
1081 // case we just return that expression.
1082 if (Arg.getKind() == TemplateArgument::Expression)
John McCallc3007a22010-10-26 07:05:15 +00001083 return SemaRef.Owned(Arg.getAsExpr());
Mike Stump11289f42009-09-09 15:08:12 +00001084
John McCall13481c52010-02-06 08:42:39 +00001085 if (Arg.getKind() == TemplateArgument::Declaration) {
1086 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001087
John McCall15dda372010-02-06 10:23:53 +00001088 // Find the instantiation of the template argument. This is
1089 // required for nested templates.
John McCall13481c52010-02-06 08:42:39 +00001090 VD = cast_or_null<ValueDecl>(
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001091 getSema().FindInstantiatedDecl(E->getLocation(),
1092 VD, TemplateArgs));
John McCall13481c52010-02-06 08:42:39 +00001093 if (!VD)
John McCallfaf5fb42010-08-26 23:41:50 +00001094 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001095
John McCall15dda372010-02-06 10:23:53 +00001096 // Derive the type we want the substituted decl to have. This had
1097 // better be non-dependent, or these checks will have serious problems.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001098 QualType TargetType;
1099 if (NTTP->isExpandedParameterPack())
1100 TargetType = NTTP->getExpansionType(
1101 getSema().ArgumentPackSubstitutionIndex);
1102 else if (NTTP->isParameterPack() &&
1103 isa<PackExpansionType>(NTTP->getType())) {
1104 TargetType = SemaRef.SubstType(
1105 cast<PackExpansionType>(NTTP->getType())->getPattern(),
1106 TemplateArgs, E->getLocation(),
1107 NTTP->getDeclName());
1108 } else
1109 TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1110 E->getLocation(), NTTP->getDeclName());
John McCall15dda372010-02-06 10:23:53 +00001111 assert(!TargetType.isNull() && "type substitution failed for param type");
1112 assert(!TargetType->isDependentType() && "param type still dependent");
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001113 return SemaRef.BuildExpressionFromDeclTemplateArgument(Arg,
1114 TargetType,
1115 E->getLocation());
John McCall13481c52010-02-06 08:42:39 +00001116 }
1117
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001118 return SemaRef.BuildExpressionFromIntegralTemplateArgument(Arg,
1119 E->getSourceRange().getBegin());
John McCall13481c52010-02-06 08:42:39 +00001120}
1121
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001122ExprResult
1123TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1124 SubstNonTypeTemplateParmPackExpr *E) {
1125 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1126 // We aren't expanding the parameter pack, so just return ourselves.
1127 return getSema().Owned(E);
1128 }
1129
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001130 const TemplateArgument &ArgPack = E->getArgumentPack();
1131 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1132 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1133
1134 const TemplateArgument &Arg = ArgPack.pack_begin()[Index];
1135 if (Arg.getKind() == TemplateArgument::Expression)
1136 return SemaRef.Owned(Arg.getAsExpr());
1137
1138 if (Arg.getKind() == TemplateArgument::Declaration) {
1139 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
1140
1141 // Find the instantiation of the template argument. This is
1142 // required for nested templates.
1143 VD = cast_or_null<ValueDecl>(
1144 getSema().FindInstantiatedDecl(E->getParameterPackLocation(),
1145 VD, TemplateArgs));
1146 if (!VD)
1147 return ExprError();
1148
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001149 QualType T;
1150 NonTypeTemplateParmDecl *NTTP = E->getParameterPack();
1151 if (NTTP->isExpandedParameterPack())
1152 T = NTTP->getExpansionType(getSema().ArgumentPackSubstitutionIndex);
1153 else if (const PackExpansionType *Expansion
1154 = dyn_cast<PackExpansionType>(NTTP->getType()))
1155 T = SemaRef.SubstType(Expansion->getPattern(), TemplateArgs,
1156 E->getParameterPackLocation(), NTTP->getDeclName());
1157 else
1158 T = E->getType();
1159 return SemaRef.BuildExpressionFromDeclTemplateArgument(Arg, T,
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001160 E->getParameterPackLocation());
1161 }
1162
1163 return SemaRef.BuildExpressionFromIntegralTemplateArgument(Arg,
1164 E->getParameterPackLocation());
1165}
John McCall13481c52010-02-06 08:42:39 +00001166
John McCalldadc5752010-08-24 06:29:42 +00001167ExprResult
John McCall13481c52010-02-06 08:42:39 +00001168TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1169 NamedDecl *D = E->getDecl();
1170 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1171 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1172 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor954de172009-10-31 17:21:17 +00001173
1174 // We have a non-type template parameter that isn't fully substituted;
1175 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001176 }
Mike Stump11289f42009-09-09 15:08:12 +00001177
John McCall47f29ea2009-12-08 09:21:05 +00001178 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001179}
1180
John McCalldadc5752010-08-24 06:29:42 +00001181ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001182 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001183 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1184 getDescribedFunctionTemplate() &&
1185 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001186 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1187 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1188 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001189}
1190
Douglas Gregor14cf7522010-04-30 18:55:50 +00001191QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001192 FunctionProtoTypeLoc TL) {
Douglas Gregor14cf7522010-04-30 18:55:50 +00001193 // We need a local instantiation scope for this function prototype.
John McCall19c1bfd2010-08-25 05:32:35 +00001194 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
John McCall31f82722010-11-12 08:19:04 +00001195 return inherited::TransformFunctionProtoType(TLB, TL);
John McCall58f10c32010-03-11 09:03:00 +00001196}
1197
1198ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001199TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001200 int indexAdjustment,
Douglas Gregor715e4612011-01-14 22:40:04 +00001201 llvm::Optional<unsigned> NumExpansions) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001202 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregor715e4612011-01-14 22:40:04 +00001203 NumExpansions);
John McCall58f10c32010-03-11 09:03:00 +00001204}
1205
Mike Stump11289f42009-09-09 15:08:12 +00001206QualType
John McCall550e0c22009-10-21 00:40:46 +00001207TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001208 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001209 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001210 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001211 // Replace the template type parameter with its corresponding
1212 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001213
1214 // If the corresponding template argument is NULL or doesn't exist, it's
1215 // because we are performing instantiation from explicitly-specified
1216 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001217 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001218 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1219 TemplateTypeParmTypeLoc NewTL
1220 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1221 NewTL.setNameLoc(TL.getNameLoc());
1222 return TL.getType();
1223 }
Mike Stump11289f42009-09-09 15:08:12 +00001224
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001225 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1226
1227 if (T->isParameterPack()) {
1228 assert(Arg.getKind() == TemplateArgument::Pack &&
1229 "Missing argument pack");
1230
1231 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001232 // We have the template argument pack, but we're not expanding the
1233 // enclosing pack expansion yet. Just save the template argument
1234 // pack for later substitution.
1235 QualType Result
1236 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1237 SubstTemplateTypeParmPackTypeLoc NewTL
1238 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1239 NewTL.setNameLoc(TL.getNameLoc());
1240 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001241 }
1242
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001243 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001244 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1245 }
1246
1247 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001248 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001249
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001250 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001251
1252 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001253 QualType Result
1254 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1255 SubstTemplateTypeParmTypeLoc NewTL
1256 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1257 NewTL.setNameLoc(TL.getNameLoc());
1258 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001259 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001260
1261 // The template type parameter comes from an inner template (e.g.,
1262 // the template parameter list of a member template inside the
1263 // template we are instantiating). Create a new template type
1264 // parameter with the template "level" reduced by one.
Chandler Carruth08836322011-05-01 00:51:33 +00001265 TemplateTypeParmDecl *NewTTPDecl = 0;
1266 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1267 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1268 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1269
John McCall550e0c22009-10-21 00:40:46 +00001270 QualType Result
1271 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1272 - TemplateArgs.getNumLevels(),
1273 T->getIndex(),
1274 T->isParameterPack(),
Chandler Carruth08836322011-05-01 00:51:33 +00001275 NewTTPDecl);
John McCall550e0c22009-10-21 00:40:46 +00001276 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1277 NewTL.setNameLoc(TL.getNameLoc());
1278 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001279}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001280
Douglas Gregorada4b792011-01-14 02:55:32 +00001281QualType
1282TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1283 TypeLocBuilder &TLB,
1284 SubstTemplateTypeParmPackTypeLoc TL) {
1285 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1286 // We aren't expanding the parameter pack, so just return ourselves.
1287 SubstTemplateTypeParmPackTypeLoc NewTL
1288 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1289 NewTL.setNameLoc(TL.getNameLoc());
1290 return TL.getType();
1291 }
1292
1293 const TemplateArgument &ArgPack = TL.getTypePtr()->getArgumentPack();
1294 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1295 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1296
1297 QualType Result = ArgPack.pack_begin()[Index].getAsType();
1298 Result = getSema().Context.getSubstTemplateTypeParmType(
1299 TL.getTypePtr()->getReplacedParameter(),
1300 Result);
1301 SubstTemplateTypeParmTypeLoc NewTL
1302 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1303 NewTL.setNameLoc(TL.getNameLoc());
1304 return Result;
1305}
1306
John McCall76d824f2009-08-25 22:02:44 +00001307/// \brief Perform substitution on the type T with a given set of template
1308/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001309///
1310/// This routine substitutes the given template arguments into the
1311/// type T and produces the instantiated type.
1312///
1313/// \param T the type into which the template arguments will be
1314/// substituted. If this type is not dependent, it will be returned
1315/// immediately.
1316///
1317/// \param TemplateArgs the template arguments that will be
1318/// substituted for the top-level template parameters within T.
1319///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001320/// \param Loc the location in the source code where this substitution
1321/// is being performed. It will typically be the location of the
1322/// declarator (if we're instantiating the type of some declaration)
1323/// or the location of the type in the source code (if, e.g., we're
1324/// instantiating the type of a cast expression).
1325///
1326/// \param Entity the name of the entity associated with a declaration
1327/// being instantiated (if any). May be empty to indicate that there
1328/// is no such entity (if, e.g., this is a type that occurs as part of
1329/// a cast expression) or that the entity has no name (e.g., an
1330/// unnamed function parameter).
1331///
1332/// \returns If the instantiation succeeds, the instantiated
1333/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001334TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001335 const MultiLevelTemplateArgumentList &Args,
1336 SourceLocation Loc,
1337 DeclarationName Entity) {
1338 assert(!ActiveTemplateInstantiations.empty() &&
1339 "Cannot perform an instantiation without some context on the "
1340 "instantiation stack");
1341
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001342 if (!T->getType()->isDependentType() &&
1343 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001344 return T;
1345
1346 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1347 return Instantiator.TransformType(T);
1348}
1349
Douglas Gregor5499af42011-01-05 23:12:31 +00001350TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1351 const MultiLevelTemplateArgumentList &Args,
1352 SourceLocation Loc,
1353 DeclarationName Entity) {
1354 assert(!ActiveTemplateInstantiations.empty() &&
1355 "Cannot perform an instantiation without some context on the "
1356 "instantiation stack");
1357
1358 if (TL.getType().isNull())
1359 return 0;
1360
1361 if (!TL.getType()->isDependentType() &&
1362 !TL.getType()->isVariablyModifiedType()) {
1363 // FIXME: Make a copy of the TypeLoc data here, so that we can
1364 // return a new TypeSourceInfo. Inefficient!
1365 TypeLocBuilder TLB;
1366 TLB.pushFullCopy(TL);
1367 return TLB.getTypeSourceInfo(Context, TL.getType());
1368 }
1369
1370 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1371 TypeLocBuilder TLB;
1372 TLB.reserve(TL.getFullDataSize());
1373 QualType Result = Instantiator.TransformType(TLB, TL);
1374 if (Result.isNull())
1375 return 0;
1376
1377 return TLB.getTypeSourceInfo(Context, Result);
1378}
1379
John McCall609459e2009-10-21 00:58:09 +00001380/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001381QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001382 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001383 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregor79cf6032009-03-10 20:44:00 +00001384 assert(!ActiveTemplateInstantiations.empty() &&
1385 "Cannot perform an instantiation without some context on the "
1386 "instantiation stack");
1387
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001388 // If T is not a dependent type or a variably-modified type, there
1389 // is nothing to do.
1390 if (!T->isDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001391 return T;
1392
Douglas Gregord6ff3322009-08-04 16:50:30 +00001393 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1394 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001395}
Douglas Gregor463421d2009-03-03 04:44:36 +00001396
John McCallb29f78f2010-04-09 17:38:44 +00001397static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001398 if (T->getType()->isDependentType() || T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001399 return true;
1400
Abramo Bagnara6d810632010-12-14 22:11:44 +00001401 TypeLoc TL = T->getTypeLoc().IgnoreParens();
John McCallb29f78f2010-04-09 17:38:44 +00001402 if (!isa<FunctionProtoTypeLoc>(TL))
1403 return false;
1404
1405 FunctionProtoTypeLoc FP = cast<FunctionProtoTypeLoc>(TL);
1406 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1407 ParmVarDecl *P = FP.getArg(I);
1408
Douglas Gregora7203e52011-05-09 20:45:16 +00001409 // The parameter's type as written might be dependent even if the
1410 // decayed type was not dependent.
1411 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
1412 if (TSInfo->getType()->isDependentType())
1413 return true;
1414
John McCallb29f78f2010-04-09 17:38:44 +00001415 // TODO: currently we always rebuild expressions. When we
1416 // properly get lazier about this, we should use the same
1417 // logic to avoid rebuilding prototypes here.
Douglas Gregor9cc278222011-01-05 21:14:17 +00001418 if (P->hasDefaultArg())
John McCallb29f78f2010-04-09 17:38:44 +00001419 return true;
1420 }
1421
1422 return false;
1423}
1424
1425/// A form of SubstType intended specifically for instantiating the
1426/// type of a FunctionDecl. Its purpose is solely to force the
1427/// instantiation of default-argument expressions.
1428TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1429 const MultiLevelTemplateArgumentList &Args,
1430 SourceLocation Loc,
1431 DeclarationName Entity) {
1432 assert(!ActiveTemplateInstantiations.empty() &&
1433 "Cannot perform an instantiation without some context on the "
1434 "instantiation stack");
1435
1436 if (!NeedsInstantiationAsFunctionType(T))
1437 return T;
1438
1439 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1440
1441 TypeLocBuilder TLB;
1442
1443 TypeLoc TL = T->getTypeLoc();
1444 TLB.reserve(TL.getFullDataSize());
1445
John McCall31f82722010-11-12 08:19:04 +00001446 QualType Result = Instantiator.TransformType(TLB, TL);
John McCallb29f78f2010-04-09 17:38:44 +00001447 if (Result.isNull())
1448 return 0;
1449
1450 return TLB.getTypeSourceInfo(Context, Result);
1451}
1452
Douglas Gregor940bca72010-04-12 07:48:19 +00001453ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001454 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall8fb0d9d2011-05-01 22:35:37 +00001455 int indexAdjustment,
Douglas Gregor715e4612011-01-14 22:40:04 +00001456 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001457 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Douglas Gregor5499af42011-01-05 23:12:31 +00001458 TypeSourceInfo *NewDI = 0;
1459
Douglas Gregor5499af42011-01-05 23:12:31 +00001460 TypeLoc OldTL = OldDI->getTypeLoc();
1461 if (isa<PackExpansionTypeLoc>(OldTL)) {
1462 PackExpansionTypeLoc ExpansionTL = cast<PackExpansionTypeLoc>(OldTL);
Douglas Gregor5499af42011-01-05 23:12:31 +00001463
1464 // We have a function parameter pack. Substitute into the pattern of the
1465 // expansion.
1466 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1467 OldParm->getLocation(), OldParm->getDeclName());
1468 if (!NewDI)
1469 return 0;
1470
1471 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1472 // We still have unexpanded parameter packs, which means that
1473 // our function parameter is still a function parameter pack.
1474 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001475 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001476 NumExpansions);
Douglas Gregor5499af42011-01-05 23:12:31 +00001477 }
1478 } else {
1479 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1480 OldParm->getDeclName());
1481 }
1482
Douglas Gregor940bca72010-04-12 07:48:19 +00001483 if (!NewDI)
1484 return 0;
1485
1486 if (NewDI->getType()->isVoidType()) {
1487 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1488 return 0;
1489 }
1490
1491 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001492 OldParm->getInnerLocStart(),
Douglas Gregor940bca72010-04-12 07:48:19 +00001493 OldParm->getLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001494 OldParm->getIdentifier(),
1495 NewDI->getType(), NewDI,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001496 OldParm->getStorageClass(),
1497 OldParm->getStorageClassAsWritten());
Douglas Gregor940bca72010-04-12 07:48:19 +00001498 if (!NewParm)
1499 return 0;
Douglas Gregor6044d692010-05-19 17:02:24 +00001500
Douglas Gregor940bca72010-04-12 07:48:19 +00001501 // Mark the (new) default argument as uninstantiated (if any).
1502 if (OldParm->hasUninstantiatedDefaultArg()) {
1503 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1504 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001505 } else if (OldParm->hasUnparsedDefaultArg()) {
1506 NewParm->setUnparsedDefaultArg();
1507 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Douglas Gregor940bca72010-04-12 07:48:19 +00001508 } else if (Expr *Arg = OldParm->getDefaultArg())
1509 NewParm->setUninstantiatedDefaultArg(Arg);
1510
1511 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1512
Douglas Gregor5499af42011-01-05 23:12:31 +00001513 // FIXME: When OldParm is a parameter pack and NewParm is not a parameter
1514 // pack, we actually have a set of instantiated locations. Maintain this set!
Douglas Gregorf3010112011-01-07 16:43:16 +00001515 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1516 // Add the new parameter to
1517 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1518 } else {
1519 // Introduce an Old -> New mapping
Douglas Gregor5499af42011-01-05 23:12:31 +00001520 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001521 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001522
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001523 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1524 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001525 NewParm->setDeclContext(CurContext);
John McCall8fb0d9d2011-05-01 22:35:37 +00001526
1527 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1528 OldParm->getFunctionScopeIndex() + indexAdjustment);
Fariborz Jahaniana6c7efe2010-07-13 20:05:58 +00001529
Douglas Gregor940bca72010-04-12 07:48:19 +00001530 return NewParm;
1531}
1532
Douglas Gregordd472162011-01-07 00:20:55 +00001533/// \brief Substitute the given template arguments into the given set of
1534/// parameters, producing the set of parameter types that would be generated
1535/// from such a substitution.
1536bool Sema::SubstParmTypes(SourceLocation Loc,
1537 ParmVarDecl **Params, unsigned NumParams,
1538 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregorf3010112011-01-07 16:43:16 +00001539 llvm::SmallVectorImpl<QualType> &ParamTypes,
1540 llvm::SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregordd472162011-01-07 00:20:55 +00001541 assert(!ActiveTemplateInstantiations.empty() &&
1542 "Cannot perform an instantiation without some context on the "
1543 "instantiation stack");
1544
1545 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1546 DeclarationName());
1547 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
Douglas Gregorf3010112011-01-07 16:43:16 +00001548 ParamTypes, OutParams);
Douglas Gregordd472162011-01-07 00:20:55 +00001549}
1550
John McCall76d824f2009-08-25 22:02:44 +00001551/// \brief Perform substitution on the base class specifiers of the
1552/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001553///
1554/// Produces a diagnostic and returns true on error, returns false and
1555/// attaches the instantiated base classes to the class template
1556/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001557bool
John McCall76d824f2009-08-25 22:02:44 +00001558Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1559 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001560 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001561 bool Invalid = false;
Douglas Gregor6181ded2009-05-29 18:27:38 +00001562 llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Mike Stump11289f42009-09-09 15:08:12 +00001563 for (ClassTemplateSpecializationDecl::base_class_iterator
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001564 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
Douglas Gregor2a72edd2009-03-10 18:52:44 +00001565 Base != BaseEnd; ++Base) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001566 if (!Base->getType()->isDependentType()) {
Fariborz Jahanian5c14ec32009-07-22 17:41:53 +00001567 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001568 continue;
1569 }
1570
Douglas Gregor752a5952011-01-03 22:36:02 +00001571 SourceLocation EllipsisLoc;
Douglas Gregorc52264e2011-03-02 02:04:06 +00001572 TypeSourceInfo *BaseTypeLoc;
Douglas Gregor752a5952011-01-03 22:36:02 +00001573 if (Base->isPackExpansion()) {
1574 // This is a pack expansion. See whether we should expand it now, or
1575 // wait until later.
1576 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1577 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1578 Unexpanded);
1579 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001580 bool RetainExpansion = false;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001581 llvm::Optional<unsigned> NumExpansions;
Douglas Gregor752a5952011-01-03 22:36:02 +00001582 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1583 Base->getSourceRange(),
1584 Unexpanded.data(), Unexpanded.size(),
1585 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001586 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001587 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001588 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001589 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001590 }
1591
1592 // If we should expand this pack expansion now, do so.
1593 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001594 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001595 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1596
1597 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1598 TemplateArgs,
1599 Base->getSourceRange().getBegin(),
1600 DeclarationName());
1601 if (!BaseTypeLoc) {
1602 Invalid = true;
1603 continue;
1604 }
1605
1606 if (CXXBaseSpecifier *InstantiatedBase
1607 = CheckBaseSpecifier(Instantiation,
1608 Base->getSourceRange(),
1609 Base->isVirtual(),
1610 Base->getAccessSpecifierAsWritten(),
1611 BaseTypeLoc,
1612 SourceLocation()))
1613 InstantiatedBases.push_back(InstantiatedBase);
1614 else
1615 Invalid = true;
1616 }
1617
1618 continue;
1619 }
1620
1621 // The resulting base specifier will (still) be a pack expansion.
1622 EllipsisLoc = Base->getEllipsisLoc();
Douglas Gregorc52264e2011-03-02 02:04:06 +00001623 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1624 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1625 TemplateArgs,
1626 Base->getSourceRange().getBegin(),
1627 DeclarationName());
1628 } else {
1629 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1630 TemplateArgs,
1631 Base->getSourceRange().getBegin(),
1632 DeclarationName());
Douglas Gregor752a5952011-01-03 22:36:02 +00001633 }
1634
Nick Lewycky19b9f952010-07-26 16:56:01 +00001635 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001636 Invalid = true;
1637 continue;
1638 }
1639
1640 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001641 = CheckBaseSpecifier(Instantiation,
Douglas Gregor463421d2009-03-03 04:44:36 +00001642 Base->getSourceRange(),
1643 Base->isVirtual(),
1644 Base->getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001645 BaseTypeLoc,
1646 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001647 InstantiatedBases.push_back(InstantiatedBase);
1648 else
1649 Invalid = true;
1650 }
1651
Douglas Gregor2a72edd2009-03-10 18:52:44 +00001652 if (!Invalid &&
Jay Foad7d0479f2009-05-21 09:52:38 +00001653 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor463421d2009-03-03 04:44:36 +00001654 InstantiatedBases.size()))
1655 Invalid = true;
1656
1657 return Invalid;
1658}
1659
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001660/// \brief Instantiate the definition of a class from a given pattern.
1661///
1662/// \param PointOfInstantiation The point of instantiation within the
1663/// source code.
1664///
1665/// \param Instantiation is the declaration whose definition is being
1666/// instantiated. This will be either a class template specialization
1667/// or a member class of a class template specialization.
1668///
1669/// \param Pattern is the pattern from which the instantiation
1670/// occurs. This will be either the declaration of a class template or
1671/// the declaration of a member class of a class template.
1672///
1673/// \param TemplateArgs The template arguments to be substituted into
1674/// the pattern.
1675///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001676/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001677///
1678/// \param Complain whether to complain if the class cannot be instantiated due
1679/// to the lack of a definition.
1680///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001681/// \returns true if an error occurred, false otherwise.
1682bool
1683Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1684 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001685 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001686 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001687 bool Complain) {
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001688 bool Invalid = false;
John McCall87a44eb2009-08-20 01:44:21 +00001689
Mike Stump11289f42009-09-09 15:08:12 +00001690 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001691 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
John McCall54766662011-04-27 06:46:31 +00001692 if (!PatternDef || PatternDef->isBeingDefined()) {
1693 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001694 // Say nothing
John McCall54766662011-04-27 06:46:31 +00001695 } else if (PatternDef) {
1696 assert(PatternDef->isBeingDefined());
1697 Diag(PointOfInstantiation,
1698 diag::err_template_instantiate_within_definition)
1699 << (TSK != TSK_ImplicitInstantiation)
1700 << Context.getTypeDeclType(Instantiation);
1701 // Not much point in noting the template declaration here, since
1702 // we're lexically inside it.
1703 Instantiation->setInvalidDecl();
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001704 } else if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001705 Diag(PointOfInstantiation,
1706 diag::err_implicit_instantiate_member_undefined)
1707 << Context.getTypeDeclType(Instantiation);
1708 Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1709 } else {
Douglas Gregora1f49972009-05-13 00:25:59 +00001710 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001711 << (TSK != TSK_ImplicitInstantiation)
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001712 << Context.getTypeDeclType(Instantiation);
1713 Diag(Pattern->getLocation(), diag::note_template_decl_here);
1714 }
1715 return true;
1716 }
1717 Pattern = PatternDef;
1718
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001719 // \brief Record the point of instantiation.
1720 if (MemberSpecializationInfo *MSInfo
1721 = Instantiation->getMemberSpecializationInfo()) {
1722 MSInfo->setTemplateSpecializationKind(TSK);
1723 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregoref6ab412009-10-27 06:26:26 +00001724 } else if (ClassTemplateSpecializationDecl *Spec
1725 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
1726 Spec->setTemplateSpecializationKind(TSK);
1727 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001728 }
1729
Douglas Gregorf3430ae2009-03-25 21:23:52 +00001730 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001731 if (Inst)
1732 return true;
1733
1734 // Enter the scope of this instantiation. We don't use
1735 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00001736 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor17158422010-05-12 17:27:19 +00001737 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00001738 Sema::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001739
Douglas Gregor51121572010-03-24 01:33:17 +00001740 // If this is an instantiation of a local class, merge this local
1741 // instantiation scope with the enclosing scope. Otherwise, every
1742 // instantiation of a class has its own local instantiation scope.
1743 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00001744 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00001745
John McCall6602bb12010-08-01 02:01:53 +00001746 // Pull attributes from the pattern onto the instantiation.
1747 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1748
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001749 // Start the definition of this instantiation.
1750 Instantiation->startDefinition();
Douglas Gregore9029562010-05-06 00:28:52 +00001751
1752 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001753
John McCall76d824f2009-08-25 22:02:44 +00001754 // Do substitution on the base class specifiers.
1755 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001756 Invalid = true;
1757
Douglas Gregor869853e2010-11-10 19:44:59 +00001758 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
John McCall48871652010-08-21 09:40:31 +00001759 llvm::SmallVector<Decl*, 4> Fields;
Richard Smith938f40b2011-06-11 17:19:42 +00001760 llvm::SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
1761 FieldsWithMemberInitializers;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001762 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001763 MemberEnd = Pattern->decls_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001764 Member != MemberEnd; ++Member) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00001765 // Don't instantiate members not belonging in this semantic context.
1766 // e.g. for:
1767 // @code
1768 // template <int i> class A {
1769 // class B *g;
1770 // };
1771 // @endcode
1772 // 'class B' has the template as lexical context but semantically it is
1773 // introduced in namespace scope.
1774 if ((*Member)->getDeclContext() != Pattern)
1775 continue;
1776
Douglas Gregor869853e2010-11-10 19:44:59 +00001777 if ((*Member)->isInvalidDecl()) {
1778 Invalid = true;
1779 continue;
1780 }
1781
1782 Decl *NewMember = Instantiator.Visit(*Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001783 if (NewMember) {
Richard Smith938f40b2011-06-11 17:19:42 +00001784 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCall48871652010-08-21 09:40:31 +00001785 Fields.push_back(Field);
Richard Smith938f40b2011-06-11 17:19:42 +00001786 FieldDecl *OldField = cast<FieldDecl>(*Member);
1787 if (OldField->getInClassInitializer())
1788 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
1789 Field));
1790 } else if (NewMember->isInvalidDecl())
Eli Friedmand0e8de22009-12-07 00:22:08 +00001791 Invalid = true;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001792 } else {
1793 // FIXME: Eventually, a NULL return will mean that one of the
Mike Stump87c57ac2009-05-16 07:39:55 +00001794 // instantiations was a semantic disaster, and we'll want to set Invalid =
1795 // true. For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001796 }
1797 }
1798
1799 // Finish checking fields.
John McCall48871652010-08-21 09:40:31 +00001800 ActOnFields(0, Instantiation->getLocation(), Instantiation,
Jay Foad7d0479f2009-05-21 09:52:38 +00001801 Fields.data(), Fields.size(), SourceLocation(), SourceLocation(),
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001802 0);
Douglas Gregor0be31a22010-07-02 17:43:08 +00001803 CheckCompletedCXXClass(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00001804
1805 // Attach any in-class member initializers now the class is complete.
1806 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
1807 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
1808 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
1809 Expr *OldInit = OldField->getInClassInitializer();
1810 ExprResult NewInit = SubstExpr(OldInit, TemplateArgs);
1811
1812 // If the initialization is no longer dependent, check it now.
1813 if ((OldField->getType()->isDependentType() || OldInit->isTypeDependent())
1814 && !NewField->getType()->isDependentType()
1815 && !NewInit.get()->isTypeDependent()) {
1816 // FIXME: handle list-initialization
1817 SourceLocation EqualLoc = NewField->getLocation();
1818 NewInit = PerformCopyInitialization(
1819 InitializedEntity::InitializeMember(NewField), EqualLoc,
1820 NewInit.release());
1821
1822 if (!NewInit.isInvalid()) {
1823 CheckImplicitConversions(NewInit.get(), EqualLoc);
1824
1825 // C++0x [class.base.init]p7:
1826 // The initialization of each base and member constitutes a
1827 // full-expression.
1828 NewInit = MaybeCreateExprWithCleanups(NewInit);
1829 }
1830 }
1831
1832 if (NewInit.isInvalid())
1833 NewField->setInvalidDecl();
1834 else
1835 NewField->setInClassInitializer(NewInit.release());
1836 }
1837
1838 if (!FieldsWithMemberInitializers.empty())
1839 ActOnFinishDelayedMemberInitializers(Instantiation);
1840
Douglas Gregor3c74d412009-10-14 20:14:33 +00001841 if (Instantiation->isInvalidDecl())
1842 Invalid = true;
Douglas Gregor869853e2010-11-10 19:44:59 +00001843 else {
1844 // Instantiate any out-of-line class template partial
1845 // specializations now.
1846 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
1847 P = Instantiator.delayed_partial_spec_begin(),
1848 PEnd = Instantiator.delayed_partial_spec_end();
1849 P != PEnd; ++P) {
1850 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
1851 P->first,
1852 P->second)) {
1853 Invalid = true;
1854 break;
1855 }
1856 }
1857 }
1858
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001859 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00001860 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001861
Douglas Gregor88d292c2010-05-13 16:44:06 +00001862 if (!Invalid) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00001863 Consumer.HandleTagDeclDefinition(Instantiation);
1864
Douglas Gregor88d292c2010-05-13 16:44:06 +00001865 // Always emit the vtable for an explicit instantiation definition
1866 // of a polymorphic class template specialization.
1867 if (TSK == TSK_ExplicitInstantiationDefinition)
1868 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
1869 }
1870
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001871 return Invalid;
1872}
1873
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001874namespace {
1875 /// \brief A partial specialization whose template arguments have matched
1876 /// a given template-id.
1877 struct PartialSpecMatchResult {
1878 ClassTemplatePartialSpecializationDecl *Partial;
1879 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001880 };
1881}
1882
Mike Stump11289f42009-09-09 15:08:12 +00001883bool
Douglas Gregor463421d2009-03-03 04:44:36 +00001884Sema::InstantiateClassTemplateSpecialization(
Douglas Gregoref6ab412009-10-27 06:26:26 +00001885 SourceLocation PointOfInstantiation,
Douglas Gregor463421d2009-03-03 04:44:36 +00001886 ClassTemplateSpecializationDecl *ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001887 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001888 bool Complain) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001889 // Perform the actual instantiation on the canonical declaration.
1890 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00001891 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor463421d2009-03-03 04:44:36 +00001892
Douglas Gregor4aa04b12009-09-11 21:19:12 +00001893 // Check whether we have already instantiated or specialized this class
1894 // template specialization.
1895 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
1896 if (ClassTemplateSpec->getSpecializationKind() ==
1897 TSK_ExplicitInstantiationDeclaration &&
1898 TSK == TSK_ExplicitInstantiationDefinition) {
1899 // An explicit instantiation definition follows an explicit instantiation
1900 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
1901 // explicit instantiation.
1902 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor88d292c2010-05-13 16:44:06 +00001903
1904 // If this is an explicit instantiation definition, mark the
1905 // vtable as used.
1906 if (TSK == TSK_ExplicitInstantiationDefinition)
1907 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
1908
Douglas Gregor4aa04b12009-09-11 21:19:12 +00001909 return false;
1910 }
1911
1912 // We can only instantiate something that hasn't already been
1913 // instantiated or specialized. Fail without any diagnostics: our
1914 // caller will provide an error message.
Douglas Gregor463421d2009-03-03 04:44:36 +00001915 return true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00001916 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001917
Douglas Gregor00a511f2009-09-15 16:51:42 +00001918 if (ClassTemplateSpec->isInvalidDecl())
1919 return true;
1920
Douglas Gregor463421d2009-03-03 04:44:36 +00001921 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001922 CXXRecordDecl *Pattern = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00001923
Douglas Gregor170bc422009-06-12 22:31:52 +00001924 // C++ [temp.class.spec.match]p1:
1925 // When a class template is used in a context that requires an
1926 // instantiation of the class, it is necessary to determine
1927 // whether the instantiation is to be generated using the primary
1928 // template or one of the partial specializations. This is done by
1929 // matching the template arguments of the class template
1930 // specialization with the template argument lists of the partial
1931 // specializations.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001932 typedef PartialSpecMatchResult MatchResult;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001933 llvm::SmallVector<MatchResult, 4> Matched;
Douglas Gregor407e9612010-04-30 05:56:50 +00001934 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1935 Template->getPartialSpecializations(PartialSpecs);
1936 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
1937 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
John McCallbc077cf2010-02-08 23:07:23 +00001938 TemplateDeductionInfo Info(Context, PointOfInstantiation);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001939 if (TemplateDeductionResult Result
Douglas Gregor407e9612010-04-30 05:56:50 +00001940 = DeduceTemplateArguments(Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001941 ClassTemplateSpec->getTemplateArgs(),
1942 Info)) {
1943 // FIXME: Store the failed-deduction information for use in
1944 // diagnostics, later.
1945 (void)Result;
1946 } else {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001947 Matched.push_back(PartialSpecMatchResult());
1948 Matched.back().Partial = Partial;
1949 Matched.back().Args = Info.take();
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001950 }
Douglas Gregor2373c592009-05-31 09:31:02 +00001951 }
1952
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001953 // If we're dealing with a member template where the template parameters
1954 // have been instantiated, this provides the original template parameters
1955 // from which the member template's parameters were instantiated.
1956 llvm::SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
1957
Douglas Gregor21610382009-10-29 00:04:11 +00001958 if (Matched.size() >= 1) {
Douglas Gregorbe999392009-09-15 16:23:51 +00001959 llvm::SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
Douglas Gregor21610382009-10-29 00:04:11 +00001960 if (Matched.size() == 1) {
1961 // -- If exactly one matching specialization is found, the
1962 // instantiation is generated from that specialization.
1963 // We don't need to do anything for this.
1964 } else {
1965 // -- If more than one matching specialization is found, the
1966 // partial order rules (14.5.4.2) are used to determine
1967 // whether one of the specializations is more specialized
1968 // than the others. If none of the specializations is more
1969 // specialized than all of the other matching
1970 // specializations, then the use of the class template is
1971 // ambiguous and the program is ill-formed.
1972 for (llvm::SmallVector<MatchResult, 4>::iterator P = Best + 1,
1973 PEnd = Matched.end();
1974 P != PEnd; ++P) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001975 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00001976 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001977 == P->Partial)
Douglas Gregor21610382009-10-29 00:04:11 +00001978 Best = P;
Douglas Gregorbe999392009-09-15 16:23:51 +00001979 }
Douglas Gregorbe999392009-09-15 16:23:51 +00001980
Douglas Gregor21610382009-10-29 00:04:11 +00001981 // Determine if the best partial specialization is more specialized than
1982 // the others.
1983 bool Ambiguous = false;
Douglas Gregorbe999392009-09-15 16:23:51 +00001984 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
1985 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00001986 P != PEnd; ++P) {
1987 if (P != Best &&
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001988 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00001989 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001990 != Best->Partial) {
Douglas Gregor21610382009-10-29 00:04:11 +00001991 Ambiguous = true;
1992 break;
1993 }
1994 }
1995
1996 if (Ambiguous) {
1997 // Partial ordering did not produce a clear winner. Complain.
1998 ClassTemplateSpec->setInvalidDecl();
1999 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2000 << ClassTemplateSpec;
2001
2002 // Print the matching partial specializations.
2003 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2004 PEnd = Matched.end();
2005 P != PEnd; ++P)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002006 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2007 << getTemplateArgumentBindingsText(
2008 P->Partial->getTemplateParameters(),
2009 *P->Args);
Douglas Gregor01afeef2009-08-28 20:31:08 +00002010
Douglas Gregor21610382009-10-29 00:04:11 +00002011 return true;
2012 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002013 }
2014
2015 // Instantiate using the best class template partial specialization.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002016 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregor21610382009-10-29 00:04:11 +00002017 while (OrigPartialSpec->getInstantiatedFromMember()) {
2018 // If we've found an explicit specialization of this class template,
2019 // stop here and use that as the pattern.
2020 if (OrigPartialSpec->isMemberSpecialization())
2021 break;
2022
2023 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2024 }
2025
2026 Pattern = OrigPartialSpec;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002027 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor170bc422009-06-12 22:31:52 +00002028 } else {
2029 // -- If no matches are found, the instantiation is generated
2030 // from the primary template.
Douglas Gregor01afeef2009-08-28 20:31:08 +00002031 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorcf915552009-10-13 16:30:37 +00002032 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2033 // If we've found an explicit specialization of this class template,
2034 // stop here and use that as the pattern.
2035 if (OrigTemplate->isMemberSpecialization())
2036 break;
2037
Douglas Gregor01afeef2009-08-28 20:31:08 +00002038 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00002039 }
2040
Douglas Gregor01afeef2009-08-28 20:31:08 +00002041 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00002042 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002043
Douglas Gregoref6ab412009-10-27 06:26:26 +00002044 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2045 Pattern,
2046 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002047 TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002048 Complain);
Mike Stump11289f42009-09-09 15:08:12 +00002049
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002050 return Result;
Douglas Gregor463421d2009-03-03 04:44:36 +00002051}
Douglas Gregor90a1a652009-03-19 17:26:29 +00002052
John McCall76d824f2009-08-25 22:02:44 +00002053/// \brief Instantiates the definitions of all of the member
2054/// of the given class, which is an instantiation of a class template
2055/// or a member class of a template.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002056void
2057Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002058 CXXRecordDecl *Instantiation,
2059 const MultiLevelTemplateArgumentList &TemplateArgs,
2060 TemplateSpecializationKind TSK) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002061 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
2062 DEnd = Instantiation->decls_end();
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002063 D != DEnd; ++D) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002064 bool SuppressNew = false;
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002065 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002066 if (FunctionDecl *Pattern
2067 = Function->getInstantiatedFromMemberFunction()) {
2068 MemberSpecializationInfo *MSInfo
2069 = Function->getMemberSpecializationInfo();
2070 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002071 if (MSInfo->getTemplateSpecializationKind()
2072 == TSK_ExplicitSpecialization)
2073 continue;
2074
Douglas Gregor1d957a32009-10-27 18:42:08 +00002075 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2076 Function,
2077 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002078 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002079 SuppressNew) ||
2080 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002081 continue;
2082
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002083 if (Function->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002084 continue;
2085
2086 if (TSK == TSK_ExplicitInstantiationDefinition) {
2087 // C++0x [temp.explicit]p8:
2088 // An explicit instantiation definition that names a class template
2089 // specialization explicitly instantiates the class template
2090 // specialization and is only an explicit instantiation definition
2091 // of members whose definition is visible at the point of
2092 // instantiation.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002093 if (!Pattern->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002094 continue;
2095
2096 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2097
2098 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2099 } else {
2100 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2101 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002102 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002103 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00002104 if (Var->isStaticDataMember()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002105 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2106 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002107 if (MSInfo->getTemplateSpecializationKind()
2108 == TSK_ExplicitSpecialization)
2109 continue;
2110
Douglas Gregor1d957a32009-10-27 18:42:08 +00002111 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2112 Var,
2113 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002114 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002115 SuppressNew) ||
2116 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002117 continue;
2118
Douglas Gregor1d957a32009-10-27 18:42:08 +00002119 if (TSK == TSK_ExplicitInstantiationDefinition) {
2120 // C++0x [temp.explicit]p8:
2121 // An explicit instantiation definition that names a class template
2122 // specialization explicitly instantiates the class template
2123 // specialization and is only an explicit instantiation definition
2124 // of members whose definition is visible at the point of
2125 // instantiation.
2126 if (!Var->getInstantiatedFromStaticDataMember()
2127 ->getOutOfLineDefinition())
2128 continue;
2129
2130 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor86d142a2009-10-08 07:24:58 +00002131 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00002132 } else {
2133 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2134 }
2135 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002136 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
Douglas Gregor1da22252010-04-18 18:11:38 +00002137 // Always skip the injected-class-name, along with any
2138 // redeclarations of nested classes, since both would cause us
2139 // to try to instantiate the members of a class twice.
2140 if (Record->isInjectedClassName() || Record->getPreviousDeclaration())
Douglas Gregord801b062009-10-07 23:56:10 +00002141 continue;
2142
Douglas Gregor1d957a32009-10-27 18:42:08 +00002143 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2144 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002145
2146 if (MSInfo->getTemplateSpecializationKind()
2147 == TSK_ExplicitSpecialization)
2148 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00002149
Douglas Gregor1d957a32009-10-27 18:42:08 +00002150 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2151 Record,
2152 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002153 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002154 SuppressNew) ||
2155 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002156 continue;
2157
Douglas Gregor1d957a32009-10-27 18:42:08 +00002158 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2159 assert(Pattern && "Missing instantiated-from-template information");
2160
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002161 if (!Record->getDefinition()) {
2162 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002163 // C++0x [temp.explicit]p8:
2164 // An explicit instantiation definition that names a class template
2165 // specialization explicitly instantiates the class template
2166 // specialization and is only an explicit instantiation definition
2167 // of members whose definition is visible at the point of
2168 // instantiation.
2169 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2170 MSInfo->setTemplateSpecializationKind(TSK);
2171 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2172 }
2173
2174 continue;
2175 }
2176
2177 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002178 TemplateArgs,
2179 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002180 } else {
2181 if (TSK == TSK_ExplicitInstantiationDefinition &&
2182 Record->getTemplateSpecializationKind() ==
2183 TSK_ExplicitInstantiationDeclaration) {
2184 Record->setTemplateSpecializationKind(TSK);
2185 MarkVTableUsed(PointOfInstantiation, Record, true);
2186 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002187 }
Douglas Gregorc093c1d2009-10-08 01:19:17 +00002188
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002189 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002190 if (Pattern)
2191 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2192 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002193 }
2194 }
2195}
2196
2197/// \brief Instantiate the definitions of all of the members of the
2198/// given class template specialization, which was named as part of an
2199/// explicit instantiation.
Mike Stump11289f42009-09-09 15:08:12 +00002200void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002201Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002202 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002203 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2204 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002205 // C++0x [temp.explicit]p7:
2206 // An explicit instantiation that names a class template
2207 // specialization is an explicit instantion of the same kind
2208 // (declaration or definition) of each of its members (not
2209 // including members inherited from base classes) that has not
2210 // been previously explicitly specialized in the translation unit
2211 // containing the explicit instantiation, except as described
2212 // below.
2213 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002214 getTemplateInstantiationArgs(ClassTemplateSpec),
2215 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002216}
2217
John McCalldadc5752010-08-24 06:29:42 +00002218StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002219Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002220 if (!S)
2221 return Owned(S);
2222
2223 TemplateInstantiator Instantiator(*this, TemplateArgs,
2224 SourceLocation(),
2225 DeclarationName());
2226 return Instantiator.TransformStmt(S);
2227}
2228
John McCalldadc5752010-08-24 06:29:42 +00002229ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002230Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002231 if (!E)
2232 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002233
Douglas Gregora16548e2009-08-11 05:31:07 +00002234 TemplateInstantiator Instantiator(*this, TemplateArgs,
2235 SourceLocation(),
2236 DeclarationName());
2237 return Instantiator.TransformExpr(E);
2238}
2239
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002240bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2241 const MultiLevelTemplateArgumentList &TemplateArgs,
2242 llvm::SmallVectorImpl<Expr *> &Outputs) {
2243 if (NumExprs == 0)
2244 return false;
2245
2246 TemplateInstantiator Instantiator(*this, TemplateArgs,
2247 SourceLocation(),
2248 DeclarationName());
2249 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2250}
2251
Douglas Gregor14454802011-02-25 02:25:35 +00002252NestedNameSpecifierLoc
2253Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2254 const MultiLevelTemplateArgumentList &TemplateArgs) {
2255 if (!NNS)
2256 return NestedNameSpecifierLoc();
2257
2258 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2259 DeclarationName());
2260 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2261}
2262
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002263/// \brief Do template substitution on declaration name info.
2264DeclarationNameInfo
2265Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2266 const MultiLevelTemplateArgumentList &TemplateArgs) {
2267 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2268 NameInfo.getName());
2269 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2270}
2271
Douglas Gregoraa594892009-03-31 18:38:02 +00002272TemplateName
Douglas Gregordf846d12011-03-02 18:46:51 +00002273Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2274 TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002275 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002276 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2277 DeclarationName());
Douglas Gregordf846d12011-03-02 18:46:51 +00002278 CXXScopeSpec SS;
2279 SS.Adopt(QualifierLoc);
2280 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregoraa594892009-03-31 18:38:02 +00002281}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002282
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002283bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2284 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002285 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002286 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2287 DeclarationName());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002288
2289 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00002290}
Douglas Gregor14cf7522010-04-30 18:55:50 +00002291
Douglas Gregorf3010112011-01-07 16:43:16 +00002292llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2293LocalInstantiationScope::findInstantiationOf(const Decl *D) {
Chris Lattnercab02a62011-02-17 20:34:02 +00002294 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002295 Current = Current->Outer) {
Chris Lattnercab02a62011-02-17 20:34:02 +00002296
Douglas Gregor14cf7522010-04-30 18:55:50 +00002297 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002298 const Decl *CheckD = D;
2299 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00002300 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002301 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00002302 return &Found->second;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002303
2304 // If this is a tag declaration, it's possible that we need to look for
2305 // a previous declaration.
2306 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2307 CheckD = Tag->getPreviousDeclaration();
2308 else
2309 CheckD = 0;
2310 } while (CheckD);
2311
Douglas Gregor14cf7522010-04-30 18:55:50 +00002312 // If we aren't combined with our outer scope, we're done.
2313 if (!Current->CombineWithOuterScope)
2314 break;
2315 }
Chris Lattnercab02a62011-02-17 20:34:02 +00002316
2317 // If we didn't find the decl, then we either have a sema bug, or we have a
2318 // forward reference to a label declaration. Return null to indicate that
2319 // we have an uninstantiated label.
2320 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Douglas Gregor14cf7522010-04-30 18:55:50 +00002321 return 0;
2322}
2323
John McCall19c1bfd2010-08-25 05:32:35 +00002324void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
Douglas Gregorf3010112011-01-07 16:43:16 +00002325 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002326 if (Stored.isNull())
2327 Stored = Inst;
2328 else if (Stored.is<Decl *>()) {
2329 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2330 Stored = Inst;
2331 } else
2332 LocalDecls[D].get<DeclArgumentPack *>()->push_back(Inst);
Douglas Gregor14cf7522010-04-30 18:55:50 +00002333}
Douglas Gregorf3010112011-01-07 16:43:16 +00002334
2335void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2336 Decl *Inst) {
2337 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2338 Pack->push_back(Inst);
2339}
2340
2341void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2342 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2343 assert(Stored.isNull() && "Already instantiated this local");
2344 DeclArgumentPack *Pack = new DeclArgumentPack;
2345 Stored = Pack;
2346 ArgumentPacks.push_back(Pack);
2347}
2348
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002349void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2350 const TemplateArgument *ExplicitArgs,
2351 unsigned NumExplicitArgs) {
2352 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2353 "Already have a partially-substituted pack");
2354 assert((!PartiallySubstitutedPack
2355 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2356 "Wrong number of arguments in partially-substituted pack");
2357 PartiallySubstitutedPack = Pack;
2358 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2359 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2360}
2361
2362NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2363 const TemplateArgument **ExplicitArgs,
2364 unsigned *NumExplicitArgs) const {
2365 if (ExplicitArgs)
2366 *ExplicitArgs = 0;
2367 if (NumExplicitArgs)
2368 *NumExplicitArgs = 0;
2369
2370 for (const LocalInstantiationScope *Current = this; Current;
2371 Current = Current->Outer) {
2372 if (Current->PartiallySubstitutedPack) {
2373 if (ExplicitArgs)
2374 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2375 if (NumExplicitArgs)
2376 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2377
2378 return Current->PartiallySubstitutedPack;
2379 }
2380
2381 if (!Current->CombineWithOuterScope)
2382 break;
2383 }
2384
2385 return 0;
2386}